babylon.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649
  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. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  180. */
  181. this.onCompileObservable = new BABYLON.Observable();
  182. /**
  183. * Observable that will be called if an error occurs during shader compilation.
  184. */
  185. this.onErrorObservable = new BABYLON.Observable();
  186. /** @hidden */
  187. this._bonesComputationForcedToCPU = false;
  188. this._uniformBuffersNames = {};
  189. this._isReady = false;
  190. this._compilationError = "";
  191. this.name = baseName;
  192. if (attributesNamesOrOptions.attributes) {
  193. var options = attributesNamesOrOptions;
  194. this._engine = uniformsNamesOrEngine;
  195. this._attributesNames = options.attributes;
  196. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  197. this._samplers = options.samplers.slice();
  198. this.defines = options.defines;
  199. this.onError = options.onError;
  200. this.onCompiled = options.onCompiled;
  201. this._fallbacks = options.fallbacks;
  202. this._indexParameters = options.indexParameters;
  203. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  204. if (options.uniformBuffersNames) {
  205. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  206. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  207. }
  208. }
  209. }
  210. else {
  211. this._engine = engine;
  212. this.defines = defines;
  213. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  214. this._samplers = samplers ? samplers.slice() : [];
  215. this._attributesNames = attributesNamesOrOptions;
  216. this.onError = onError;
  217. this.onCompiled = onCompiled;
  218. this._indexParameters = indexParameters;
  219. this._fallbacks = fallbacks;
  220. }
  221. this.uniqueId = Effect._uniqueIdSeed++;
  222. var vertexSource;
  223. var fragmentSource;
  224. if (baseName.vertexElement) {
  225. vertexSource = document.getElementById(baseName.vertexElement);
  226. if (!vertexSource) {
  227. vertexSource = baseName.vertexElement;
  228. }
  229. }
  230. else {
  231. vertexSource = baseName.vertex || baseName;
  232. }
  233. if (baseName.fragmentElement) {
  234. fragmentSource = document.getElementById(baseName.fragmentElement);
  235. if (!fragmentSource) {
  236. fragmentSource = baseName.fragmentElement;
  237. }
  238. }
  239. else {
  240. fragmentSource = baseName.fragment || baseName;
  241. }
  242. this._loadVertexShader(vertexSource, function (vertexCode) {
  243. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  244. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  245. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  246. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  247. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  248. if (baseName) {
  249. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  250. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  251. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  252. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  253. }
  254. else {
  255. _this._vertexSourceCode = migratedVertexCode;
  256. _this._fragmentSourceCode = migratedFragmentCode;
  257. }
  258. _this._prepareEffect();
  259. });
  260. });
  261. });
  262. });
  263. });
  264. });
  265. }
  266. Object.defineProperty(Effect.prototype, "onBindObservable", {
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. get: function () {
  271. if (!this._onBindObservable) {
  272. this._onBindObservable = new BABYLON.Observable();
  273. }
  274. return this._onBindObservable;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. Object.defineProperty(Effect.prototype, "key", {
  280. /**
  281. * Unique key for this effect
  282. */
  283. get: function () {
  284. return this._key;
  285. },
  286. enumerable: true,
  287. configurable: true
  288. });
  289. /**
  290. * If the effect has been compiled and prepared.
  291. * @returns if the effect is compiled and prepared.
  292. */
  293. Effect.prototype.isReady = function () {
  294. if (!this._isReady && this._program && this._program.isParallelCompiled) {
  295. return this._engine._isProgramCompiled(this._program);
  296. }
  297. return this._isReady;
  298. };
  299. /**
  300. * The engine the effect was initialized with.
  301. * @returns the engine.
  302. */
  303. Effect.prototype.getEngine = function () {
  304. return this._engine;
  305. };
  306. /**
  307. * The compiled webGL program for the effect
  308. * @returns the webGL program.
  309. */
  310. Effect.prototype.getProgram = function () {
  311. return this._program;
  312. };
  313. /**
  314. * The set of names of attribute variables for the shader.
  315. * @returns An array of attribute names.
  316. */
  317. Effect.prototype.getAttributesNames = function () {
  318. return this._attributesNames;
  319. };
  320. /**
  321. * Returns the attribute at the given index.
  322. * @param index The index of the attribute.
  323. * @returns The location of the attribute.
  324. */
  325. Effect.prototype.getAttributeLocation = function (index) {
  326. return this._attributes[index];
  327. };
  328. /**
  329. * Returns the attribute based on the name of the variable.
  330. * @param name of the attribute to look up.
  331. * @returns the attribute location.
  332. */
  333. Effect.prototype.getAttributeLocationByName = function (name) {
  334. var index = this._attributesNames.indexOf(name);
  335. return this._attributes[index];
  336. };
  337. /**
  338. * The number of attributes.
  339. * @returns the numnber of attributes.
  340. */
  341. Effect.prototype.getAttributesCount = function () {
  342. return this._attributes.length;
  343. };
  344. /**
  345. * Gets the index of a uniform variable.
  346. * @param uniformName of the uniform to look up.
  347. * @returns the index.
  348. */
  349. Effect.prototype.getUniformIndex = function (uniformName) {
  350. return this._uniformsNames.indexOf(uniformName);
  351. };
  352. /**
  353. * Returns the attribute based on the name of the variable.
  354. * @param uniformName of the uniform to look up.
  355. * @returns the location of the uniform.
  356. */
  357. Effect.prototype.getUniform = function (uniformName) {
  358. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  359. };
  360. /**
  361. * Returns an array of sampler variable names
  362. * @returns The array of sampler variable neames.
  363. */
  364. Effect.prototype.getSamplers = function () {
  365. return this._samplers;
  366. };
  367. /**
  368. * The error from the last compilation.
  369. * @returns the error string.
  370. */
  371. Effect.prototype.getCompilationError = function () {
  372. return this._compilationError;
  373. };
  374. /**
  375. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  376. * @param func The callback to be used.
  377. */
  378. Effect.prototype.executeWhenCompiled = function (func) {
  379. var _this = this;
  380. if (this.isReady()) {
  381. func(this);
  382. return;
  383. }
  384. this.onCompileObservable.add(function (effect) {
  385. func(effect);
  386. });
  387. if (!this._program || this._program.isParallelCompiled) {
  388. setTimeout(function () {
  389. _this._checkIsReady();
  390. }, 16);
  391. }
  392. };
  393. Effect.prototype._checkIsReady = function () {
  394. var _this = this;
  395. if (this.isReady()) {
  396. return;
  397. }
  398. setTimeout(function () {
  399. _this._checkIsReady();
  400. }, 16);
  401. };
  402. /** @hidden */
  403. Effect.prototype._loadVertexShader = function (vertex, callback) {
  404. if (BABYLON.Tools.IsWindowObjectExist()) {
  405. // DOM element ?
  406. if (vertex instanceof HTMLElement) {
  407. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  408. callback(vertexCode);
  409. return;
  410. }
  411. }
  412. // Base64 encoded ?
  413. if (vertex.substr(0, 7) === "base64:") {
  414. var vertexBinary = window.atob(vertex.substr(7));
  415. callback(vertexBinary);
  416. return;
  417. }
  418. // Is in local store ?
  419. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  420. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  421. return;
  422. }
  423. var vertexShaderUrl;
  424. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  425. vertexShaderUrl = vertex;
  426. }
  427. else {
  428. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  429. }
  430. // Vertex shader
  431. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  432. };
  433. /** @hidden */
  434. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  435. if (BABYLON.Tools.IsWindowObjectExist()) {
  436. // DOM element ?
  437. if (fragment instanceof HTMLElement) {
  438. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  439. callback(fragmentCode);
  440. return;
  441. }
  442. }
  443. // Base64 encoded ?
  444. if (fragment.substr(0, 7) === "base64:") {
  445. var fragmentBinary = window.atob(fragment.substr(7));
  446. callback(fragmentBinary);
  447. return;
  448. }
  449. // Is in local store ?
  450. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  451. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  452. return;
  453. }
  454. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  455. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  456. return;
  457. }
  458. var fragmentShaderUrl;
  459. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  460. fragmentShaderUrl = fragment;
  461. }
  462. else {
  463. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  464. }
  465. // Fragment shader
  466. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  467. };
  468. /** @hidden */
  469. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  470. // Rebuild shaders source code
  471. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  472. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  473. vertexCode = prefix + vertexCode;
  474. fragmentCode = prefix + fragmentCode;
  475. // Number lines of shaders source code
  476. var i = 2;
  477. var regex = /\n/gm;
  478. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  479. i = 2;
  480. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  481. // Dump shaders name and formatted source code
  482. if (this.name.vertexElement) {
  483. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  484. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  485. }
  486. else if (this.name.vertex) {
  487. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  488. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  489. }
  490. else {
  491. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  492. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  493. }
  494. };
  495. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  496. var preparedSourceCode = this._processPrecision(sourceCode);
  497. if (this._engine.webGLVersion == 1) {
  498. callback(preparedSourceCode);
  499. return;
  500. }
  501. // Already converted
  502. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  503. callback(preparedSourceCode.replace("#version 300 es", ""));
  504. return;
  505. }
  506. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  507. // Remove extensions
  508. // #extension GL_OES_standard_derivatives : enable
  509. // #extension GL_EXT_shader_texture_lod : enable
  510. // #extension GL_EXT_frag_depth : enable
  511. // #extension GL_EXT_draw_buffers : require
  512. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  513. var result = preparedSourceCode.replace(regex, "");
  514. // Migrate to GLSL v300
  515. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  516. result = result.replace(/attribute[ \t]/g, "in ");
  517. result = result.replace(/[ \t]attribute/g, " in");
  518. if (isFragment) {
  519. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  520. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  521. result = result.replace(/texture2D\s*\(/g, "texture(");
  522. result = result.replace(/textureCube\s*\(/g, "texture(");
  523. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  524. result = result.replace(/gl_FragColor/g, "glFragColor");
  525. result = result.replace(/gl_FragData/g, "glFragData");
  526. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  527. }
  528. callback(result);
  529. };
  530. Effect.prototype._processIncludes = function (sourceCode, callback) {
  531. var _this = this;
  532. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  533. var match = regex.exec(sourceCode);
  534. var returnValue = new String(sourceCode);
  535. while (match != null) {
  536. var includeFile = match[1];
  537. // Uniform declaration
  538. if (includeFile.indexOf("__decl__") !== -1) {
  539. includeFile = includeFile.replace(/__decl__/, "");
  540. if (this._engine.supportsUniformBuffers) {
  541. includeFile = includeFile.replace(/Vertex/, "Ubo");
  542. includeFile = includeFile.replace(/Fragment/, "Ubo");
  543. }
  544. includeFile = includeFile + "Declaration";
  545. }
  546. if (Effect.IncludesShadersStore[includeFile]) {
  547. // Substitution
  548. var includeContent = Effect.IncludesShadersStore[includeFile];
  549. if (match[2]) {
  550. var splits = match[3].split(",");
  551. for (var index = 0; index < splits.length; index += 2) {
  552. var source = new RegExp(splits[index], "g");
  553. var dest = splits[index + 1];
  554. includeContent = includeContent.replace(source, dest);
  555. }
  556. }
  557. if (match[4]) {
  558. var indexString = match[5];
  559. if (indexString.indexOf("..") !== -1) {
  560. var indexSplits = indexString.split("..");
  561. var minIndex = parseInt(indexSplits[0]);
  562. var maxIndex = parseInt(indexSplits[1]);
  563. var sourceIncludeContent = includeContent.slice(0);
  564. includeContent = "";
  565. if (isNaN(maxIndex)) {
  566. maxIndex = this._indexParameters[indexSplits[1]];
  567. }
  568. for (var i = minIndex; i < maxIndex; i++) {
  569. if (!this._engine.supportsUniformBuffers) {
  570. // Ubo replacement
  571. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  572. return p1 + "{X}";
  573. });
  574. }
  575. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  576. }
  577. }
  578. else {
  579. if (!this._engine.supportsUniformBuffers) {
  580. // Ubo replacement
  581. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  582. return p1 + "{X}";
  583. });
  584. }
  585. includeContent = includeContent.replace(/\{X\}/g, indexString);
  586. }
  587. }
  588. // Replace
  589. returnValue = returnValue.replace(match[0], includeContent);
  590. }
  591. else {
  592. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  593. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  594. Effect.IncludesShadersStore[includeFile] = fileContent;
  595. _this._processIncludes(returnValue, callback);
  596. });
  597. return;
  598. }
  599. match = regex.exec(sourceCode);
  600. }
  601. callback(returnValue);
  602. };
  603. Effect.prototype._processPrecision = function (source) {
  604. if (source.indexOf("precision highp float") === -1) {
  605. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  606. source = "precision mediump float;\n" + source;
  607. }
  608. else {
  609. source = "precision highp float;\n" + source;
  610. }
  611. }
  612. else {
  613. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  614. source = source.replace("precision highp float", "precision mediump float");
  615. }
  616. }
  617. return source;
  618. };
  619. /**
  620. * Recompiles the webGL program
  621. * @param vertexSourceCode The source code for the vertex shader.
  622. * @param fragmentSourceCode The source code for the fragment shader.
  623. * @param onCompiled Callback called when completed.
  624. * @param onError Callback called on error.
  625. * @hidden
  626. */
  627. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  628. var _this = this;
  629. this._isReady = false;
  630. this._vertexSourceCodeOverride = vertexSourceCode;
  631. this._fragmentSourceCodeOverride = fragmentSourceCode;
  632. this.onError = function (effect, error) {
  633. if (onError) {
  634. onError(error);
  635. }
  636. };
  637. this.onCompiled = function () {
  638. var scenes = _this.getEngine().scenes;
  639. for (var i = 0; i < scenes.length; i++) {
  640. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  641. }
  642. if (onCompiled) {
  643. onCompiled(_this._program);
  644. }
  645. };
  646. this._fallbacks = null;
  647. this._prepareEffect();
  648. };
  649. /**
  650. * Gets the uniform locations of the the specified variable names
  651. * @param names THe names of the variables to lookup.
  652. * @returns Array of locations in the same order as variable names.
  653. */
  654. Effect.prototype.getSpecificUniformLocations = function (names) {
  655. var engine = this._engine;
  656. return engine.getUniforms(this._program, names);
  657. };
  658. /**
  659. * Prepares the effect
  660. * @hidden
  661. */
  662. Effect.prototype._prepareEffect = function () {
  663. var _this = this;
  664. var attributesNames = this._attributesNames;
  665. var defines = this.defines;
  666. var fallbacks = this._fallbacks;
  667. this._valueCache = {};
  668. var previousProgram = this._program;
  669. try {
  670. var engine_1 = this._engine;
  671. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  672. this._program = engine_1.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  673. }
  674. else {
  675. this._program = engine_1.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  676. }
  677. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  678. engine_1._executeWhenProgramIsCompiled(this._program, function () {
  679. if (engine_1.supportsUniformBuffers) {
  680. for (var name in _this._uniformBuffersNames) {
  681. _this.bindUniformBlock(name, _this._uniformBuffersNames[name]);
  682. }
  683. }
  684. _this._uniforms = engine_1.getUniforms(_this._program, _this._uniformsNames);
  685. _this._attributes = engine_1.getAttributes(_this._program, attributesNames);
  686. var index;
  687. for (index = 0; index < _this._samplers.length; index++) {
  688. var sampler = _this.getUniform(_this._samplers[index]);
  689. if (sampler == null) {
  690. _this._samplers.splice(index, 1);
  691. index--;
  692. }
  693. }
  694. engine_1.bindSamplers(_this);
  695. _this._compilationError = "";
  696. _this._isReady = true;
  697. if (_this.onCompiled) {
  698. _this.onCompiled(_this);
  699. }
  700. _this.onCompileObservable.notifyObservers(_this);
  701. _this.onCompileObservable.clear();
  702. // Unbind mesh reference in fallbacks
  703. if (_this._fallbacks) {
  704. _this._fallbacks.unBindMesh();
  705. }
  706. if (previousProgram) {
  707. _this.getEngine()._deleteProgram(previousProgram);
  708. }
  709. });
  710. if (this._program.isParallelCompiled) {
  711. this._checkIsReady();
  712. }
  713. }
  714. catch (e) {
  715. this._compilationError = e.message;
  716. // Let's go through fallbacks then
  717. BABYLON.Tools.Error("Unable to compile effect:");
  718. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  719. return " " + uniform;
  720. }));
  721. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  722. return " " + attribute;
  723. }));
  724. BABYLON.Tools.Error("Error: " + this._compilationError);
  725. if (previousProgram) {
  726. this._program = previousProgram;
  727. this._isReady = true;
  728. if (this.onError) {
  729. this.onError(this, this._compilationError);
  730. }
  731. this.onErrorObservable.notifyObservers(this);
  732. }
  733. if (fallbacks && fallbacks.isMoreFallbacks) {
  734. BABYLON.Tools.Error("Trying next fallback.");
  735. this.defines = fallbacks.reduce(this.defines, this);
  736. this._prepareEffect();
  737. }
  738. else { // Sorry we did everything we can
  739. if (this.onError) {
  740. this.onError(this, this._compilationError);
  741. }
  742. this.onErrorObservable.notifyObservers(this);
  743. this.onErrorObservable.clear();
  744. // Unbind mesh reference in fallbacks
  745. if (this._fallbacks) {
  746. this._fallbacks.unBindMesh();
  747. }
  748. }
  749. }
  750. };
  751. Object.defineProperty(Effect.prototype, "isSupported", {
  752. /**
  753. * Checks if the effect is supported. (Must be called after compilation)
  754. */
  755. get: function () {
  756. return this._compilationError === "";
  757. },
  758. enumerable: true,
  759. configurable: true
  760. });
  761. /**
  762. * Binds a texture to the engine to be used as output of the shader.
  763. * @param channel Name of the output variable.
  764. * @param texture Texture to bind.
  765. * @hidden
  766. */
  767. Effect.prototype._bindTexture = function (channel, texture) {
  768. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  769. };
  770. /**
  771. * Sets a texture on the engine to be used in the shader.
  772. * @param channel Name of the sampler variable.
  773. * @param texture Texture to set.
  774. */
  775. Effect.prototype.setTexture = function (channel, texture) {
  776. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  777. };
  778. /**
  779. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  780. * @param channel Name of the sampler variable.
  781. * @param texture Texture to set.
  782. */
  783. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  784. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  785. };
  786. /**
  787. * Sets an array of textures on the engine to be used in the shader.
  788. * @param channel Name of the variable.
  789. * @param textures Textures to set.
  790. */
  791. Effect.prototype.setTextureArray = function (channel, textures) {
  792. if (this._samplers.indexOf(channel + "Ex") === -1) {
  793. var initialPos = this._samplers.indexOf(channel);
  794. for (var index = 1; index < textures.length; index++) {
  795. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  796. }
  797. }
  798. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  799. };
  800. /**
  801. * 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)
  802. * @param channel Name of the sampler variable.
  803. * @param postProcess Post process to get the input texture from.
  804. */
  805. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  806. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  807. };
  808. /**
  809. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  810. * 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)
  811. * @param channel Name of the sampler variable.
  812. * @param postProcess Post process to get the output texture from.
  813. */
  814. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  815. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  816. };
  817. /** @hidden */
  818. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  819. var cache = this._valueCache[uniformName];
  820. var flag = matrix.updateFlag;
  821. if (cache !== undefined && cache === flag) {
  822. return false;
  823. }
  824. this._valueCache[uniformName] = flag;
  825. return true;
  826. };
  827. /** @hidden */
  828. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  829. var cache = this._valueCache[uniformName];
  830. if (!cache) {
  831. cache = [x, y];
  832. this._valueCache[uniformName] = cache;
  833. return true;
  834. }
  835. var changed = false;
  836. if (cache[0] !== x) {
  837. cache[0] = x;
  838. changed = true;
  839. }
  840. if (cache[1] !== y) {
  841. cache[1] = y;
  842. changed = true;
  843. }
  844. return changed;
  845. };
  846. /** @hidden */
  847. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  848. var cache = this._valueCache[uniformName];
  849. if (!cache) {
  850. cache = [x, y, z];
  851. this._valueCache[uniformName] = cache;
  852. return true;
  853. }
  854. var changed = false;
  855. if (cache[0] !== x) {
  856. cache[0] = x;
  857. changed = true;
  858. }
  859. if (cache[1] !== y) {
  860. cache[1] = y;
  861. changed = true;
  862. }
  863. if (cache[2] !== z) {
  864. cache[2] = z;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /** @hidden */
  870. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  871. var cache = this._valueCache[uniformName];
  872. if (!cache) {
  873. cache = [x, y, z, w];
  874. this._valueCache[uniformName] = cache;
  875. return true;
  876. }
  877. var changed = false;
  878. if (cache[0] !== x) {
  879. cache[0] = x;
  880. changed = true;
  881. }
  882. if (cache[1] !== y) {
  883. cache[1] = y;
  884. changed = true;
  885. }
  886. if (cache[2] !== z) {
  887. cache[2] = z;
  888. changed = true;
  889. }
  890. if (cache[3] !== w) {
  891. cache[3] = w;
  892. changed = true;
  893. }
  894. return changed;
  895. };
  896. /**
  897. * Binds a buffer to a uniform.
  898. * @param buffer Buffer to bind.
  899. * @param name Name of the uniform variable to bind to.
  900. */
  901. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  902. var bufferName = this._uniformBuffersNames[name];
  903. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  904. return;
  905. }
  906. Effect._baseCache[bufferName] = buffer;
  907. this._engine.bindUniformBufferBase(buffer, bufferName);
  908. };
  909. /**
  910. * Binds block to a uniform.
  911. * @param blockName Name of the block to bind.
  912. * @param index Index to bind.
  913. */
  914. Effect.prototype.bindUniformBlock = function (blockName, index) {
  915. this._engine.bindUniformBlock(this._program, blockName, index);
  916. };
  917. /**
  918. * Sets an interger value on a uniform variable.
  919. * @param uniformName Name of the variable.
  920. * @param value Value to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setInt = function (uniformName, value) {
  924. var cache = this._valueCache[uniformName];
  925. if (cache !== undefined && cache === value) {
  926. return this;
  927. }
  928. this._valueCache[uniformName] = value;
  929. this._engine.setInt(this.getUniform(uniformName), value);
  930. return this;
  931. };
  932. /**
  933. * Sets an int array on a uniform variable.
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setIntArray = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setIntArray(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setIntArray2 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setIntArray2(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * 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)
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setIntArray3 = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setIntArray3(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * 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)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setIntArray4 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setIntArray4(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an float array on a uniform variable.
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setFloatArray = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setFloatArray(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * 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)
  1000. * @param uniformName Name of the variable.
  1001. * @param array array to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1005. this._valueCache[uniformName] = null;
  1006. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1007. return this;
  1008. };
  1009. /**
  1010. * 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)
  1011. * @param uniformName Name of the variable.
  1012. * @param array array to be set.
  1013. * @returns this effect.
  1014. */
  1015. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1016. this._valueCache[uniformName] = null;
  1017. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1018. return this;
  1019. };
  1020. /**
  1021. * Sets an array on a uniform variable.
  1022. * @param uniformName Name of the variable.
  1023. * @param array array to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setArray = function (uniformName, array) {
  1027. this._valueCache[uniformName] = null;
  1028. this._engine.setArray(this.getUniform(uniformName), array);
  1029. return this;
  1030. };
  1031. /**
  1032. * 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)
  1033. * @param uniformName Name of the variable.
  1034. * @param array array to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setArray2 = function (uniformName, array) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setArray2(this.getUniform(uniformName), array);
  1040. return this;
  1041. };
  1042. /**
  1043. * 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)
  1044. * @param uniformName Name of the variable.
  1045. * @param array array to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setArray3 = function (uniformName, array) {
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setArray3(this.getUniform(uniformName), array);
  1051. return this;
  1052. };
  1053. /**
  1054. * 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)
  1055. * @param uniformName Name of the variable.
  1056. * @param array array to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setArray4 = function (uniformName, array) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setArray4(this.getUniform(uniformName), array);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets matrices on a uniform variable.
  1066. * @param uniformName Name of the variable.
  1067. * @param matrices matrices to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1071. if (!matrices) {
  1072. return this;
  1073. }
  1074. this._valueCache[uniformName] = null;
  1075. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1076. return this;
  1077. };
  1078. /**
  1079. * Sets matrix on a uniform variable.
  1080. * @param uniformName Name of the variable.
  1081. * @param matrix matrix to be set.
  1082. * @returns this effect.
  1083. */
  1084. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1085. if (this._cacheMatrix(uniformName, matrix)) {
  1086. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1087. }
  1088. return this;
  1089. };
  1090. /**
  1091. * 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)
  1092. * @param uniformName Name of the variable.
  1093. * @param matrix matrix to be set.
  1094. * @returns this effect.
  1095. */
  1096. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1097. this._valueCache[uniformName] = null;
  1098. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1103. * @param uniformName Name of the variable.
  1104. * @param matrix matrix to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1108. this._valueCache[uniformName] = null;
  1109. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a float on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param value value to be set.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat = function (uniformName, value) {
  1119. var cache = this._valueCache[uniformName];
  1120. if (cache !== undefined && cache === value) {
  1121. return this;
  1122. }
  1123. this._valueCache[uniformName] = value;
  1124. this._engine.setFloat(this.getUniform(uniformName), value);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a boolean on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param bool value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setBool = function (uniformName, bool) {
  1134. var cache = this._valueCache[uniformName];
  1135. if (cache !== undefined && cache === bool) {
  1136. return this;
  1137. }
  1138. this._valueCache[uniformName] = bool;
  1139. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1140. return this;
  1141. };
  1142. /**
  1143. * Sets a Vector2 on a uniform variable.
  1144. * @param uniformName Name of the variable.
  1145. * @param vector2 vector2 to be set.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1149. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1150. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float2 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param x First float in float2.
  1158. * @param y Second float in float2.
  1159. * @returns this effect.
  1160. */
  1161. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1162. if (this._cacheFloat2(uniformName, x, y)) {
  1163. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1164. }
  1165. return this;
  1166. };
  1167. /**
  1168. * Sets a Vector3 on a uniform variable.
  1169. * @param uniformName Name of the variable.
  1170. * @param vector3 Value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1174. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1175. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a float3 on a uniform variable.
  1181. * @param uniformName Name of the variable.
  1182. * @param x First float in float3.
  1183. * @param y Second float in float3.
  1184. * @param z Third float in float3.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1188. if (this._cacheFloat3(uniformName, x, y, z)) {
  1189. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Vector4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param vector4 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1200. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1201. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a float4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param x First float in float4.
  1209. * @param y Second float in float4.
  1210. * @param z Third float in float4.
  1211. * @param w Fourth float in float4.
  1212. * @returns this effect.
  1213. */
  1214. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1215. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1216. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1217. }
  1218. return this;
  1219. };
  1220. /**
  1221. * Sets a Color3 on a uniform variable.
  1222. * @param uniformName Name of the variable.
  1223. * @param color3 Value to be set.
  1224. * @returns this effect.
  1225. */
  1226. Effect.prototype.setColor3 = function (uniformName, color3) {
  1227. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1228. this._engine.setColor3(this.getUniform(uniformName), color3);
  1229. }
  1230. return this;
  1231. };
  1232. /**
  1233. * Sets a Color4 on a uniform variable.
  1234. * @param uniformName Name of the variable.
  1235. * @param color3 Value to be set.
  1236. * @param alpha Alpha value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1240. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1241. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a Color4 on a uniform variable
  1247. * @param uniformName defines the name of the variable
  1248. * @param color4 defines the value to be set
  1249. * @returns this effect.
  1250. */
  1251. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1252. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1253. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1254. }
  1255. return this;
  1256. };
  1257. /**
  1258. * This function will add a new shader to the shader store
  1259. * @param name the name of the shader
  1260. * @param pixelShader optional pixel shader content
  1261. * @param vertexShader optional vertex shader content
  1262. */
  1263. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1264. if (pixelShader) {
  1265. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1266. }
  1267. if (vertexShader) {
  1268. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1269. }
  1270. };
  1271. /**
  1272. * Resets the cache of effects.
  1273. */
  1274. Effect.ResetCache = function () {
  1275. Effect._baseCache = {};
  1276. };
  1277. Effect._uniqueIdSeed = 0;
  1278. Effect._baseCache = {};
  1279. /**
  1280. * Store of each shader (The can be looked up using effect.key)
  1281. */
  1282. Effect.ShadersStore = {};
  1283. /**
  1284. * Store of each included file for a shader (The can be looked up using effect.key)
  1285. */
  1286. Effect.IncludesShadersStore = {};
  1287. return Effect;
  1288. }());
  1289. BABYLON.Effect = Effect;
  1290. })(BABYLON || (BABYLON = {}));
  1291. //# sourceMappingURL=babylon.effect.js.map
  1292. //# sourceMappingURL=babylon.types.js.map
  1293. var BABYLON;
  1294. (function (BABYLON) {
  1295. /**
  1296. * Gather the list of keyboard event types as constants.
  1297. */
  1298. var KeyboardEventTypes = /** @class */ (function () {
  1299. function KeyboardEventTypes() {
  1300. }
  1301. /**
  1302. * The keydown event is fired when a key becomes active (pressed).
  1303. */
  1304. KeyboardEventTypes.KEYDOWN = 0x01;
  1305. /**
  1306. * The keyup event is fired when a key has been released.
  1307. */
  1308. KeyboardEventTypes.KEYUP = 0x02;
  1309. return KeyboardEventTypes;
  1310. }());
  1311. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1312. /**
  1313. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1314. */
  1315. var KeyboardInfo = /** @class */ (function () {
  1316. /**
  1317. * Instantiates a new keyboard info.
  1318. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfo(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. this.type = type;
  1332. this.event = event;
  1333. }
  1334. return KeyboardInfo;
  1335. }());
  1336. BABYLON.KeyboardInfo = KeyboardInfo;
  1337. /**
  1338. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1339. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1340. */
  1341. var KeyboardInfoPre = /** @class */ (function (_super) {
  1342. __extends(KeyboardInfoPre, _super);
  1343. /**
  1344. * Instantiates a new keyboard pre info.
  1345. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1346. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1347. * @param event Defines the related dom event
  1348. */
  1349. function KeyboardInfoPre(
  1350. /**
  1351. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1352. */
  1353. type,
  1354. /**
  1355. * Defines the related dom event
  1356. */
  1357. event) {
  1358. var _this = _super.call(this, type, event) || this;
  1359. _this.type = type;
  1360. _this.event = event;
  1361. _this.skipOnPointerObservable = false;
  1362. return _this;
  1363. }
  1364. return KeyboardInfoPre;
  1365. }(KeyboardInfo));
  1366. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1367. })(BABYLON || (BABYLON = {}));
  1368. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1369. var BABYLON;
  1370. (function (BABYLON) {
  1371. /**
  1372. * Gather the list of pointer event types as constants.
  1373. */
  1374. var PointerEventTypes = /** @class */ (function () {
  1375. function PointerEventTypes() {
  1376. }
  1377. /**
  1378. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1379. */
  1380. PointerEventTypes.POINTERDOWN = 0x01;
  1381. /**
  1382. * The pointerup event is fired when a pointer is no longer active.
  1383. */
  1384. PointerEventTypes.POINTERUP = 0x02;
  1385. /**
  1386. * The pointermove event is fired when a pointer changes coordinates.
  1387. */
  1388. PointerEventTypes.POINTERMOVE = 0x04;
  1389. /**
  1390. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1391. */
  1392. PointerEventTypes.POINTERWHEEL = 0x08;
  1393. /**
  1394. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1395. */
  1396. PointerEventTypes.POINTERPICK = 0x10;
  1397. /**
  1398. * The pointertap event is fired when a the object has been touched and released without drag.
  1399. */
  1400. PointerEventTypes.POINTERTAP = 0x20;
  1401. /**
  1402. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1403. */
  1404. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1405. return PointerEventTypes;
  1406. }());
  1407. BABYLON.PointerEventTypes = PointerEventTypes;
  1408. /**
  1409. * Base class of pointer info types.
  1410. */
  1411. var PointerInfoBase = /** @class */ (function () {
  1412. /**
  1413. * Instantiates the base class of pointers info.
  1414. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1415. * @param event Defines the related dom event
  1416. */
  1417. function PointerInfoBase(
  1418. /**
  1419. * Defines the type of event (BABYLON.PointerEventTypes)
  1420. */
  1421. type,
  1422. /**
  1423. * Defines the related dom event
  1424. */
  1425. event) {
  1426. this.type = type;
  1427. this.event = event;
  1428. }
  1429. return PointerInfoBase;
  1430. }());
  1431. BABYLON.PointerInfoBase = PointerInfoBase;
  1432. /**
  1433. * This class is used to store pointer related info for the onPrePointerObservable event.
  1434. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1435. */
  1436. var PointerInfoPre = /** @class */ (function (_super) {
  1437. __extends(PointerInfoPre, _super);
  1438. /**
  1439. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1440. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1441. * @param event Defines the related dom event
  1442. * @param localX Defines the local x coordinates of the pointer when the event occured
  1443. * @param localY Defines the local y coordinates of the pointer when the event occured
  1444. */
  1445. function PointerInfoPre(type, event, localX, localY) {
  1446. var _this = _super.call(this, type, event) || this;
  1447. /**
  1448. * Ray from a pointer if availible (eg. 6dof controller)
  1449. */
  1450. _this.ray = null;
  1451. _this.skipOnPointerObservable = false;
  1452. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1453. return _this;
  1454. }
  1455. return PointerInfoPre;
  1456. }(PointerInfoBase));
  1457. BABYLON.PointerInfoPre = PointerInfoPre;
  1458. /**
  1459. * This type contains all the data related to a pointer event in Babylon.js.
  1460. * 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.
  1461. */
  1462. var PointerInfo = /** @class */ (function (_super) {
  1463. __extends(PointerInfo, _super);
  1464. /**
  1465. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1466. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1467. * @param event Defines the related dom event
  1468. * @param pickInfo Defines the picking info associated to the info (if any)\
  1469. */
  1470. function PointerInfo(type, event,
  1471. /**
  1472. * Defines the picking info associated to the info (if any)\
  1473. */
  1474. pickInfo) {
  1475. var _this = _super.call(this, type, event) || this;
  1476. _this.pickInfo = pickInfo;
  1477. return _this;
  1478. }
  1479. return PointerInfo;
  1480. }(PointerInfoBase));
  1481. BABYLON.PointerInfo = PointerInfo;
  1482. })(BABYLON || (BABYLON = {}));
  1483. //# sourceMappingURL=babylon.pointerEvents.js.map
  1484. var BABYLON;
  1485. (function (BABYLON) {
  1486. /** Class used to store color4 gradient */
  1487. var ColorGradient = /** @class */ (function () {
  1488. function ColorGradient() {
  1489. }
  1490. /**
  1491. * Will get a color picked randomly between color1 and color2.
  1492. * If color2 is undefined then color1 will be used
  1493. * @param result defines the target Color4 to store the result in
  1494. */
  1495. ColorGradient.prototype.getColorToRef = function (result) {
  1496. if (!this.color2) {
  1497. result.copyFrom(this.color1);
  1498. return;
  1499. }
  1500. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  1501. };
  1502. return ColorGradient;
  1503. }());
  1504. BABYLON.ColorGradient = ColorGradient;
  1505. /** Class used to store color 3 gradient */
  1506. var Color3Gradient = /** @class */ (function () {
  1507. function Color3Gradient() {
  1508. }
  1509. return Color3Gradient;
  1510. }());
  1511. BABYLON.Color3Gradient = Color3Gradient;
  1512. /** Class used to store factor gradient */
  1513. var FactorGradient = /** @class */ (function () {
  1514. function FactorGradient() {
  1515. }
  1516. /**
  1517. * Will get a number picked randomly between factor1 and factor2.
  1518. * If factor2 is undefined then factor1 will be used
  1519. * @returns the picked number
  1520. */
  1521. FactorGradient.prototype.getFactor = function () {
  1522. if (this.factor2 === undefined) {
  1523. return this.factor1;
  1524. }
  1525. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  1526. };
  1527. return FactorGradient;
  1528. }());
  1529. BABYLON.FactorGradient = FactorGradient;
  1530. /**
  1531. * @ignore
  1532. * Application error to support additional information when loading a file
  1533. */
  1534. var LoadFileError = /** @class */ (function (_super) {
  1535. __extends(LoadFileError, _super);
  1536. /**
  1537. * Creates a new LoadFileError
  1538. * @param message defines the message of the error
  1539. * @param request defines the optional XHR request
  1540. */
  1541. function LoadFileError(message,
  1542. /** defines the optional XHR request */
  1543. request) {
  1544. var _this = _super.call(this, message) || this;
  1545. _this.request = request;
  1546. _this.name = "LoadFileError";
  1547. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  1548. return _this;
  1549. }
  1550. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  1551. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  1552. // Polyfill for Object.setPrototypeOf if necessary.
  1553. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  1554. return LoadFileError;
  1555. }(Error));
  1556. BABYLON.LoadFileError = LoadFileError;
  1557. /**
  1558. * Class used to define a retry strategy when error happens while loading assets
  1559. */
  1560. var RetryStrategy = /** @class */ (function () {
  1561. function RetryStrategy() {
  1562. }
  1563. /**
  1564. * Function used to defines an exponential back off strategy
  1565. * @param maxRetries defines the maximum number of retries (3 by default)
  1566. * @param baseInterval defines the interval between retries
  1567. * @returns the strategy function to use
  1568. */
  1569. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  1570. if (maxRetries === void 0) { maxRetries = 3; }
  1571. if (baseInterval === void 0) { baseInterval = 500; }
  1572. return function (url, request, retryIndex) {
  1573. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  1574. return -1;
  1575. }
  1576. return Math.pow(2, retryIndex) * baseInterval;
  1577. };
  1578. };
  1579. return RetryStrategy;
  1580. }());
  1581. BABYLON.RetryStrategy = RetryStrategy;
  1582. // Screenshots
  1583. var screenshotCanvas;
  1584. var cloneValue = function (source, destinationObject) {
  1585. if (!source) {
  1586. return null;
  1587. }
  1588. if (source instanceof BABYLON.Mesh) {
  1589. return null;
  1590. }
  1591. if (source instanceof BABYLON.SubMesh) {
  1592. return source.clone(destinationObject);
  1593. }
  1594. else if (source.clone) {
  1595. return source.clone();
  1596. }
  1597. return null;
  1598. };
  1599. /**
  1600. * Class containing a set of static utilities functions
  1601. */
  1602. var Tools = /** @class */ (function () {
  1603. function Tools() {
  1604. }
  1605. /**
  1606. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  1607. * @param u defines the coordinate on X axis
  1608. * @param v defines the coordinate on Y axis
  1609. * @param width defines the width of the source data
  1610. * @param height defines the height of the source data
  1611. * @param pixels defines the source byte array
  1612. * @param color defines the output color
  1613. */
  1614. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  1615. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  1616. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  1617. var position = (wrappedU + wrappedV * width) * 4;
  1618. color.r = pixels[position] / 255;
  1619. color.g = pixels[position + 1] / 255;
  1620. color.b = pixels[position + 2] / 255;
  1621. color.a = pixels[position + 3] / 255;
  1622. };
  1623. /**
  1624. * Interpolates between a and b via alpha
  1625. * @param a The lower value (returned when alpha = 0)
  1626. * @param b The upper value (returned when alpha = 1)
  1627. * @param alpha The interpolation-factor
  1628. * @return The mixed value
  1629. */
  1630. Tools.Mix = function (a, b, alpha) {
  1631. return a * (1 - alpha) + b * alpha;
  1632. };
  1633. /**
  1634. * Tries to instantiate a new object from a given class name
  1635. * @param className defines the class name to instantiate
  1636. * @returns the new object or null if the system was not able to do the instantiation
  1637. */
  1638. Tools.Instantiate = function (className) {
  1639. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  1640. return Tools.RegisteredExternalClasses[className];
  1641. }
  1642. var arr = className.split(".");
  1643. var fn = (window || this);
  1644. for (var i = 0, len = arr.length; i < len; i++) {
  1645. fn = fn[arr[i]];
  1646. }
  1647. if (typeof fn !== "function") {
  1648. return null;
  1649. }
  1650. return fn;
  1651. };
  1652. /**
  1653. * Provides a slice function that will work even on IE
  1654. * @param data defines the array to slice
  1655. * @param start defines the start of the data (optional)
  1656. * @param end defines the end of the data (optional)
  1657. * @returns the new sliced array
  1658. */
  1659. Tools.Slice = function (data, start, end) {
  1660. if (data.slice) {
  1661. return data.slice(start, end);
  1662. }
  1663. return Array.prototype.slice.call(data, start, end);
  1664. };
  1665. /**
  1666. * Polyfill for setImmediate
  1667. * @param action defines the action to execute after the current execution block
  1668. */
  1669. Tools.SetImmediate = function (action) {
  1670. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  1671. window.setImmediate(action);
  1672. }
  1673. else {
  1674. setTimeout(action, 1);
  1675. }
  1676. };
  1677. /**
  1678. * Function indicating if a number is an exponent of 2
  1679. * @param value defines the value to test
  1680. * @returns true if the value is an exponent of 2
  1681. */
  1682. Tools.IsExponentOfTwo = function (value) {
  1683. var count = 1;
  1684. do {
  1685. count *= 2;
  1686. } while (count < value);
  1687. return count === value;
  1688. };
  1689. /**
  1690. * Returns the nearest 32-bit single precision float representation of a Number
  1691. * @param value A Number. If the parameter is of a different type, it will get converted
  1692. * to a number or to NaN if it cannot be converted
  1693. * @returns number
  1694. */
  1695. Tools.FloatRound = function (value) {
  1696. if (Math.fround) {
  1697. return Math.fround(value);
  1698. }
  1699. return (Tools._tmpFloatArray[0] = value);
  1700. };
  1701. /**
  1702. * Find the next highest power of two.
  1703. * @param x Number to start search from.
  1704. * @return Next highest power of two.
  1705. */
  1706. Tools.CeilingPOT = function (x) {
  1707. x--;
  1708. x |= x >> 1;
  1709. x |= x >> 2;
  1710. x |= x >> 4;
  1711. x |= x >> 8;
  1712. x |= x >> 16;
  1713. x++;
  1714. return x;
  1715. };
  1716. /**
  1717. * Find the next lowest power of two.
  1718. * @param x Number to start search from.
  1719. * @return Next lowest power of two.
  1720. */
  1721. Tools.FloorPOT = function (x) {
  1722. x = x | (x >> 1);
  1723. x = x | (x >> 2);
  1724. x = x | (x >> 4);
  1725. x = x | (x >> 8);
  1726. x = x | (x >> 16);
  1727. return x - (x >> 1);
  1728. };
  1729. /**
  1730. * Find the nearest power of two.
  1731. * @param x Number to start search from.
  1732. * @return Next nearest power of two.
  1733. */
  1734. Tools.NearestPOT = function (x) {
  1735. var c = Tools.CeilingPOT(x);
  1736. var f = Tools.FloorPOT(x);
  1737. return (c - x) > (x - f) ? f : c;
  1738. };
  1739. /**
  1740. * Get the closest exponent of two
  1741. * @param value defines the value to approximate
  1742. * @param max defines the maximum value to return
  1743. * @param mode defines how to define the closest value
  1744. * @returns closest exponent of two of the given value
  1745. */
  1746. Tools.GetExponentOfTwo = function (value, max, mode) {
  1747. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  1748. var pot;
  1749. switch (mode) {
  1750. case BABYLON.Engine.SCALEMODE_FLOOR:
  1751. pot = Tools.FloorPOT(value);
  1752. break;
  1753. case BABYLON.Engine.SCALEMODE_NEAREST:
  1754. pot = Tools.NearestPOT(value);
  1755. break;
  1756. case BABYLON.Engine.SCALEMODE_CEILING:
  1757. default:
  1758. pot = Tools.CeilingPOT(value);
  1759. break;
  1760. }
  1761. return Math.min(pot, max);
  1762. };
  1763. /**
  1764. * Extracts the filename from a path
  1765. * @param path defines the path to use
  1766. * @returns the filename
  1767. */
  1768. Tools.GetFilename = function (path) {
  1769. var index = path.lastIndexOf("/");
  1770. if (index < 0) {
  1771. return path;
  1772. }
  1773. return path.substring(index + 1);
  1774. };
  1775. /**
  1776. * Extracts the "folder" part of a path (everything before the filename).
  1777. * @param uri The URI to extract the info from
  1778. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  1779. * @returns The "folder" part of the path
  1780. */
  1781. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  1782. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  1783. var index = uri.lastIndexOf("/");
  1784. if (index < 0) {
  1785. if (returnUnchangedIfNoSlash) {
  1786. return uri;
  1787. }
  1788. return "";
  1789. }
  1790. return uri.substring(0, index + 1);
  1791. };
  1792. /**
  1793. * Extracts text content from a DOM element hierarchy
  1794. * @param element defines the root element
  1795. * @returns a string
  1796. */
  1797. Tools.GetDOMTextContent = function (element) {
  1798. var result = "";
  1799. var child = element.firstChild;
  1800. while (child) {
  1801. if (child.nodeType === 3) {
  1802. result += child.textContent;
  1803. }
  1804. child = child.nextSibling;
  1805. }
  1806. return result;
  1807. };
  1808. /**
  1809. * Convert an angle in radians to degrees
  1810. * @param angle defines the angle to convert
  1811. * @returns the angle in degrees
  1812. */
  1813. Tools.ToDegrees = function (angle) {
  1814. return angle * 180 / Math.PI;
  1815. };
  1816. /**
  1817. * Convert an angle in degrees to radians
  1818. * @param angle defines the angle to convert
  1819. * @returns the angle in radians
  1820. */
  1821. Tools.ToRadians = function (angle) {
  1822. return angle * Math.PI / 180;
  1823. };
  1824. /**
  1825. * Encode a buffer to a base64 string
  1826. * @param buffer defines the buffer to encode
  1827. * @returns the encoded string
  1828. */
  1829. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  1830. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1831. var output = "";
  1832. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  1833. var i = 0;
  1834. var bytes = new Uint8Array(buffer);
  1835. while (i < bytes.length) {
  1836. chr1 = bytes[i++];
  1837. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  1838. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  1839. enc1 = chr1 >> 2;
  1840. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  1841. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  1842. enc4 = chr3 & 63;
  1843. if (isNaN(chr2)) {
  1844. enc3 = enc4 = 64;
  1845. }
  1846. else if (isNaN(chr3)) {
  1847. enc4 = 64;
  1848. }
  1849. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  1850. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  1851. }
  1852. return "data:image/png;base64," + output;
  1853. };
  1854. /**
  1855. * Extracts minimum and maximum values from a list of indexed positions
  1856. * @param positions defines the positions to use
  1857. * @param indices defines the indices to the positions
  1858. * @param indexStart defines the start index
  1859. * @param indexCount defines the end index
  1860. * @param bias defines bias value to add to the result
  1861. * @return minimum and maximum values
  1862. */
  1863. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  1864. if (bias === void 0) { bias = null; }
  1865. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1866. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1867. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1868. var offset = indices[index] * 3;
  1869. var x = positions[offset];
  1870. var y = positions[offset + 1];
  1871. var z = positions[offset + 2];
  1872. minimum.minimizeInPlaceFromFloats(x, y, z);
  1873. maximum.maximizeInPlaceFromFloats(x, y, z);
  1874. }
  1875. if (bias) {
  1876. minimum.x -= minimum.x * bias.x + bias.y;
  1877. minimum.y -= minimum.y * bias.x + bias.y;
  1878. minimum.z -= minimum.z * bias.x + bias.y;
  1879. maximum.x += maximum.x * bias.x + bias.y;
  1880. maximum.y += maximum.y * bias.x + bias.y;
  1881. maximum.z += maximum.z * bias.x + bias.y;
  1882. }
  1883. return {
  1884. minimum: minimum,
  1885. maximum: maximum
  1886. };
  1887. };
  1888. /**
  1889. * Extracts minimum and maximum values from a list of positions
  1890. * @param positions defines the positions to use
  1891. * @param start defines the start index in the positions array
  1892. * @param count defines the number of positions to handle
  1893. * @param bias defines bias value to add to the result
  1894. * @param stride defines the stride size to use (distance between two positions in the positions array)
  1895. * @return minimum and maximum values
  1896. */
  1897. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  1898. if (bias === void 0) { bias = null; }
  1899. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1900. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1901. if (!stride) {
  1902. stride = 3;
  1903. }
  1904. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  1905. var x = positions[offset];
  1906. var y = positions[offset + 1];
  1907. var z = positions[offset + 2];
  1908. minimum.minimizeInPlaceFromFloats(x, y, z);
  1909. maximum.maximizeInPlaceFromFloats(x, y, z);
  1910. }
  1911. if (bias) {
  1912. minimum.x -= minimum.x * bias.x + bias.y;
  1913. minimum.y -= minimum.y * bias.x + bias.y;
  1914. minimum.z -= minimum.z * bias.x + bias.y;
  1915. maximum.x += maximum.x * bias.x + bias.y;
  1916. maximum.y += maximum.y * bias.x + bias.y;
  1917. maximum.z += maximum.z * bias.x + bias.y;
  1918. }
  1919. return {
  1920. minimum: minimum,
  1921. maximum: maximum
  1922. };
  1923. };
  1924. /**
  1925. * Returns an array if obj is not an array
  1926. * @param obj defines the object to evaluate as an array
  1927. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  1928. * @returns either obj directly if obj is an array or a new array containing obj
  1929. */
  1930. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1931. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  1932. return null;
  1933. }
  1934. return Array.isArray(obj) ? obj : [obj];
  1935. };
  1936. /**
  1937. * Returns an array of the given size filled with element built from the given constructor and the paramters
  1938. * @param size the number of element to construct and put in the array
  1939. * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
  1940. * @returns a new array filled with new objects
  1941. */
  1942. Tools.BuildArray = function (size, itemBuilder) {
  1943. var a = [];
  1944. for (var i = 0; i < size; ++i) {
  1945. a.push(itemBuilder());
  1946. }
  1947. return a;
  1948. };
  1949. /**
  1950. * Gets the pointer prefix to use
  1951. * @returns "pointer" if touch is enabled. Else returns "mouse"
  1952. */
  1953. Tools.GetPointerPrefix = function () {
  1954. var eventPrefix = "pointer";
  1955. // Check if pointer events are supported
  1956. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  1957. eventPrefix = "mouse";
  1958. }
  1959. return eventPrefix;
  1960. };
  1961. /**
  1962. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  1963. * @param func - the function to be called
  1964. * @param requester - the object that will request the next frame. Falls back to window.
  1965. * @returns frame number
  1966. */
  1967. Tools.QueueNewFrame = function (func, requester) {
  1968. if (!Tools.IsWindowObjectExist()) {
  1969. return setTimeout(func, 16);
  1970. }
  1971. if (!requester) {
  1972. requester = window;
  1973. }
  1974. if (requester.requestAnimationFrame) {
  1975. return requester.requestAnimationFrame(func);
  1976. }
  1977. else if (requester.msRequestAnimationFrame) {
  1978. return requester.msRequestAnimationFrame(func);
  1979. }
  1980. else if (requester.webkitRequestAnimationFrame) {
  1981. return requester.webkitRequestAnimationFrame(func);
  1982. }
  1983. else if (requester.mozRequestAnimationFrame) {
  1984. return requester.mozRequestAnimationFrame(func);
  1985. }
  1986. else if (requester.oRequestAnimationFrame) {
  1987. return requester.oRequestAnimationFrame(func);
  1988. }
  1989. else {
  1990. return window.setTimeout(func, 16);
  1991. }
  1992. };
  1993. /**
  1994. * Ask the browser to promote the current element to fullscreen rendering mode
  1995. * @param element defines the DOM element to promote
  1996. */
  1997. Tools.RequestFullscreen = function (element) {
  1998. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  1999. if (!requestFunction) {
  2000. return;
  2001. }
  2002. requestFunction.call(element);
  2003. };
  2004. /**
  2005. * Asks the browser to exit fullscreen mode
  2006. */
  2007. Tools.ExitFullscreen = function () {
  2008. if (document.exitFullscreen) {
  2009. document.exitFullscreen();
  2010. }
  2011. else if (document.mozCancelFullScreen) {
  2012. document.mozCancelFullScreen();
  2013. }
  2014. else if (document.webkitCancelFullScreen) {
  2015. document.webkitCancelFullScreen();
  2016. }
  2017. else if (document.msCancelFullScreen) {
  2018. document.msCancelFullScreen();
  2019. }
  2020. };
  2021. /**
  2022. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  2023. * @param url define the url we are trying
  2024. * @param element define the dom element where to configure the cors policy
  2025. */
  2026. Tools.SetCorsBehavior = function (url, element) {
  2027. if (url && url.indexOf("data:") === 0) {
  2028. return;
  2029. }
  2030. if (Tools.CorsBehavior) {
  2031. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  2032. element.crossOrigin = Tools.CorsBehavior;
  2033. }
  2034. else {
  2035. var result = Tools.CorsBehavior(url);
  2036. if (result) {
  2037. element.crossOrigin = result;
  2038. }
  2039. }
  2040. }
  2041. };
  2042. // External files
  2043. /**
  2044. * Removes unwanted characters from an url
  2045. * @param url defines the url to clean
  2046. * @returns the cleaned url
  2047. */
  2048. Tools.CleanUrl = function (url) {
  2049. url = url.replace(/#/mg, "%23");
  2050. return url;
  2051. };
  2052. /**
  2053. * Loads an image as an HTMLImageElement.
  2054. * @param input url string, ArrayBuffer, or Blob to load
  2055. * @param onLoad callback called when the image successfully loads
  2056. * @param onError callback called when the image fails to load
  2057. * @param offlineProvider offline provider for caching
  2058. * @returns the HTMLImageElement of the loaded image
  2059. */
  2060. Tools.LoadImage = function (input, onLoad, onError, offlineProvider) {
  2061. var url;
  2062. var usingObjectURL = false;
  2063. if (input instanceof ArrayBuffer) {
  2064. url = URL.createObjectURL(new Blob([input]));
  2065. usingObjectURL = true;
  2066. }
  2067. else if (input instanceof Blob) {
  2068. url = URL.createObjectURL(input);
  2069. usingObjectURL = true;
  2070. }
  2071. else {
  2072. url = Tools.CleanUrl(input);
  2073. url = Tools.PreprocessUrl(input);
  2074. }
  2075. var img = new Image();
  2076. Tools.SetCorsBehavior(url, img);
  2077. var loadHandler = function () {
  2078. if (usingObjectURL && img.src) {
  2079. URL.revokeObjectURL(img.src);
  2080. }
  2081. img.removeEventListener("load", loadHandler);
  2082. img.removeEventListener("error", errorHandler);
  2083. onLoad(img);
  2084. };
  2085. var errorHandler = function (err) {
  2086. if (usingObjectURL && img.src) {
  2087. URL.revokeObjectURL(img.src);
  2088. }
  2089. img.removeEventListener("load", loadHandler);
  2090. img.removeEventListener("error", errorHandler);
  2091. Tools.Error("Error while trying to load image: " + input);
  2092. if (onError) {
  2093. onError("Error while trying to load image: " + input, err);
  2094. }
  2095. };
  2096. img.addEventListener("load", loadHandler);
  2097. img.addEventListener("error", errorHandler);
  2098. var noOfflineSupport = function () {
  2099. img.src = url;
  2100. };
  2101. var loadFromOfflineSupport = function () {
  2102. if (offlineProvider) {
  2103. offlineProvider.loadImage(url, img);
  2104. }
  2105. };
  2106. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  2107. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  2108. }
  2109. else {
  2110. if (url.indexOf("file:") !== -1) {
  2111. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  2112. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  2113. try {
  2114. var blobURL;
  2115. try {
  2116. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2117. }
  2118. catch (ex) {
  2119. // Chrome doesn't support oneTimeOnly parameter
  2120. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2121. }
  2122. img.src = blobURL;
  2123. usingObjectURL = true;
  2124. }
  2125. catch (e) {
  2126. img.src = "";
  2127. }
  2128. return img;
  2129. }
  2130. }
  2131. noOfflineSupport();
  2132. }
  2133. return img;
  2134. };
  2135. /**
  2136. * Loads a file
  2137. * @param url url string, ArrayBuffer, or Blob to load
  2138. * @param onSuccess callback called when the file successfully loads
  2139. * @param onProgress callback called while file is loading (if the server supports this mode)
  2140. * @param offlineProvider defines the offline provider for caching
  2141. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  2142. * @param onError callback called when the file fails to load
  2143. * @returns a file request object
  2144. */
  2145. Tools.LoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  2146. url = Tools.CleanUrl(url);
  2147. url = Tools.PreprocessUrl(url);
  2148. // If file and file input are set
  2149. if (url.indexOf("file:") !== -1) {
  2150. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  2151. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  2152. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  2153. }
  2154. }
  2155. var loadUrl = Tools.BaseUrl + url;
  2156. var aborted = false;
  2157. var fileRequest = {
  2158. onCompleteObservable: new BABYLON.Observable(),
  2159. abort: function () { return aborted = true; },
  2160. };
  2161. var requestFile = function () {
  2162. var request = new XMLHttpRequest();
  2163. var retryHandle = null;
  2164. fileRequest.abort = function () {
  2165. aborted = true;
  2166. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  2167. request.abort();
  2168. }
  2169. if (retryHandle !== null) {
  2170. clearTimeout(retryHandle);
  2171. retryHandle = null;
  2172. }
  2173. };
  2174. var retryLoop = function (retryIndex) {
  2175. request.open('GET', loadUrl, true);
  2176. if (useArrayBuffer) {
  2177. request.responseType = "arraybuffer";
  2178. }
  2179. if (onProgress) {
  2180. request.addEventListener("progress", onProgress);
  2181. }
  2182. var onLoadEnd = function () {
  2183. request.removeEventListener("loadend", onLoadEnd);
  2184. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2185. fileRequest.onCompleteObservable.clear();
  2186. };
  2187. request.addEventListener("loadend", onLoadEnd);
  2188. var onReadyStateChange = function () {
  2189. if (aborted) {
  2190. return;
  2191. }
  2192. // In case of undefined state in some browsers.
  2193. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  2194. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  2195. request.removeEventListener("readystatechange", onReadyStateChange);
  2196. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  2197. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  2198. return;
  2199. }
  2200. var retryStrategy = Tools.DefaultRetryStrategy;
  2201. if (retryStrategy) {
  2202. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  2203. if (waitTime !== -1) {
  2204. // Prevent the request from completing for retry.
  2205. request.removeEventListener("loadend", onLoadEnd);
  2206. request = new XMLHttpRequest();
  2207. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  2208. return;
  2209. }
  2210. }
  2211. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  2212. if (onError) {
  2213. onError(request, e);
  2214. }
  2215. else {
  2216. throw e;
  2217. }
  2218. }
  2219. };
  2220. request.addEventListener("readystatechange", onReadyStateChange);
  2221. request.send();
  2222. };
  2223. retryLoop(0);
  2224. };
  2225. // Caching all files
  2226. if (offlineProvider && offlineProvider.enableSceneOffline) {
  2227. var noOfflineSupport_1 = function (request) {
  2228. if (request && request.status > 400) {
  2229. if (onError) {
  2230. onError(request);
  2231. }
  2232. }
  2233. else {
  2234. if (!aborted) {
  2235. requestFile();
  2236. }
  2237. }
  2238. };
  2239. var loadFromOfflineSupport = function () {
  2240. // TODO: database needs to support aborting and should return a IFileRequest
  2241. if (aborted) {
  2242. return;
  2243. }
  2244. if (offlineProvider) {
  2245. offlineProvider.loadFile(url, function (data) {
  2246. if (!aborted) {
  2247. onSuccess(data);
  2248. }
  2249. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2250. }, onProgress ? function (event) {
  2251. if (!aborted) {
  2252. onProgress(event);
  2253. }
  2254. } : undefined, noOfflineSupport_1, useArrayBuffer);
  2255. }
  2256. };
  2257. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport_1);
  2258. }
  2259. else {
  2260. requestFile();
  2261. }
  2262. return fileRequest;
  2263. };
  2264. /**
  2265. * Load a script (identified by an url). When the url returns, the
  2266. * content of this file is added into a new script element, attached to the DOM (body element)
  2267. * @param scriptUrl defines the url of the script to laod
  2268. * @param onSuccess defines the callback called when the script is loaded
  2269. * @param onError defines the callback to call if an error occurs
  2270. */
  2271. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  2272. if (!Tools.IsWindowObjectExist()) {
  2273. return;
  2274. }
  2275. var head = document.getElementsByTagName('head')[0];
  2276. var script = document.createElement('script');
  2277. script.type = 'text/javascript';
  2278. script.src = scriptUrl;
  2279. script.onload = function () {
  2280. if (onSuccess) {
  2281. onSuccess();
  2282. }
  2283. };
  2284. script.onerror = function (e) {
  2285. if (onError) {
  2286. onError("Unable to load script '" + scriptUrl + "'", e);
  2287. }
  2288. };
  2289. head.appendChild(script);
  2290. };
  2291. /**
  2292. * Loads a file from a blob
  2293. * @param fileToLoad defines the blob to use
  2294. * @param callback defines the callback to call when data is loaded
  2295. * @param progressCallback defines the callback to call during loading process
  2296. * @returns a file request object
  2297. */
  2298. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2299. var reader = new FileReader();
  2300. var request = {
  2301. onCompleteObservable: new BABYLON.Observable(),
  2302. abort: function () { return reader.abort(); },
  2303. };
  2304. reader.onloadend = function (e) {
  2305. request.onCompleteObservable.notifyObservers(request);
  2306. };
  2307. reader.onload = function (e) {
  2308. //target doesn't have result from ts 1.3
  2309. callback(e.target['result']);
  2310. };
  2311. reader.onprogress = progressCallback;
  2312. reader.readAsDataURL(fileToLoad);
  2313. return request;
  2314. };
  2315. /**
  2316. * Loads a file
  2317. * @param fileToLoad defines the file to load
  2318. * @param callback defines the callback to call when data is loaded
  2319. * @param progressCallBack defines the callback to call during loading process
  2320. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  2321. * @returns a file request object
  2322. */
  2323. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2324. var reader = new FileReader();
  2325. var request = {
  2326. onCompleteObservable: new BABYLON.Observable(),
  2327. abort: function () { return reader.abort(); },
  2328. };
  2329. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  2330. reader.onerror = function (e) {
  2331. Tools.Log("Error while reading file: " + fileToLoad.name);
  2332. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  2333. };
  2334. reader.onload = function (e) {
  2335. //target doesn't have result from ts 1.3
  2336. callback(e.target['result']);
  2337. };
  2338. if (progressCallBack) {
  2339. reader.onprogress = progressCallBack;
  2340. }
  2341. if (!useArrayBuffer) {
  2342. // Asynchronous read
  2343. reader.readAsText(fileToLoad);
  2344. }
  2345. else {
  2346. reader.readAsArrayBuffer(fileToLoad);
  2347. }
  2348. return request;
  2349. };
  2350. /**
  2351. * Creates a data url from a given string content
  2352. * @param content defines the content to convert
  2353. * @returns the new data url link
  2354. */
  2355. Tools.FileAsURL = function (content) {
  2356. var fileBlob = new Blob([content]);
  2357. var url = window.URL || window.webkitURL;
  2358. var link = url.createObjectURL(fileBlob);
  2359. return link;
  2360. };
  2361. /**
  2362. * Format the given number to a specific decimal format
  2363. * @param value defines the number to format
  2364. * @param decimals defines the number of decimals to use
  2365. * @returns the formatted string
  2366. */
  2367. Tools.Format = function (value, decimals) {
  2368. if (decimals === void 0) { decimals = 2; }
  2369. return value.toFixed(decimals);
  2370. };
  2371. /**
  2372. * Checks if a given vector is inside a specific range
  2373. * @param v defines the vector to test
  2374. * @param min defines the minimum range
  2375. * @param max defines the maximum range
  2376. */
  2377. Tools.CheckExtends = function (v, min, max) {
  2378. min.minimizeInPlace(v);
  2379. max.maximizeInPlace(v);
  2380. };
  2381. /**
  2382. * Tries to copy an object by duplicating every property
  2383. * @param source defines the source object
  2384. * @param destination defines the target object
  2385. * @param doNotCopyList defines a list of properties to avoid
  2386. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  2387. */
  2388. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2389. for (var prop in source) {
  2390. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2391. continue;
  2392. }
  2393. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2394. continue;
  2395. }
  2396. var sourceValue = source[prop];
  2397. var typeOfSourceValue = typeof sourceValue;
  2398. if (typeOfSourceValue === "function") {
  2399. continue;
  2400. }
  2401. try {
  2402. if (typeOfSourceValue === "object") {
  2403. if (sourceValue instanceof Array) {
  2404. destination[prop] = [];
  2405. if (sourceValue.length > 0) {
  2406. if (typeof sourceValue[0] == "object") {
  2407. for (var index = 0; index < sourceValue.length; index++) {
  2408. var clonedValue = cloneValue(sourceValue[index], destination);
  2409. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  2410. destination[prop].push(clonedValue);
  2411. }
  2412. }
  2413. }
  2414. else {
  2415. destination[prop] = sourceValue.slice(0);
  2416. }
  2417. }
  2418. }
  2419. else {
  2420. destination[prop] = cloneValue(sourceValue, destination);
  2421. }
  2422. }
  2423. else {
  2424. destination[prop] = sourceValue;
  2425. }
  2426. }
  2427. catch (e) {
  2428. // Just ignore error (it could be because of a read-only property)
  2429. }
  2430. }
  2431. };
  2432. /**
  2433. * Gets a boolean indicating if the given object has no own property
  2434. * @param obj defines the object to test
  2435. * @returns true if object has no own property
  2436. */
  2437. Tools.IsEmpty = function (obj) {
  2438. for (var i in obj) {
  2439. if (obj.hasOwnProperty(i)) {
  2440. return false;
  2441. }
  2442. }
  2443. return true;
  2444. };
  2445. /**
  2446. * Function used to register events at window level
  2447. * @param events defines the events to register
  2448. */
  2449. Tools.RegisterTopRootEvents = function (events) {
  2450. for (var index = 0; index < events.length; index++) {
  2451. var event = events[index];
  2452. window.addEventListener(event.name, event.handler, false);
  2453. try {
  2454. if (window.parent) {
  2455. window.parent.addEventListener(event.name, event.handler, false);
  2456. }
  2457. }
  2458. catch (e) {
  2459. // Silently fails...
  2460. }
  2461. }
  2462. };
  2463. /**
  2464. * Function used to unregister events from window level
  2465. * @param events defines the events to unregister
  2466. */
  2467. Tools.UnregisterTopRootEvents = function (events) {
  2468. for (var index = 0; index < events.length; index++) {
  2469. var event = events[index];
  2470. window.removeEventListener(event.name, event.handler);
  2471. try {
  2472. if (window.parent) {
  2473. window.parent.removeEventListener(event.name, event.handler);
  2474. }
  2475. }
  2476. catch (e) {
  2477. // Silently fails...
  2478. }
  2479. }
  2480. };
  2481. /**
  2482. * Dumps the current bound framebuffer
  2483. * @param width defines the rendering width
  2484. * @param height defines the rendering height
  2485. * @param engine defines the hosting engine
  2486. * @param successCallback defines the callback triggered once the data are available
  2487. * @param mimeType defines the mime type of the result
  2488. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  2489. */
  2490. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  2491. if (mimeType === void 0) { mimeType = "image/png"; }
  2492. // Read the contents of the framebuffer
  2493. var numberOfChannelsByLine = width * 4;
  2494. var halfHeight = height / 2;
  2495. //Reading datas from WebGL
  2496. var data = engine.readPixels(0, 0, width, height);
  2497. //To flip image on Y axis.
  2498. for (var i = 0; i < halfHeight; i++) {
  2499. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2500. var currentCell = j + i * numberOfChannelsByLine;
  2501. var targetLine = height - i - 1;
  2502. var targetCell = j + targetLine * numberOfChannelsByLine;
  2503. var temp = data[currentCell];
  2504. data[currentCell] = data[targetCell];
  2505. data[targetCell] = temp;
  2506. }
  2507. }
  2508. // Create a 2D canvas to store the result
  2509. if (!screenshotCanvas) {
  2510. screenshotCanvas = document.createElement('canvas');
  2511. }
  2512. screenshotCanvas.width = width;
  2513. screenshotCanvas.height = height;
  2514. var context = screenshotCanvas.getContext('2d');
  2515. if (context) {
  2516. // Copy the pixels to a 2D canvas
  2517. var imageData = context.createImageData(width, height);
  2518. var castData = (imageData.data);
  2519. castData.set(data);
  2520. context.putImageData(imageData, 0, 0);
  2521. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  2522. }
  2523. };
  2524. /**
  2525. * Converts the canvas data to blob.
  2526. * This acts as a polyfill for browsers not supporting the to blob function.
  2527. * @param canvas Defines the canvas to extract the data from
  2528. * @param successCallback Defines the callback triggered once the data are available
  2529. * @param mimeType Defines the mime type of the result
  2530. */
  2531. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  2532. if (mimeType === void 0) { mimeType = "image/png"; }
  2533. // We need HTMLCanvasElement.toBlob for HD screenshots
  2534. if (!canvas.toBlob) {
  2535. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  2536. canvas.toBlob = function (callback, type, quality) {
  2537. var _this = this;
  2538. setTimeout(function () {
  2539. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  2540. for (var i = 0; i < len; i++) {
  2541. arr[i] = binStr.charCodeAt(i);
  2542. }
  2543. callback(new Blob([arr]));
  2544. });
  2545. };
  2546. }
  2547. canvas.toBlob(function (blob) {
  2548. successCallback(blob);
  2549. }, mimeType);
  2550. };
  2551. /**
  2552. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  2553. * @param successCallback defines the callback triggered once the data are available
  2554. * @param mimeType defines the mime type of the result
  2555. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  2556. */
  2557. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  2558. if (mimeType === void 0) { mimeType = "image/png"; }
  2559. if (successCallback) {
  2560. var base64Image = screenshotCanvas.toDataURL(mimeType);
  2561. successCallback(base64Image);
  2562. }
  2563. else {
  2564. this.ToBlob(screenshotCanvas, function (blob) {
  2565. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2566. if (("download" in document.createElement("a"))) {
  2567. if (!fileName) {
  2568. var date = new Date();
  2569. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  2570. fileName = "screenshot_" + stringDate + ".png";
  2571. }
  2572. Tools.Download(blob, fileName);
  2573. }
  2574. else {
  2575. var url = URL.createObjectURL(blob);
  2576. var newWindow = window.open("");
  2577. if (!newWindow) {
  2578. return;
  2579. }
  2580. var img = newWindow.document.createElement("img");
  2581. img.onload = function () {
  2582. // no longer need to read the blob so it's revoked
  2583. URL.revokeObjectURL(url);
  2584. };
  2585. img.src = url;
  2586. newWindow.document.body.appendChild(img);
  2587. }
  2588. }, mimeType);
  2589. }
  2590. };
  2591. /**
  2592. * Downloads a blob in the browser
  2593. * @param blob defines the blob to download
  2594. * @param fileName defines the name of the downloaded file
  2595. */
  2596. Tools.Download = function (blob, fileName) {
  2597. if (navigator && navigator.msSaveBlob) {
  2598. navigator.msSaveBlob(blob, fileName);
  2599. return;
  2600. }
  2601. var url = window.URL.createObjectURL(blob);
  2602. var a = document.createElement("a");
  2603. document.body.appendChild(a);
  2604. a.style.display = "none";
  2605. a.href = url;
  2606. a.download = fileName;
  2607. a.addEventListener("click", function () {
  2608. if (a.parentElement) {
  2609. a.parentElement.removeChild(a);
  2610. }
  2611. });
  2612. a.click();
  2613. window.URL.revokeObjectURL(url);
  2614. };
  2615. /**
  2616. * Captures a screenshot of the current rendering
  2617. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2618. * @param engine defines the rendering engine
  2619. * @param camera defines the source camera
  2620. * @param size This parameter can be set to a single number or to an object with the
  2621. * following (optional) properties: precision, width, height. If a single number is passed,
  2622. * it will be used for both width and height. If an object is passed, the screenshot size
  2623. * will be derived from the parameters. The precision property is a multiplier allowing
  2624. * rendering at a higher or lower resolution
  2625. * @param successCallback defines the callback receives a single parameter which contains the
  2626. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2627. * src parameter of an <img> to display it
  2628. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  2629. * Check your browser for supported MIME types
  2630. */
  2631. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  2632. if (mimeType === void 0) { mimeType = "image/png"; }
  2633. var width;
  2634. var height;
  2635. // If a precision value is specified
  2636. if (size.precision) {
  2637. width = Math.round(engine.getRenderWidth() * size.precision);
  2638. height = Math.round(width / engine.getAspectRatio(camera));
  2639. }
  2640. else if (size.width && size.height) {
  2641. width = size.width;
  2642. height = size.height;
  2643. }
  2644. //If passing only width, computing height to keep display canvas ratio.
  2645. else if (size.width && !size.height) {
  2646. width = size.width;
  2647. height = Math.round(width / engine.getAspectRatio(camera));
  2648. }
  2649. //If passing only height, computing width to keep display canvas ratio.
  2650. else if (size.height && !size.width) {
  2651. height = size.height;
  2652. width = Math.round(height * engine.getAspectRatio(camera));
  2653. }
  2654. //Assuming here that "size" parameter is a number
  2655. else if (!isNaN(size)) {
  2656. height = size;
  2657. width = size;
  2658. }
  2659. else {
  2660. Tools.Error("Invalid 'size' parameter !");
  2661. return;
  2662. }
  2663. if (!screenshotCanvas) {
  2664. screenshotCanvas = document.createElement('canvas');
  2665. }
  2666. screenshotCanvas.width = width;
  2667. screenshotCanvas.height = height;
  2668. var renderContext = screenshotCanvas.getContext("2d");
  2669. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  2670. var newWidth = width;
  2671. var newHeight = newWidth / ratio;
  2672. if (newHeight > height) {
  2673. newHeight = height;
  2674. newWidth = newHeight * ratio;
  2675. }
  2676. var offsetX = Math.max(0, width - newWidth) / 2;
  2677. var offsetY = Math.max(0, height - newHeight) / 2;
  2678. var renderingCanvas = engine.getRenderingCanvas();
  2679. if (renderContext && renderingCanvas) {
  2680. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  2681. }
  2682. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  2683. };
  2684. /**
  2685. * Generates an image screenshot from the specified camera.
  2686. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2687. * @param engine The engine to use for rendering
  2688. * @param camera The camera to use for rendering
  2689. * @param size This parameter can be set to a single number or to an object with the
  2690. * following (optional) properties: precision, width, height. If a single number is passed,
  2691. * it will be used for both width and height. If an object is passed, the screenshot size
  2692. * will be derived from the parameters. The precision property is a multiplier allowing
  2693. * rendering at a higher or lower resolution
  2694. * @param successCallback The callback receives a single parameter which contains the
  2695. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2696. * src parameter of an <img> to display it
  2697. * @param mimeType The MIME type of the screenshot image (default: image/png).
  2698. * Check your browser for supported MIME types
  2699. * @param samples Texture samples (default: 1)
  2700. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  2701. * @param fileName A name for for the downloaded file.
  2702. */
  2703. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  2704. if (mimeType === void 0) { mimeType = "image/png"; }
  2705. if (samples === void 0) { samples = 1; }
  2706. if (antialiasing === void 0) { antialiasing = false; }
  2707. var width;
  2708. var height;
  2709. //If a precision value is specified
  2710. if (size.precision) {
  2711. width = Math.round(engine.getRenderWidth() * size.precision);
  2712. height = Math.round(width / engine.getAspectRatio(camera));
  2713. size = { width: width, height: height };
  2714. }
  2715. else if (size.width && size.height) {
  2716. width = size.width;
  2717. height = size.height;
  2718. }
  2719. //If passing only width, computing height to keep display canvas ratio.
  2720. else if (size.width && !size.height) {
  2721. width = size.width;
  2722. height = Math.round(width / engine.getAspectRatio(camera));
  2723. size = { width: width, height: height };
  2724. }
  2725. //If passing only height, computing width to keep display canvas ratio.
  2726. else if (size.height && !size.width) {
  2727. height = size.height;
  2728. width = Math.round(height * engine.getAspectRatio(camera));
  2729. size = { width: width, height: height };
  2730. }
  2731. //Assuming here that "size" parameter is a number
  2732. else if (!isNaN(size)) {
  2733. height = size;
  2734. width = size;
  2735. }
  2736. else {
  2737. Tools.Error("Invalid 'size' parameter !");
  2738. return;
  2739. }
  2740. var scene = camera.getScene();
  2741. var previousCamera = null;
  2742. if (scene.activeCamera !== camera) {
  2743. previousCamera = scene.activeCamera;
  2744. scene.activeCamera = camera;
  2745. }
  2746. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2747. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  2748. texture.renderList = null;
  2749. texture.samples = samples;
  2750. if (antialiasing) {
  2751. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  2752. }
  2753. texture.onAfterRenderObservable.add(function () {
  2754. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  2755. });
  2756. scene.incrementRenderId();
  2757. scene.resetCachedMaterial();
  2758. texture.render(true);
  2759. texture.dispose();
  2760. if (previousCamera) {
  2761. scene.activeCamera = previousCamera;
  2762. }
  2763. camera.getProjectionMatrix(true); // Force cache refresh;
  2764. };
  2765. /**
  2766. * Validates if xhr data is correct
  2767. * @param xhr defines the request to validate
  2768. * @param dataType defines the expected data type
  2769. * @returns true if data is correct
  2770. */
  2771. Tools.ValidateXHRData = function (xhr, dataType) {
  2772. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2773. if (dataType === void 0) { dataType = 7; }
  2774. try {
  2775. if (dataType & 1) {
  2776. if (xhr.responseText && xhr.responseText.length > 0) {
  2777. return true;
  2778. }
  2779. else if (dataType === 1) {
  2780. return false;
  2781. }
  2782. }
  2783. if (dataType & 2) {
  2784. // Check header width and height since there is no "TGA" magic number
  2785. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  2786. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2787. return true;
  2788. }
  2789. else if (dataType === 2) {
  2790. return false;
  2791. }
  2792. }
  2793. if (dataType & 4) {
  2794. // Check for the "DDS" magic number
  2795. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2796. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2797. return true;
  2798. }
  2799. else {
  2800. return false;
  2801. }
  2802. }
  2803. }
  2804. catch (e) {
  2805. // Global protection
  2806. }
  2807. return false;
  2808. };
  2809. /**
  2810. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  2811. * Be aware Math.random() could cause collisions, but:
  2812. * "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"
  2813. * @returns a pseudo random id
  2814. */
  2815. Tools.RandomId = function () {
  2816. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2817. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  2818. return v.toString(16);
  2819. });
  2820. };
  2821. /**
  2822. * Test if the given uri is a base64 string
  2823. * @param uri The uri to test
  2824. * @return True if the uri is a base64 string or false otherwise
  2825. */
  2826. Tools.IsBase64 = function (uri) {
  2827. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2828. };
  2829. /**
  2830. * Decode the given base64 uri.
  2831. * @param uri The uri to decode
  2832. * @return The decoded base64 data.
  2833. */
  2834. Tools.DecodeBase64 = function (uri) {
  2835. var decodedString = atob(uri.split(",")[1]);
  2836. var bufferLength = decodedString.length;
  2837. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2838. for (var i = 0; i < bufferLength; i++) {
  2839. bufferView[i] = decodedString.charCodeAt(i);
  2840. }
  2841. return bufferView.buffer;
  2842. };
  2843. Tools._AddLogEntry = function (entry) {
  2844. Tools._LogCache = entry + Tools._LogCache;
  2845. if (Tools.OnNewCacheEntry) {
  2846. Tools.OnNewCacheEntry(entry);
  2847. }
  2848. };
  2849. Tools._FormatMessage = function (message) {
  2850. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2851. var date = new Date();
  2852. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2853. };
  2854. Tools._LogDisabled = function (message) {
  2855. // nothing to do
  2856. };
  2857. Tools._LogEnabled = function (message) {
  2858. var formattedMessage = Tools._FormatMessage(message);
  2859. console.log("BJS - " + formattedMessage);
  2860. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2861. Tools._AddLogEntry(entry);
  2862. };
  2863. Tools._WarnDisabled = function (message) {
  2864. // nothing to do
  2865. };
  2866. Tools._WarnEnabled = function (message) {
  2867. var formattedMessage = Tools._FormatMessage(message);
  2868. console.warn("BJS - " + formattedMessage);
  2869. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2870. Tools._AddLogEntry(entry);
  2871. };
  2872. Tools._ErrorDisabled = function (message) {
  2873. // nothing to do
  2874. };
  2875. Tools._ErrorEnabled = function (message) {
  2876. Tools.errorsCount++;
  2877. var formattedMessage = Tools._FormatMessage(message);
  2878. console.error("BJS - " + formattedMessage);
  2879. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2880. Tools._AddLogEntry(entry);
  2881. };
  2882. Object.defineProperty(Tools, "LogCache", {
  2883. /**
  2884. * Gets current log cache (list of logs)
  2885. */
  2886. get: function () {
  2887. return Tools._LogCache;
  2888. },
  2889. enumerable: true,
  2890. configurable: true
  2891. });
  2892. /**
  2893. * Clears the log cache
  2894. */
  2895. Tools.ClearLogCache = function () {
  2896. Tools._LogCache = "";
  2897. Tools.errorsCount = 0;
  2898. };
  2899. Object.defineProperty(Tools, "LogLevels", {
  2900. /**
  2901. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  2902. */
  2903. set: function (level) {
  2904. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2905. Tools.Log = Tools._LogEnabled;
  2906. }
  2907. else {
  2908. Tools.Log = Tools._LogDisabled;
  2909. }
  2910. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2911. Tools.Warn = Tools._WarnEnabled;
  2912. }
  2913. else {
  2914. Tools.Warn = Tools._WarnDisabled;
  2915. }
  2916. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2917. Tools.Error = Tools._ErrorEnabled;
  2918. }
  2919. else {
  2920. Tools.Error = Tools._ErrorDisabled;
  2921. }
  2922. },
  2923. enumerable: true,
  2924. configurable: true
  2925. });
  2926. /**
  2927. * Checks if the loaded document was accessed via `file:`-Protocol.
  2928. * @returns boolean
  2929. */
  2930. Tools.IsFileURL = function () {
  2931. return location.protocol === "file:";
  2932. };
  2933. /**
  2934. * Checks if the window object exists
  2935. * @returns true if the window object exists
  2936. */
  2937. Tools.IsWindowObjectExist = function () {
  2938. return (typeof window) !== "undefined";
  2939. };
  2940. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2941. /**
  2942. * Sets the current performance log level
  2943. */
  2944. set: function (level) {
  2945. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2946. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2947. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2948. return;
  2949. }
  2950. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2951. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2952. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2953. return;
  2954. }
  2955. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2956. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2957. },
  2958. enumerable: true,
  2959. configurable: true
  2960. });
  2961. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2962. };
  2963. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2964. };
  2965. Tools._StartUserMark = function (counterName, condition) {
  2966. if (condition === void 0) { condition = true; }
  2967. if (!Tools._performance) {
  2968. if (!Tools.IsWindowObjectExist()) {
  2969. return;
  2970. }
  2971. Tools._performance = window.performance;
  2972. }
  2973. if (!condition || !Tools._performance.mark) {
  2974. return;
  2975. }
  2976. Tools._performance.mark(counterName + "-Begin");
  2977. };
  2978. Tools._EndUserMark = function (counterName, condition) {
  2979. if (condition === void 0) { condition = true; }
  2980. if (!condition || !Tools._performance.mark) {
  2981. return;
  2982. }
  2983. Tools._performance.mark(counterName + "-End");
  2984. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2985. };
  2986. Tools._StartPerformanceConsole = function (counterName, condition) {
  2987. if (condition === void 0) { condition = true; }
  2988. if (!condition) {
  2989. return;
  2990. }
  2991. Tools._StartUserMark(counterName, condition);
  2992. if (console.time) {
  2993. console.time(counterName);
  2994. }
  2995. };
  2996. Tools._EndPerformanceConsole = function (counterName, condition) {
  2997. if (condition === void 0) { condition = true; }
  2998. if (!condition) {
  2999. return;
  3000. }
  3001. Tools._EndUserMark(counterName, condition);
  3002. if (console.time) {
  3003. console.timeEnd(counterName);
  3004. }
  3005. };
  3006. Object.defineProperty(Tools, "Now", {
  3007. /**
  3008. * Gets either window.performance.now() if supported or Date.now() else
  3009. */
  3010. get: function () {
  3011. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  3012. return window.performance.now();
  3013. }
  3014. return Date.now();
  3015. },
  3016. enumerable: true,
  3017. configurable: true
  3018. });
  3019. /**
  3020. * This method will return the name of the class used to create the instance of the given object.
  3021. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  3022. * @param object the object to get the class name from
  3023. * @param isType defines if the object is actually a type
  3024. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  3025. */
  3026. Tools.GetClassName = function (object, isType) {
  3027. if (isType === void 0) { isType = false; }
  3028. var name = null;
  3029. if (!isType && object.getClassName) {
  3030. name = object.getClassName();
  3031. }
  3032. else {
  3033. if (object instanceof Object) {
  3034. var classObj = isType ? object : Object.getPrototypeOf(object);
  3035. name = classObj.constructor["__bjsclassName__"];
  3036. }
  3037. if (!name) {
  3038. name = typeof object;
  3039. }
  3040. }
  3041. return name;
  3042. };
  3043. /**
  3044. * Gets the first element of an array satisfying a given predicate
  3045. * @param array defines the array to browse
  3046. * @param predicate defines the predicate to use
  3047. * @returns null if not found or the element
  3048. */
  3049. Tools.First = function (array, predicate) {
  3050. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  3051. var el = array_1[_i];
  3052. if (predicate(el)) {
  3053. return el;
  3054. }
  3055. }
  3056. return null;
  3057. };
  3058. /**
  3059. * This method will return the name of the full name of the class, including its owning module (if any).
  3060. * 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).
  3061. * @param object the object to get the class name from
  3062. * @param isType defines if the object is actually a type
  3063. * @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.
  3064. * @ignorenaming
  3065. */
  3066. Tools.getFullClassName = function (object, isType) {
  3067. if (isType === void 0) { isType = false; }
  3068. var className = null;
  3069. var moduleName = null;
  3070. if (!isType && object.getClassName) {
  3071. className = object.getClassName();
  3072. }
  3073. else {
  3074. if (object instanceof Object) {
  3075. var classObj = isType ? object : Object.getPrototypeOf(object);
  3076. className = classObj.constructor["__bjsclassName__"];
  3077. moduleName = classObj.constructor["__bjsmoduleName__"];
  3078. }
  3079. if (!className) {
  3080. className = typeof object;
  3081. }
  3082. }
  3083. if (!className) {
  3084. return null;
  3085. }
  3086. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  3087. };
  3088. /**
  3089. * Returns a promise that resolves after the given amount of time.
  3090. * @param delay Number of milliseconds to delay
  3091. * @returns Promise that resolves after the given amount of time
  3092. */
  3093. Tools.DelayAsync = function (delay) {
  3094. return new Promise(function (resolve) {
  3095. setTimeout(function () {
  3096. resolve();
  3097. }, delay);
  3098. });
  3099. };
  3100. /**
  3101. * Gets the current gradient from an array of IValueGradient
  3102. * @param ratio defines the current ratio to get
  3103. * @param gradients defines the array of IValueGradient
  3104. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  3105. */
  3106. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  3107. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  3108. var currentGradient = gradients[gradientIndex];
  3109. var nextGradient = gradients[gradientIndex + 1];
  3110. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  3111. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  3112. updateFunc(currentGradient, nextGradient, scale);
  3113. return;
  3114. }
  3115. }
  3116. // Use last index if over
  3117. var lastIndex = gradients.length - 1;
  3118. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  3119. };
  3120. /**
  3121. * Gets or sets the base URL to use to load assets
  3122. */
  3123. Tools.BaseUrl = "";
  3124. /**
  3125. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  3126. */
  3127. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  3128. /**
  3129. * Default behaviour for cors in the application.
  3130. * It can be a string if the expected behavior is identical in the entire app.
  3131. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  3132. */
  3133. Tools.CorsBehavior = "anonymous";
  3134. /**
  3135. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  3136. * @ignorenaming
  3137. */
  3138. Tools.UseFallbackTexture = true;
  3139. /**
  3140. * Use this object to register external classes like custom textures or material
  3141. * to allow the laoders to instantiate them
  3142. */
  3143. Tools.RegisteredExternalClasses = {};
  3144. /**
  3145. * Texture content used if a texture cannot loaded
  3146. * @ignorenaming
  3147. */
  3148. 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";
  3149. Tools._tmpFloatArray = new Float32Array(1);
  3150. /**
  3151. * Gets or sets a function used to pre-process url before using them to load assets
  3152. */
  3153. Tools.PreprocessUrl = function (url) {
  3154. return url;
  3155. };
  3156. // Logs
  3157. /**
  3158. * No log
  3159. */
  3160. Tools.NoneLogLevel = 0;
  3161. /**
  3162. * Only message logs
  3163. */
  3164. Tools.MessageLogLevel = 1;
  3165. /**
  3166. * Only warning logs
  3167. */
  3168. Tools.WarningLogLevel = 2;
  3169. /**
  3170. * Only error logs
  3171. */
  3172. Tools.ErrorLogLevel = 4;
  3173. /**
  3174. * All logs
  3175. */
  3176. Tools.AllLogLevel = 7;
  3177. Tools._LogCache = "";
  3178. /**
  3179. * Gets a value indicating the number of loading errors
  3180. * @ignorenaming
  3181. */
  3182. Tools.errorsCount = 0;
  3183. /**
  3184. * Log a message to the console
  3185. */
  3186. Tools.Log = Tools._LogEnabled;
  3187. /**
  3188. * Write a warning message to the console
  3189. */
  3190. Tools.Warn = Tools._WarnEnabled;
  3191. /**
  3192. * Write an error message to the console
  3193. */
  3194. Tools.Error = Tools._ErrorEnabled;
  3195. // Performances
  3196. /**
  3197. * No performance log
  3198. */
  3199. Tools.PerformanceNoneLogLevel = 0;
  3200. /**
  3201. * Use user marks to log performance
  3202. */
  3203. Tools.PerformanceUserMarkLogLevel = 1;
  3204. /**
  3205. * Log performance to the console
  3206. */
  3207. Tools.PerformanceConsoleLogLevel = 2;
  3208. /**
  3209. * Starts a performance counter
  3210. */
  3211. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3212. /**
  3213. * Ends a specific performance coutner
  3214. */
  3215. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3216. return Tools;
  3217. }());
  3218. BABYLON.Tools = Tools;
  3219. /**
  3220. * This class is used to track a performance counter which is number based.
  3221. * The user has access to many properties which give statistics of different nature.
  3222. *
  3223. * The implementer can track two kinds of Performance Counter: time and count.
  3224. * 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.
  3225. * 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.
  3226. */
  3227. var PerfCounter = /** @class */ (function () {
  3228. /**
  3229. * Creates a new counter
  3230. */
  3231. function PerfCounter() {
  3232. this._startMonitoringTime = 0;
  3233. this._min = 0;
  3234. this._max = 0;
  3235. this._average = 0;
  3236. this._lastSecAverage = 0;
  3237. this._current = 0;
  3238. this._totalValueCount = 0;
  3239. this._totalAccumulated = 0;
  3240. this._lastSecAccumulated = 0;
  3241. this._lastSecTime = 0;
  3242. this._lastSecValueCount = 0;
  3243. }
  3244. Object.defineProperty(PerfCounter.prototype, "min", {
  3245. /**
  3246. * Returns the smallest value ever
  3247. */
  3248. get: function () {
  3249. return this._min;
  3250. },
  3251. enumerable: true,
  3252. configurable: true
  3253. });
  3254. Object.defineProperty(PerfCounter.prototype, "max", {
  3255. /**
  3256. * Returns the biggest value ever
  3257. */
  3258. get: function () {
  3259. return this._max;
  3260. },
  3261. enumerable: true,
  3262. configurable: true
  3263. });
  3264. Object.defineProperty(PerfCounter.prototype, "average", {
  3265. /**
  3266. * Returns the average value since the performance counter is running
  3267. */
  3268. get: function () {
  3269. return this._average;
  3270. },
  3271. enumerable: true,
  3272. configurable: true
  3273. });
  3274. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  3275. /**
  3276. * Returns the average value of the last second the counter was monitored
  3277. */
  3278. get: function () {
  3279. return this._lastSecAverage;
  3280. },
  3281. enumerable: true,
  3282. configurable: true
  3283. });
  3284. Object.defineProperty(PerfCounter.prototype, "current", {
  3285. /**
  3286. * Returns the current value
  3287. */
  3288. get: function () {
  3289. return this._current;
  3290. },
  3291. enumerable: true,
  3292. configurable: true
  3293. });
  3294. Object.defineProperty(PerfCounter.prototype, "total", {
  3295. /**
  3296. * Gets the accumulated total
  3297. */
  3298. get: function () {
  3299. return this._totalAccumulated;
  3300. },
  3301. enumerable: true,
  3302. configurable: true
  3303. });
  3304. Object.defineProperty(PerfCounter.prototype, "count", {
  3305. /**
  3306. * Gets the total value count
  3307. */
  3308. get: function () {
  3309. return this._totalValueCount;
  3310. },
  3311. enumerable: true,
  3312. configurable: true
  3313. });
  3314. /**
  3315. * Call this method to start monitoring a new frame.
  3316. * 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.
  3317. */
  3318. PerfCounter.prototype.fetchNewFrame = function () {
  3319. this._totalValueCount++;
  3320. this._current = 0;
  3321. this._lastSecValueCount++;
  3322. };
  3323. /**
  3324. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  3325. * @param newCount the count value to add to the monitored count
  3326. * @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.
  3327. */
  3328. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  3329. if (!PerfCounter.Enabled) {
  3330. return;
  3331. }
  3332. this._current += newCount;
  3333. if (fetchResult) {
  3334. this._fetchResult();
  3335. }
  3336. };
  3337. /**
  3338. * Start monitoring this performance counter
  3339. */
  3340. PerfCounter.prototype.beginMonitoring = function () {
  3341. if (!PerfCounter.Enabled) {
  3342. return;
  3343. }
  3344. this._startMonitoringTime = Tools.Now;
  3345. };
  3346. /**
  3347. * Compute the time lapsed since the previous beginMonitoring() call.
  3348. * @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
  3349. */
  3350. PerfCounter.prototype.endMonitoring = function (newFrame) {
  3351. if (newFrame === void 0) { newFrame = true; }
  3352. if (!PerfCounter.Enabled) {
  3353. return;
  3354. }
  3355. if (newFrame) {
  3356. this.fetchNewFrame();
  3357. }
  3358. var currentTime = Tools.Now;
  3359. this._current = currentTime - this._startMonitoringTime;
  3360. if (newFrame) {
  3361. this._fetchResult();
  3362. }
  3363. };
  3364. PerfCounter.prototype._fetchResult = function () {
  3365. this._totalAccumulated += this._current;
  3366. this._lastSecAccumulated += this._current;
  3367. // Min/Max update
  3368. this._min = Math.min(this._min, this._current);
  3369. this._max = Math.max(this._max, this._current);
  3370. this._average = this._totalAccumulated / this._totalValueCount;
  3371. // Reset last sec?
  3372. var now = Tools.Now;
  3373. if ((now - this._lastSecTime) > 1000) {
  3374. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  3375. this._lastSecTime = now;
  3376. this._lastSecAccumulated = 0;
  3377. this._lastSecValueCount = 0;
  3378. }
  3379. };
  3380. /**
  3381. * Gets or sets a global boolean to turn on and off all the counters
  3382. */
  3383. PerfCounter.Enabled = true;
  3384. return PerfCounter;
  3385. }());
  3386. BABYLON.PerfCounter = PerfCounter;
  3387. /**
  3388. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  3389. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  3390. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  3391. * @param name The name of the class, case should be preserved
  3392. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  3393. */
  3394. function className(name, module) {
  3395. return function (target) {
  3396. target["__bjsclassName__"] = name;
  3397. target["__bjsmoduleName__"] = (module != null) ? module : null;
  3398. };
  3399. }
  3400. BABYLON.className = className;
  3401. /**
  3402. * An implementation of a loop for asynchronous functions.
  3403. */
  3404. var AsyncLoop = /** @class */ (function () {
  3405. /**
  3406. * Constructor.
  3407. * @param iterations the number of iterations.
  3408. * @param func the function to run each iteration
  3409. * @param successCallback the callback that will be called upon succesful execution
  3410. * @param offset starting offset.
  3411. */
  3412. function AsyncLoop(
  3413. /**
  3414. * Defines the number of iterations for the loop
  3415. */
  3416. iterations, func, successCallback, offset) {
  3417. if (offset === void 0) { offset = 0; }
  3418. this.iterations = iterations;
  3419. this.index = offset - 1;
  3420. this._done = false;
  3421. this._fn = func;
  3422. this._successCallback = successCallback;
  3423. }
  3424. /**
  3425. * Execute the next iteration. Must be called after the last iteration was finished.
  3426. */
  3427. AsyncLoop.prototype.executeNext = function () {
  3428. if (!this._done) {
  3429. if (this.index + 1 < this.iterations) {
  3430. ++this.index;
  3431. this._fn(this);
  3432. }
  3433. else {
  3434. this.breakLoop();
  3435. }
  3436. }
  3437. };
  3438. /**
  3439. * Break the loop and run the success callback.
  3440. */
  3441. AsyncLoop.prototype.breakLoop = function () {
  3442. this._done = true;
  3443. this._successCallback();
  3444. };
  3445. /**
  3446. * Create and run an async loop.
  3447. * @param iterations the number of iterations.
  3448. * @param fn the function to run each iteration
  3449. * @param successCallback the callback that will be called upon succesful execution
  3450. * @param offset starting offset.
  3451. * @returns the created async loop object
  3452. */
  3453. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  3454. if (offset === void 0) { offset = 0; }
  3455. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  3456. loop.executeNext();
  3457. return loop;
  3458. };
  3459. /**
  3460. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3461. * @param iterations total number of iterations
  3462. * @param syncedIterations number of synchronous iterations in each async iteration.
  3463. * @param fn the function to call each iteration.
  3464. * @param callback a success call back that will be called when iterating stops.
  3465. * @param breakFunction a break condition (optional)
  3466. * @param timeout timeout settings for the setTimeout function. default - 0.
  3467. * @returns the created async loop object
  3468. */
  3469. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3470. if (timeout === void 0) { timeout = 0; }
  3471. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3472. if (breakFunction && breakFunction()) {
  3473. loop.breakLoop();
  3474. }
  3475. else {
  3476. setTimeout(function () {
  3477. for (var i = 0; i < syncedIterations; ++i) {
  3478. var iteration = (loop.index * syncedIterations) + i;
  3479. if (iteration >= iterations) {
  3480. break;
  3481. }
  3482. fn(iteration);
  3483. if (breakFunction && breakFunction()) {
  3484. loop.breakLoop();
  3485. break;
  3486. }
  3487. }
  3488. loop.executeNext();
  3489. }, timeout);
  3490. }
  3491. }, callback);
  3492. };
  3493. return AsyncLoop;
  3494. }());
  3495. BABYLON.AsyncLoop = AsyncLoop;
  3496. })(BABYLON || (BABYLON = {}));
  3497. //# sourceMappingURL=babylon.tools.js.map
  3498. var BABYLON;
  3499. (function (BABYLON) {
  3500. /**
  3501. * Constant used to convert a value to gamma space
  3502. * @ignorenaming
  3503. */
  3504. BABYLON.ToGammaSpace = 1 / 2.2;
  3505. /**
  3506. * Constant used to convert a value to linear space
  3507. * @ignorenaming
  3508. */
  3509. BABYLON.ToLinearSpace = 2.2;
  3510. /**
  3511. * Constant used to define the minimal number value in Babylon.js
  3512. * @ignorenaming
  3513. */
  3514. BABYLON.Epsilon = 0.001;
  3515. /**
  3516. * Class used to hold a RBG color
  3517. */
  3518. var Color3 = /** @class */ (function () {
  3519. /**
  3520. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  3521. * @param r defines the red component (between 0 and 1, default is 0)
  3522. * @param g defines the green component (between 0 and 1, default is 0)
  3523. * @param b defines the blue component (between 0 and 1, default is 0)
  3524. */
  3525. function Color3(
  3526. /**
  3527. * Defines the red component (between 0 and 1, default is 0)
  3528. */
  3529. r,
  3530. /**
  3531. * Defines the green component (between 0 and 1, default is 0)
  3532. */
  3533. g,
  3534. /**
  3535. * Defines the blue component (between 0 and 1, default is 0)
  3536. */
  3537. b) {
  3538. if (r === void 0) { r = 0; }
  3539. if (g === void 0) { g = 0; }
  3540. if (b === void 0) { b = 0; }
  3541. this.r = r;
  3542. this.g = g;
  3543. this.b = b;
  3544. }
  3545. /**
  3546. * Creates a string with the Color3 current values
  3547. * @returns the string representation of the Color3 object
  3548. */
  3549. Color3.prototype.toString = function () {
  3550. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  3551. };
  3552. /**
  3553. * Returns the string "Color3"
  3554. * @returns "Color3"
  3555. */
  3556. Color3.prototype.getClassName = function () {
  3557. return "Color3";
  3558. };
  3559. /**
  3560. * Compute the Color3 hash code
  3561. * @returns an unique number that can be used to hash Color3 objects
  3562. */
  3563. Color3.prototype.getHashCode = function () {
  3564. var hash = this.r || 0;
  3565. hash = (hash * 397) ^ (this.g || 0);
  3566. hash = (hash * 397) ^ (this.b || 0);
  3567. return hash;
  3568. };
  3569. // Operators
  3570. /**
  3571. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  3572. * @param array defines the array where to store the r,g,b components
  3573. * @param index defines an optional index in the target array to define where to start storing values
  3574. * @returns the current Color3 object
  3575. */
  3576. Color3.prototype.toArray = function (array, index) {
  3577. if (index === undefined) {
  3578. index = 0;
  3579. }
  3580. array[index] = this.r;
  3581. array[index + 1] = this.g;
  3582. array[index + 2] = this.b;
  3583. return this;
  3584. };
  3585. /**
  3586. * Returns a new Color4 object from the current Color3 and the given alpha
  3587. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  3588. * @returns a new Color4 object
  3589. */
  3590. Color3.prototype.toColor4 = function (alpha) {
  3591. if (alpha === void 0) { alpha = 1; }
  3592. return new Color4(this.r, this.g, this.b, alpha);
  3593. };
  3594. /**
  3595. * Returns a new array populated with 3 numeric elements : red, green and blue values
  3596. * @returns the new array
  3597. */
  3598. Color3.prototype.asArray = function () {
  3599. var result = new Array();
  3600. this.toArray(result, 0);
  3601. return result;
  3602. };
  3603. /**
  3604. * Returns the luminance value
  3605. * @returns a float value
  3606. */
  3607. Color3.prototype.toLuminance = function () {
  3608. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  3609. };
  3610. /**
  3611. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  3612. * @param otherColor defines the second operand
  3613. * @returns the new Color3 object
  3614. */
  3615. Color3.prototype.multiply = function (otherColor) {
  3616. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  3617. };
  3618. /**
  3619. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  3620. * @param otherColor defines the second operand
  3621. * @param result defines the Color3 object where to store the result
  3622. * @returns the current Color3
  3623. */
  3624. Color3.prototype.multiplyToRef = function (otherColor, result) {
  3625. result.r = this.r * otherColor.r;
  3626. result.g = this.g * otherColor.g;
  3627. result.b = this.b * otherColor.b;
  3628. return this;
  3629. };
  3630. /**
  3631. * Determines equality between Color3 objects
  3632. * @param otherColor defines the second operand
  3633. * @returns true if the rgb values are equal to the given ones
  3634. */
  3635. Color3.prototype.equals = function (otherColor) {
  3636. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  3637. };
  3638. /**
  3639. * Determines equality between the current Color3 object and a set of r,b,g values
  3640. * @param r defines the red component to check
  3641. * @param g defines the green component to check
  3642. * @param b defines the blue component to check
  3643. * @returns true if the rgb values are equal to the given ones
  3644. */
  3645. Color3.prototype.equalsFloats = function (r, g, b) {
  3646. return this.r === r && this.g === g && this.b === b;
  3647. };
  3648. /**
  3649. * Multiplies in place each rgb value by scale
  3650. * @param scale defines the scaling factor
  3651. * @returns the updated Color3
  3652. */
  3653. Color3.prototype.scale = function (scale) {
  3654. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  3655. };
  3656. /**
  3657. * Multiplies the rgb values by scale and stores the result into "result"
  3658. * @param scale defines the scaling factor
  3659. * @param result defines the Color3 object where to store the result
  3660. * @returns the unmodified current Color3
  3661. */
  3662. Color3.prototype.scaleToRef = function (scale, result) {
  3663. result.r = this.r * scale;
  3664. result.g = this.g * scale;
  3665. result.b = this.b * scale;
  3666. return this;
  3667. };
  3668. /**
  3669. * Scale the current Color3 values by a factor and add the result to a given Color3
  3670. * @param scale defines the scale factor
  3671. * @param result defines color to store the result into
  3672. * @returns the unmodified current Color3
  3673. */
  3674. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  3675. result.r += this.r * scale;
  3676. result.g += this.g * scale;
  3677. result.b += this.b * scale;
  3678. return this;
  3679. };
  3680. /**
  3681. * Clamps the rgb values by the min and max values and stores the result into "result"
  3682. * @param min defines minimum clamping value (default is 0)
  3683. * @param max defines maximum clamping value (default is 1)
  3684. * @param result defines color to store the result into
  3685. * @returns the original Color3
  3686. */
  3687. Color3.prototype.clampToRef = function (min, max, result) {
  3688. if (min === void 0) { min = 0; }
  3689. if (max === void 0) { max = 1; }
  3690. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  3691. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  3692. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  3693. return this;
  3694. };
  3695. /**
  3696. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  3697. * @param otherColor defines the second operand
  3698. * @returns the new Color3
  3699. */
  3700. Color3.prototype.add = function (otherColor) {
  3701. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  3702. };
  3703. /**
  3704. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  3705. * @param otherColor defines the second operand
  3706. * @param result defines Color3 object to store the result into
  3707. * @returns the unmodified current Color3
  3708. */
  3709. Color3.prototype.addToRef = function (otherColor, result) {
  3710. result.r = this.r + otherColor.r;
  3711. result.g = this.g + otherColor.g;
  3712. result.b = this.b + otherColor.b;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  3717. * @param otherColor defines the second operand
  3718. * @returns the new Color3
  3719. */
  3720. Color3.prototype.subtract = function (otherColor) {
  3721. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  3722. };
  3723. /**
  3724. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  3725. * @param otherColor defines the second operand
  3726. * @param result defines Color3 object to store the result into
  3727. * @returns the unmodified current Color3
  3728. */
  3729. Color3.prototype.subtractToRef = function (otherColor, result) {
  3730. result.r = this.r - otherColor.r;
  3731. result.g = this.g - otherColor.g;
  3732. result.b = this.b - otherColor.b;
  3733. return this;
  3734. };
  3735. /**
  3736. * Copy the current object
  3737. * @returns a new Color3 copied the current one
  3738. */
  3739. Color3.prototype.clone = function () {
  3740. return new Color3(this.r, this.g, this.b);
  3741. };
  3742. /**
  3743. * Copies the rgb values from the source in the current Color3
  3744. * @param source defines the source Color3 object
  3745. * @returns the updated Color3 object
  3746. */
  3747. Color3.prototype.copyFrom = function (source) {
  3748. this.r = source.r;
  3749. this.g = source.g;
  3750. this.b = source.b;
  3751. return this;
  3752. };
  3753. /**
  3754. * Updates the Color3 rgb values from the given floats
  3755. * @param r defines the red component to read from
  3756. * @param g defines the green component to read from
  3757. * @param b defines the blue component to read from
  3758. * @returns the current Color3 object
  3759. */
  3760. Color3.prototype.copyFromFloats = function (r, g, b) {
  3761. this.r = r;
  3762. this.g = g;
  3763. this.b = b;
  3764. return this;
  3765. };
  3766. /**
  3767. * Updates the Color3 rgb values from the given floats
  3768. * @param r defines the red component to read from
  3769. * @param g defines the green component to read from
  3770. * @param b defines the blue component to read from
  3771. * @returns the current Color3 object
  3772. */
  3773. Color3.prototype.set = function (r, g, b) {
  3774. return this.copyFromFloats(r, g, b);
  3775. };
  3776. /**
  3777. * Compute the Color3 hexadecimal code as a string
  3778. * @returns a string containing the hexadecimal representation of the Color3 object
  3779. */
  3780. Color3.prototype.toHexString = function () {
  3781. var intR = (this.r * 255) | 0;
  3782. var intG = (this.g * 255) | 0;
  3783. var intB = (this.b * 255) | 0;
  3784. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  3785. };
  3786. /**
  3787. * Computes a new Color3 converted from the current one to linear space
  3788. * @returns a new Color3 object
  3789. */
  3790. Color3.prototype.toLinearSpace = function () {
  3791. var convertedColor = new Color3();
  3792. this.toLinearSpaceToRef(convertedColor);
  3793. return convertedColor;
  3794. };
  3795. /**
  3796. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  3797. * @param convertedColor defines the Color3 object where to store the linear space version
  3798. * @returns the unmodified Color3
  3799. */
  3800. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  3801. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  3802. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  3803. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  3804. return this;
  3805. };
  3806. /**
  3807. * Computes a new Color3 converted from the current one to gamma space
  3808. * @returns a new Color3 object
  3809. */
  3810. Color3.prototype.toGammaSpace = function () {
  3811. var convertedColor = new Color3();
  3812. this.toGammaSpaceToRef(convertedColor);
  3813. return convertedColor;
  3814. };
  3815. /**
  3816. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  3817. * @param convertedColor defines the Color3 object where to store the gamma space version
  3818. * @returns the unmodified Color3
  3819. */
  3820. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  3821. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  3822. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  3823. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  3824. return this;
  3825. };
  3826. // Statics
  3827. /**
  3828. * Creates a new Color3 from the string containing valid hexadecimal values
  3829. * @param hex defines a string containing valid hexadecimal values
  3830. * @returns a new Color3 object
  3831. */
  3832. Color3.FromHexString = function (hex) {
  3833. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  3834. return new Color3(0, 0, 0);
  3835. }
  3836. var r = parseInt(hex.substring(1, 3), 16);
  3837. var g = parseInt(hex.substring(3, 5), 16);
  3838. var b = parseInt(hex.substring(5, 7), 16);
  3839. return Color3.FromInts(r, g, b);
  3840. };
  3841. /**
  3842. * Creates a new Vector3 from the starting index of the given array
  3843. * @param array defines the source array
  3844. * @param offset defines an offset in the source array
  3845. * @returns a new Color3 object
  3846. */
  3847. Color3.FromArray = function (array, offset) {
  3848. if (offset === void 0) { offset = 0; }
  3849. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  3850. };
  3851. /**
  3852. * Creates a new Color3 from integer values (< 256)
  3853. * @param r defines the red component to read from (value between 0 and 255)
  3854. * @param g defines the green component to read from (value between 0 and 255)
  3855. * @param b defines the blue component to read from (value between 0 and 255)
  3856. * @returns a new Color3 object
  3857. */
  3858. Color3.FromInts = function (r, g, b) {
  3859. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  3860. };
  3861. /**
  3862. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3863. * @param start defines the start Color3 value
  3864. * @param end defines the end Color3 value
  3865. * @param amount defines the gradient value between start and end
  3866. * @returns a new Color3 object
  3867. */
  3868. Color3.Lerp = function (start, end, amount) {
  3869. var result = new Color3(0.0, 0.0, 0.0);
  3870. Color3.LerpToRef(start, end, amount, result);
  3871. return result;
  3872. };
  3873. /**
  3874. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3875. * @param left defines the start value
  3876. * @param right defines the end value
  3877. * @param amount defines the gradient factor
  3878. * @param result defines the Color3 object where to store the result
  3879. */
  3880. Color3.LerpToRef = function (left, right, amount, result) {
  3881. result.r = left.r + ((right.r - left.r) * amount);
  3882. result.g = left.g + ((right.g - left.g) * amount);
  3883. result.b = left.b + ((right.b - left.b) * amount);
  3884. };
  3885. /**
  3886. * Returns a Color3 value containing a red color
  3887. * @returns a new Color3 object
  3888. */
  3889. Color3.Red = function () { return new Color3(1, 0, 0); };
  3890. /**
  3891. * Returns a Color3 value containing a green color
  3892. * @returns a new Color3 object
  3893. */
  3894. Color3.Green = function () { return new Color3(0, 1, 0); };
  3895. /**
  3896. * Returns a Color3 value containing a blue color
  3897. * @returns a new Color3 object
  3898. */
  3899. Color3.Blue = function () { return new Color3(0, 0, 1); };
  3900. /**
  3901. * Returns a Color3 value containing a black color
  3902. * @returns a new Color3 object
  3903. */
  3904. Color3.Black = function () { return new Color3(0, 0, 0); };
  3905. /**
  3906. * Returns a Color3 value containing a white color
  3907. * @returns a new Color3 object
  3908. */
  3909. Color3.White = function () { return new Color3(1, 1, 1); };
  3910. /**
  3911. * Returns a Color3 value containing a purple color
  3912. * @returns a new Color3 object
  3913. */
  3914. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  3915. /**
  3916. * Returns a Color3 value containing a magenta color
  3917. * @returns a new Color3 object
  3918. */
  3919. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  3920. /**
  3921. * Returns a Color3 value containing a yellow color
  3922. * @returns a new Color3 object
  3923. */
  3924. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  3925. /**
  3926. * Returns a Color3 value containing a gray color
  3927. * @returns a new Color3 object
  3928. */
  3929. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  3930. /**
  3931. * Returns a Color3 value containing a teal color
  3932. * @returns a new Color3 object
  3933. */
  3934. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  3935. /**
  3936. * Returns a Color3 value containing a random color
  3937. * @returns a new Color3 object
  3938. */
  3939. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  3940. return Color3;
  3941. }());
  3942. BABYLON.Color3 = Color3;
  3943. /**
  3944. * Class used to hold a RBGA color
  3945. */
  3946. var Color4 = /** @class */ (function () {
  3947. /**
  3948. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  3949. * @param r defines the red component (between 0 and 1, default is 0)
  3950. * @param g defines the green component (between 0 and 1, default is 0)
  3951. * @param b defines the blue component (between 0 and 1, default is 0)
  3952. * @param a defines the alpha component (between 0 and 1, default is 1)
  3953. */
  3954. function Color4(
  3955. /**
  3956. * Defines the red component (between 0 and 1, default is 0)
  3957. */
  3958. r,
  3959. /**
  3960. * Defines the green component (between 0 and 1, default is 0)
  3961. */
  3962. g,
  3963. /**
  3964. * Defines the blue component (between 0 and 1, default is 0)
  3965. */
  3966. b,
  3967. /**
  3968. * Defines the alpha component (between 0 and 1, default is 1)
  3969. */
  3970. a) {
  3971. if (r === void 0) { r = 0; }
  3972. if (g === void 0) { g = 0; }
  3973. if (b === void 0) { b = 0; }
  3974. if (a === void 0) { a = 1; }
  3975. this.r = r;
  3976. this.g = g;
  3977. this.b = b;
  3978. this.a = a;
  3979. }
  3980. // Operators
  3981. /**
  3982. * Adds in place the given Color4 values to the current Color4 object
  3983. * @param right defines the second operand
  3984. * @returns the current updated Color4 object
  3985. */
  3986. Color4.prototype.addInPlace = function (right) {
  3987. this.r += right.r;
  3988. this.g += right.g;
  3989. this.b += right.b;
  3990. this.a += right.a;
  3991. return this;
  3992. };
  3993. /**
  3994. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  3995. * @returns the new array
  3996. */
  3997. Color4.prototype.asArray = function () {
  3998. var result = new Array();
  3999. this.toArray(result, 0);
  4000. return result;
  4001. };
  4002. /**
  4003. * Stores from the starting index in the given array the Color4 successive values
  4004. * @param array defines the array where to store the r,g,b components
  4005. * @param index defines an optional index in the target array to define where to start storing values
  4006. * @returns the current Color4 object
  4007. */
  4008. Color4.prototype.toArray = function (array, index) {
  4009. if (index === void 0) { index = 0; }
  4010. array[index] = this.r;
  4011. array[index + 1] = this.g;
  4012. array[index + 2] = this.b;
  4013. array[index + 3] = this.a;
  4014. return this;
  4015. };
  4016. /**
  4017. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  4018. * @param right defines the second operand
  4019. * @returns a new Color4 object
  4020. */
  4021. Color4.prototype.add = function (right) {
  4022. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  4023. };
  4024. /**
  4025. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  4026. * @param right defines the second operand
  4027. * @returns a new Color4 object
  4028. */
  4029. Color4.prototype.subtract = function (right) {
  4030. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  4031. };
  4032. /**
  4033. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  4034. * @param right defines the second operand
  4035. * @param result defines the Color4 object where to store the result
  4036. * @returns the current Color4 object
  4037. */
  4038. Color4.prototype.subtractToRef = function (right, result) {
  4039. result.r = this.r - right.r;
  4040. result.g = this.g - right.g;
  4041. result.b = this.b - right.b;
  4042. result.a = this.a - right.a;
  4043. return this;
  4044. };
  4045. /**
  4046. * Creates a new Color4 with the current Color4 values multiplied by scale
  4047. * @param scale defines the scaling factor to apply
  4048. * @returns a new Color4 object
  4049. */
  4050. Color4.prototype.scale = function (scale) {
  4051. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  4052. };
  4053. /**
  4054. * Multiplies the current Color4 values by scale and stores the result in "result"
  4055. * @param scale defines the scaling factor to apply
  4056. * @param result defines the Color4 object where to store the result
  4057. * @returns the current unmodified Color4
  4058. */
  4059. Color4.prototype.scaleToRef = function (scale, result) {
  4060. result.r = this.r * scale;
  4061. result.g = this.g * scale;
  4062. result.b = this.b * scale;
  4063. result.a = this.a * scale;
  4064. return this;
  4065. };
  4066. /**
  4067. * Scale the current Color4 values by a factor and add the result to a given Color4
  4068. * @param scale defines the scale factor
  4069. * @param result defines the Color4 object where to store the result
  4070. * @returns the unmodified current Color4
  4071. */
  4072. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  4073. result.r += this.r * scale;
  4074. result.g += this.g * scale;
  4075. result.b += this.b * scale;
  4076. result.a += this.a * scale;
  4077. return this;
  4078. };
  4079. /**
  4080. * Clamps the rgb values by the min and max values and stores the result into "result"
  4081. * @param min defines minimum clamping value (default is 0)
  4082. * @param max defines maximum clamping value (default is 1)
  4083. * @param result defines color to store the result into.
  4084. * @returns the cuurent Color4
  4085. */
  4086. Color4.prototype.clampToRef = function (min, max, result) {
  4087. if (min === void 0) { min = 0; }
  4088. if (max === void 0) { max = 1; }
  4089. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  4090. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  4091. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  4092. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  4093. return this;
  4094. };
  4095. /**
  4096. * Multipy an Color4 value by another and return a new Color4 object
  4097. * @param color defines the Color4 value to multiply by
  4098. * @returns a new Color4 object
  4099. */
  4100. Color4.prototype.multiply = function (color) {
  4101. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  4102. };
  4103. /**
  4104. * Multipy a Color4 value by another and push the result in a reference value
  4105. * @param color defines the Color4 value to multiply by
  4106. * @param result defines the Color4 to fill the result in
  4107. * @returns the result Color4
  4108. */
  4109. Color4.prototype.multiplyToRef = function (color, result) {
  4110. result.r = this.r * color.r;
  4111. result.g = this.g * color.g;
  4112. result.b = this.b * color.b;
  4113. result.a = this.a * color.a;
  4114. return result;
  4115. };
  4116. /**
  4117. * Creates a string with the Color4 current values
  4118. * @returns the string representation of the Color4 object
  4119. */
  4120. Color4.prototype.toString = function () {
  4121. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  4122. };
  4123. /**
  4124. * Returns the string "Color4"
  4125. * @returns "Color4"
  4126. */
  4127. Color4.prototype.getClassName = function () {
  4128. return "Color4";
  4129. };
  4130. /**
  4131. * Compute the Color4 hash code
  4132. * @returns an unique number that can be used to hash Color4 objects
  4133. */
  4134. Color4.prototype.getHashCode = function () {
  4135. var hash = this.r || 0;
  4136. hash = (hash * 397) ^ (this.g || 0);
  4137. hash = (hash * 397) ^ (this.b || 0);
  4138. hash = (hash * 397) ^ (this.a || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Creates a new Color4 copied from the current one
  4143. * @returns a new Color4 object
  4144. */
  4145. Color4.prototype.clone = function () {
  4146. return new Color4(this.r, this.g, this.b, this.a);
  4147. };
  4148. /**
  4149. * Copies the given Color4 values into the current one
  4150. * @param source defines the source Color4 object
  4151. * @returns the current updated Color4 object
  4152. */
  4153. Color4.prototype.copyFrom = function (source) {
  4154. this.r = source.r;
  4155. this.g = source.g;
  4156. this.b = source.b;
  4157. this.a = source.a;
  4158. return this;
  4159. };
  4160. /**
  4161. * Copies the given float values into the current one
  4162. * @param r defines the red component to read from
  4163. * @param g defines the green component to read from
  4164. * @param b defines the blue component to read from
  4165. * @param a defines the alpha component to read from
  4166. * @returns the current updated Color4 object
  4167. */
  4168. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  4169. this.r = r;
  4170. this.g = g;
  4171. this.b = b;
  4172. this.a = a;
  4173. return this;
  4174. };
  4175. /**
  4176. * Copies the given float values into the current one
  4177. * @param r defines the red component to read from
  4178. * @param g defines the green component to read from
  4179. * @param b defines the blue component to read from
  4180. * @param a defines the alpha component to read from
  4181. * @returns the current updated Color4 object
  4182. */
  4183. Color4.prototype.set = function (r, g, b, a) {
  4184. return this.copyFromFloats(r, g, b, a);
  4185. };
  4186. /**
  4187. * Compute the Color4 hexadecimal code as a string
  4188. * @returns a string containing the hexadecimal representation of the Color4 object
  4189. */
  4190. Color4.prototype.toHexString = function () {
  4191. var intR = (this.r * 255) | 0;
  4192. var intG = (this.g * 255) | 0;
  4193. var intB = (this.b * 255) | 0;
  4194. var intA = (this.a * 255) | 0;
  4195. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  4196. };
  4197. /**
  4198. * Computes a new Color4 converted from the current one to linear space
  4199. * @returns a new Color4 object
  4200. */
  4201. Color4.prototype.toLinearSpace = function () {
  4202. var convertedColor = new Color4();
  4203. this.toLinearSpaceToRef(convertedColor);
  4204. return convertedColor;
  4205. };
  4206. /**
  4207. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  4208. * @param convertedColor defines the Color4 object where to store the linear space version
  4209. * @returns the unmodified Color4
  4210. */
  4211. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  4212. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  4213. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  4214. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  4215. convertedColor.a = this.a;
  4216. return this;
  4217. };
  4218. /**
  4219. * Computes a new Color4 converted from the current one to gamma space
  4220. * @returns a new Color4 object
  4221. */
  4222. Color4.prototype.toGammaSpace = function () {
  4223. var convertedColor = new Color4();
  4224. this.toGammaSpaceToRef(convertedColor);
  4225. return convertedColor;
  4226. };
  4227. /**
  4228. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  4229. * @param convertedColor defines the Color4 object where to store the gamma space version
  4230. * @returns the unmodified Color4
  4231. */
  4232. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  4233. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  4234. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  4235. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  4236. convertedColor.a = this.a;
  4237. return this;
  4238. };
  4239. // Statics
  4240. /**
  4241. * Creates a new Color4 from the string containing valid hexadecimal values
  4242. * @param hex defines a string containing valid hexadecimal values
  4243. * @returns a new Color4 object
  4244. */
  4245. Color4.FromHexString = function (hex) {
  4246. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  4247. return new Color4(0.0, 0.0, 0.0, 0.0);
  4248. }
  4249. var r = parseInt(hex.substring(1, 3), 16);
  4250. var g = parseInt(hex.substring(3, 5), 16);
  4251. var b = parseInt(hex.substring(5, 7), 16);
  4252. var a = parseInt(hex.substring(7, 9), 16);
  4253. return Color4.FromInts(r, g, b, a);
  4254. };
  4255. /**
  4256. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4257. * @param left defines the start value
  4258. * @param right defines the end value
  4259. * @param amount defines the gradient factor
  4260. * @returns a new Color4 object
  4261. */
  4262. Color4.Lerp = function (left, right, amount) {
  4263. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  4264. Color4.LerpToRef(left, right, amount, result);
  4265. return result;
  4266. };
  4267. /**
  4268. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4269. * @param left defines the start value
  4270. * @param right defines the end value
  4271. * @param amount defines the gradient factor
  4272. * @param result defines the Color4 object where to store data
  4273. */
  4274. Color4.LerpToRef = function (left, right, amount, result) {
  4275. result.r = left.r + (right.r - left.r) * amount;
  4276. result.g = left.g + (right.g - left.g) * amount;
  4277. result.b = left.b + (right.b - left.b) * amount;
  4278. result.a = left.a + (right.a - left.a) * amount;
  4279. };
  4280. /**
  4281. * Creates a new Color4 from a Color3 and an alpha value
  4282. * @param color3 defines the source Color3 to read from
  4283. * @param alpha defines the alpha component (1.0 by default)
  4284. * @returns a new Color4 object
  4285. */
  4286. Color4.FromColor3 = function (color3, alpha) {
  4287. if (alpha === void 0) { alpha = 1.0; }
  4288. return new Color4(color3.r, color3.g, color3.b, alpha);
  4289. };
  4290. /**
  4291. * Creates a new Color4 from the starting index element of the given array
  4292. * @param array defines the source array to read from
  4293. * @param offset defines the offset in the source array
  4294. * @returns a new Color4 object
  4295. */
  4296. Color4.FromArray = function (array, offset) {
  4297. if (offset === void 0) { offset = 0; }
  4298. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4299. };
  4300. /**
  4301. * Creates a new Color3 from integer values (< 256)
  4302. * @param r defines the red component to read from (value between 0 and 255)
  4303. * @param g defines the green component to read from (value between 0 and 255)
  4304. * @param b defines the blue component to read from (value between 0 and 255)
  4305. * @param a defines the alpha component to read from (value between 0 and 255)
  4306. * @returns a new Color3 object
  4307. */
  4308. Color4.FromInts = function (r, g, b, a) {
  4309. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  4310. };
  4311. /**
  4312. * Check the content of a given array and convert it to an array containing RGBA data
  4313. * If the original array was already containing count * 4 values then it is returned directly
  4314. * @param colors defines the array to check
  4315. * @param count defines the number of RGBA data to expect
  4316. * @returns an array containing count * 4 values (RGBA)
  4317. */
  4318. Color4.CheckColors4 = function (colors, count) {
  4319. // Check if color3 was used
  4320. if (colors.length === count * 3) {
  4321. var colors4 = [];
  4322. for (var index = 0; index < colors.length; index += 3) {
  4323. var newIndex = (index / 3) * 4;
  4324. colors4[newIndex] = colors[index];
  4325. colors4[newIndex + 1] = colors[index + 1];
  4326. colors4[newIndex + 2] = colors[index + 2];
  4327. colors4[newIndex + 3] = 1.0;
  4328. }
  4329. return colors4;
  4330. }
  4331. return colors;
  4332. };
  4333. return Color4;
  4334. }());
  4335. BABYLON.Color4 = Color4;
  4336. /**
  4337. * Class representing a vector containing 2 coordinates
  4338. */
  4339. var Vector2 = /** @class */ (function () {
  4340. /**
  4341. * Creates a new Vector2 from the given x and y coordinates
  4342. * @param x defines the first coordinate
  4343. * @param y defines the second coordinate
  4344. */
  4345. function Vector2(
  4346. /** defines the first coordinate */
  4347. x,
  4348. /** defines the second coordinate */
  4349. y) {
  4350. if (x === void 0) { x = 0; }
  4351. if (y === void 0) { y = 0; }
  4352. this.x = x;
  4353. this.y = y;
  4354. }
  4355. /**
  4356. * Gets a string with the Vector2 coordinates
  4357. * @returns a string with the Vector2 coordinates
  4358. */
  4359. Vector2.prototype.toString = function () {
  4360. return "{X: " + this.x + " Y:" + this.y + "}";
  4361. };
  4362. /**
  4363. * Gets class name
  4364. * @returns the string "Vector2"
  4365. */
  4366. Vector2.prototype.getClassName = function () {
  4367. return "Vector2";
  4368. };
  4369. /**
  4370. * Gets current vector hash code
  4371. * @returns the Vector2 hash code as a number
  4372. */
  4373. Vector2.prototype.getHashCode = function () {
  4374. var hash = this.x || 0;
  4375. hash = (hash * 397) ^ (this.y || 0);
  4376. return hash;
  4377. };
  4378. // Operators
  4379. /**
  4380. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  4381. * @param array defines the source array
  4382. * @param index defines the offset in source array
  4383. * @returns the current Vector2
  4384. */
  4385. Vector2.prototype.toArray = function (array, index) {
  4386. if (index === void 0) { index = 0; }
  4387. array[index] = this.x;
  4388. array[index + 1] = this.y;
  4389. return this;
  4390. };
  4391. /**
  4392. * Copy the current vector to an array
  4393. * @returns a new array with 2 elements: the Vector2 coordinates.
  4394. */
  4395. Vector2.prototype.asArray = function () {
  4396. var result = new Array();
  4397. this.toArray(result, 0);
  4398. return result;
  4399. };
  4400. /**
  4401. * Sets the Vector2 coordinates with the given Vector2 coordinates
  4402. * @param source defines the source Vector2
  4403. * @returns the current updated Vector2
  4404. */
  4405. Vector2.prototype.copyFrom = function (source) {
  4406. this.x = source.x;
  4407. this.y = source.y;
  4408. return this;
  4409. };
  4410. /**
  4411. * Sets the Vector2 coordinates with the given floats
  4412. * @param x defines the first coordinate
  4413. * @param y defines the second coordinate
  4414. * @returns the current updated Vector2
  4415. */
  4416. Vector2.prototype.copyFromFloats = function (x, y) {
  4417. this.x = x;
  4418. this.y = y;
  4419. return this;
  4420. };
  4421. /**
  4422. * Sets the Vector2 coordinates with the given floats
  4423. * @param x defines the first coordinate
  4424. * @param y defines the second coordinate
  4425. * @returns the current updated Vector2
  4426. */
  4427. Vector2.prototype.set = function (x, y) {
  4428. return this.copyFromFloats(x, y);
  4429. };
  4430. /**
  4431. * Add another vector with the current one
  4432. * @param otherVector defines the other vector
  4433. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  4434. */
  4435. Vector2.prototype.add = function (otherVector) {
  4436. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4437. };
  4438. /**
  4439. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  4440. * @param otherVector defines the other vector
  4441. * @param result defines the target vector
  4442. * @returns the unmodified current Vector2
  4443. */
  4444. Vector2.prototype.addToRef = function (otherVector, result) {
  4445. result.x = this.x + otherVector.x;
  4446. result.y = this.y + otherVector.y;
  4447. return this;
  4448. };
  4449. /**
  4450. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  4451. * @param otherVector defines the other vector
  4452. * @returns the current updated Vector2
  4453. */
  4454. Vector2.prototype.addInPlace = function (otherVector) {
  4455. this.x += otherVector.x;
  4456. this.y += otherVector.y;
  4457. return this;
  4458. };
  4459. /**
  4460. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  4461. * @param otherVector defines the other vector
  4462. * @returns a new Vector2
  4463. */
  4464. Vector2.prototype.addVector3 = function (otherVector) {
  4465. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4466. };
  4467. /**
  4468. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  4469. * @param otherVector defines the other vector
  4470. * @returns a new Vector2
  4471. */
  4472. Vector2.prototype.subtract = function (otherVector) {
  4473. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  4474. };
  4475. /**
  4476. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  4477. * @param otherVector defines the other vector
  4478. * @param result defines the target vector
  4479. * @returns the unmodified current Vector2
  4480. */
  4481. Vector2.prototype.subtractToRef = function (otherVector, result) {
  4482. result.x = this.x - otherVector.x;
  4483. result.y = this.y - otherVector.y;
  4484. return this;
  4485. };
  4486. /**
  4487. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  4488. * @param otherVector defines the other vector
  4489. * @returns the current updated Vector2
  4490. */
  4491. Vector2.prototype.subtractInPlace = function (otherVector) {
  4492. this.x -= otherVector.x;
  4493. this.y -= otherVector.y;
  4494. return this;
  4495. };
  4496. /**
  4497. * Multiplies in place the current Vector2 coordinates by the given ones
  4498. * @param otherVector defines the other vector
  4499. * @returns the current updated Vector2
  4500. */
  4501. Vector2.prototype.multiplyInPlace = function (otherVector) {
  4502. this.x *= otherVector.x;
  4503. this.y *= otherVector.y;
  4504. return this;
  4505. };
  4506. /**
  4507. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  4508. * @param otherVector defines the other vector
  4509. * @returns a new Vector2
  4510. */
  4511. Vector2.prototype.multiply = function (otherVector) {
  4512. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  4513. };
  4514. /**
  4515. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  4516. * @param otherVector defines the other vector
  4517. * @param result defines the target vector
  4518. * @returns the unmodified current Vector2
  4519. */
  4520. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  4521. result.x = this.x * otherVector.x;
  4522. result.y = this.y * otherVector.y;
  4523. return this;
  4524. };
  4525. /**
  4526. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  4527. * @param x defines the first coordinate
  4528. * @param y defines the second coordinate
  4529. * @returns a new Vector2
  4530. */
  4531. Vector2.prototype.multiplyByFloats = function (x, y) {
  4532. return new Vector2(this.x * x, this.y * y);
  4533. };
  4534. /**
  4535. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  4536. * @param otherVector defines the other vector
  4537. * @returns a new Vector2
  4538. */
  4539. Vector2.prototype.divide = function (otherVector) {
  4540. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  4541. };
  4542. /**
  4543. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  4544. * @param otherVector defines the other vector
  4545. * @param result defines the target vector
  4546. * @returns the unmodified current Vector2
  4547. */
  4548. Vector2.prototype.divideToRef = function (otherVector, result) {
  4549. result.x = this.x / otherVector.x;
  4550. result.y = this.y / otherVector.y;
  4551. return this;
  4552. };
  4553. /**
  4554. * Divides the current Vector2 coordinates by the given ones
  4555. * @param otherVector defines the other vector
  4556. * @returns the current updated Vector2
  4557. */
  4558. Vector2.prototype.divideInPlace = function (otherVector) {
  4559. return this.divideToRef(otherVector, this);
  4560. };
  4561. /**
  4562. * Gets a new Vector2 with current Vector2 negated coordinates
  4563. * @returns a new Vector2
  4564. */
  4565. Vector2.prototype.negate = function () {
  4566. return new Vector2(-this.x, -this.y);
  4567. };
  4568. /**
  4569. * Multiply the Vector2 coordinates by scale
  4570. * @param scale defines the scaling factor
  4571. * @returns the current updated Vector2
  4572. */
  4573. Vector2.prototype.scaleInPlace = function (scale) {
  4574. this.x *= scale;
  4575. this.y *= scale;
  4576. return this;
  4577. };
  4578. /**
  4579. * Returns a new Vector2 scaled by "scale" from the current Vector2
  4580. * @param scale defines the scaling factor
  4581. * @returns a new Vector2
  4582. */
  4583. Vector2.prototype.scale = function (scale) {
  4584. var result = new Vector2(0, 0);
  4585. this.scaleToRef(scale, result);
  4586. return result;
  4587. };
  4588. /**
  4589. * Scale the current Vector2 values by a factor to a given Vector2
  4590. * @param scale defines the scale factor
  4591. * @param result defines the Vector2 object where to store the result
  4592. * @returns the unmodified current Vector2
  4593. */
  4594. Vector2.prototype.scaleToRef = function (scale, result) {
  4595. result.x = this.x * scale;
  4596. result.y = this.y * scale;
  4597. return this;
  4598. };
  4599. /**
  4600. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  4601. * @param scale defines the scale factor
  4602. * @param result defines the Vector2 object where to store the result
  4603. * @returns the unmodified current Vector2
  4604. */
  4605. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  4606. result.x += this.x * scale;
  4607. result.y += this.y * scale;
  4608. return this;
  4609. };
  4610. /**
  4611. * Gets a boolean if two vectors are equals
  4612. * @param otherVector defines the other vector
  4613. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  4614. */
  4615. Vector2.prototype.equals = function (otherVector) {
  4616. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  4617. };
  4618. /**
  4619. * Gets a boolean if two vectors are equals (using an epsilon value)
  4620. * @param otherVector defines the other vector
  4621. * @param epsilon defines the minimal distance to consider equality
  4622. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  4623. */
  4624. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4625. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4626. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  4627. };
  4628. /**
  4629. * Gets a new Vector2 from current Vector2 floored values
  4630. * @returns a new Vector2
  4631. */
  4632. Vector2.prototype.floor = function () {
  4633. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  4634. };
  4635. /**
  4636. * Gets a new Vector2 from current Vector2 floored values
  4637. * @returns a new Vector2
  4638. */
  4639. Vector2.prototype.fract = function () {
  4640. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  4641. };
  4642. // Properties
  4643. /**
  4644. * Gets the length of the vector
  4645. * @returns the vector length (float)
  4646. */
  4647. Vector2.prototype.length = function () {
  4648. return Math.sqrt(this.x * this.x + this.y * this.y);
  4649. };
  4650. /**
  4651. * Gets the vector squared length
  4652. * @returns the vector squared length (float)
  4653. */
  4654. Vector2.prototype.lengthSquared = function () {
  4655. return (this.x * this.x + this.y * this.y);
  4656. };
  4657. // Methods
  4658. /**
  4659. * Normalize the vector
  4660. * @returns the current updated Vector2
  4661. */
  4662. Vector2.prototype.normalize = function () {
  4663. var len = this.length();
  4664. if (len === 0) {
  4665. return this;
  4666. }
  4667. var num = 1.0 / len;
  4668. this.x *= num;
  4669. this.y *= num;
  4670. return this;
  4671. };
  4672. /**
  4673. * Gets a new Vector2 copied from the Vector2
  4674. * @returns a new Vector2
  4675. */
  4676. Vector2.prototype.clone = function () {
  4677. return new Vector2(this.x, this.y);
  4678. };
  4679. // Statics
  4680. /**
  4681. * Gets a new Vector2(0, 0)
  4682. * @returns a new Vector2
  4683. */
  4684. Vector2.Zero = function () {
  4685. return new Vector2(0, 0);
  4686. };
  4687. /**
  4688. * Gets a new Vector2(1, 1)
  4689. * @returns a new Vector2
  4690. */
  4691. Vector2.One = function () {
  4692. return new Vector2(1, 1);
  4693. };
  4694. /**
  4695. * Gets a new Vector2 set from the given index element of the given array
  4696. * @param array defines the data source
  4697. * @param offset defines the offset in the data source
  4698. * @returns a new Vector2
  4699. */
  4700. Vector2.FromArray = function (array, offset) {
  4701. if (offset === void 0) { offset = 0; }
  4702. return new Vector2(array[offset], array[offset + 1]);
  4703. };
  4704. /**
  4705. * Sets "result" from the given index element of the given array
  4706. * @param array defines the data source
  4707. * @param offset defines the offset in the data source
  4708. * @param result defines the target vector
  4709. */
  4710. Vector2.FromArrayToRef = function (array, offset, result) {
  4711. result.x = array[offset];
  4712. result.y = array[offset + 1];
  4713. };
  4714. /**
  4715. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  4716. * @param value1 defines 1st point of control
  4717. * @param value2 defines 2nd point of control
  4718. * @param value3 defines 3rd point of control
  4719. * @param value4 defines 4th point of control
  4720. * @param amount defines the interpolation factor
  4721. * @returns a new Vector2
  4722. */
  4723. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  4724. var squared = amount * amount;
  4725. var cubed = amount * squared;
  4726. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  4727. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  4728. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  4729. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  4730. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  4731. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  4732. return new Vector2(x, y);
  4733. };
  4734. /**
  4735. * 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".
  4736. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  4737. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  4738. * @param value defines the value to clamp
  4739. * @param min defines the lower limit
  4740. * @param max defines the upper limit
  4741. * @returns a new Vector2
  4742. */
  4743. Vector2.Clamp = function (value, min, max) {
  4744. var x = value.x;
  4745. x = (x > max.x) ? max.x : x;
  4746. x = (x < min.x) ? min.x : x;
  4747. var y = value.y;
  4748. y = (y > max.y) ? max.y : y;
  4749. y = (y < min.y) ? min.y : y;
  4750. return new Vector2(x, y);
  4751. };
  4752. /**
  4753. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  4754. * @param value1 defines the 1st control point
  4755. * @param tangent1 defines the outgoing tangent
  4756. * @param value2 defines the 2nd control point
  4757. * @param tangent2 defines the incoming tangent
  4758. * @param amount defines the interpolation factor
  4759. * @returns a new Vector2
  4760. */
  4761. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4762. var squared = amount * amount;
  4763. var cubed = amount * squared;
  4764. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4765. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4766. var part3 = (cubed - (2.0 * squared)) + amount;
  4767. var part4 = cubed - squared;
  4768. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4769. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4770. return new Vector2(x, y);
  4771. };
  4772. /**
  4773. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  4774. * @param start defines the start vector
  4775. * @param end defines the end vector
  4776. * @param amount defines the interpolation factor
  4777. * @returns a new Vector2
  4778. */
  4779. Vector2.Lerp = function (start, end, amount) {
  4780. var x = start.x + ((end.x - start.x) * amount);
  4781. var y = start.y + ((end.y - start.y) * amount);
  4782. return new Vector2(x, y);
  4783. };
  4784. /**
  4785. * Gets the dot product of the vector "left" and the vector "right"
  4786. * @param left defines first vector
  4787. * @param right defines second vector
  4788. * @returns the dot product (float)
  4789. */
  4790. Vector2.Dot = function (left, right) {
  4791. return left.x * right.x + left.y * right.y;
  4792. };
  4793. /**
  4794. * Returns a new Vector2 equal to the normalized given vector
  4795. * @param vector defines the vector to normalize
  4796. * @returns a new Vector2
  4797. */
  4798. Vector2.Normalize = function (vector) {
  4799. var newVector = vector.clone();
  4800. newVector.normalize();
  4801. return newVector;
  4802. };
  4803. /**
  4804. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  4805. * @param left defines 1st vector
  4806. * @param right defines 2nd vector
  4807. * @returns a new Vector2
  4808. */
  4809. Vector2.Minimize = function (left, right) {
  4810. var x = (left.x < right.x) ? left.x : right.x;
  4811. var y = (left.y < right.y) ? left.y : right.y;
  4812. return new Vector2(x, y);
  4813. };
  4814. /**
  4815. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  4816. * @param left defines 1st vector
  4817. * @param right defines 2nd vector
  4818. * @returns a new Vector2
  4819. */
  4820. Vector2.Maximize = function (left, right) {
  4821. var x = (left.x > right.x) ? left.x : right.x;
  4822. var y = (left.y > right.y) ? left.y : right.y;
  4823. return new Vector2(x, y);
  4824. };
  4825. /**
  4826. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  4827. * @param vector defines the vector to transform
  4828. * @param transformation defines the matrix to apply
  4829. * @returns a new Vector2
  4830. */
  4831. Vector2.Transform = function (vector, transformation) {
  4832. var r = Vector2.Zero();
  4833. Vector2.TransformToRef(vector, transformation, r);
  4834. return r;
  4835. };
  4836. /**
  4837. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  4838. * @param vector defines the vector to transform
  4839. * @param transformation defines the matrix to apply
  4840. * @param result defines the target vector
  4841. */
  4842. Vector2.TransformToRef = function (vector, transformation, result) {
  4843. var m = transformation.m;
  4844. var x = (vector.x * m[0]) + (vector.y * m[4]) + m[12];
  4845. var y = (vector.x * m[1]) + (vector.y * m[5]) + m[13];
  4846. result.x = x;
  4847. result.y = y;
  4848. };
  4849. /**
  4850. * Determines if a given vector is included in a triangle
  4851. * @param p defines the vector to test
  4852. * @param p0 defines 1st triangle point
  4853. * @param p1 defines 2nd triangle point
  4854. * @param p2 defines 3rd triangle point
  4855. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  4856. */
  4857. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  4858. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  4859. var sign = a < 0 ? -1 : 1;
  4860. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  4861. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  4862. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  4863. };
  4864. /**
  4865. * Gets the distance between the vectors "value1" and "value2"
  4866. * @param value1 defines first vector
  4867. * @param value2 defines second vector
  4868. * @returns the distance between vectors
  4869. */
  4870. Vector2.Distance = function (value1, value2) {
  4871. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  4872. };
  4873. /**
  4874. * Returns the squared distance between the vectors "value1" and "value2"
  4875. * @param value1 defines first vector
  4876. * @param value2 defines second vector
  4877. * @returns the squared distance between vectors
  4878. */
  4879. Vector2.DistanceSquared = function (value1, value2) {
  4880. var x = value1.x - value2.x;
  4881. var y = value1.y - value2.y;
  4882. return (x * x) + (y * y);
  4883. };
  4884. /**
  4885. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  4886. * @param value1 defines first vector
  4887. * @param value2 defines second vector
  4888. * @returns a new Vector2
  4889. */
  4890. Vector2.Center = function (value1, value2) {
  4891. var center = value1.add(value2);
  4892. center.scaleInPlace(0.5);
  4893. return center;
  4894. };
  4895. /**
  4896. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  4897. * @param p defines the middle point
  4898. * @param segA defines one point of the segment
  4899. * @param segB defines the other point of the segment
  4900. * @returns the shortest distance
  4901. */
  4902. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  4903. var l2 = Vector2.DistanceSquared(segA, segB);
  4904. if (l2 === 0.0) {
  4905. return Vector2.Distance(p, segA);
  4906. }
  4907. var v = segB.subtract(segA);
  4908. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  4909. var proj = segA.add(v.multiplyByFloats(t, t));
  4910. return Vector2.Distance(p, proj);
  4911. };
  4912. return Vector2;
  4913. }());
  4914. BABYLON.Vector2 = Vector2;
  4915. /**
  4916. * Classed used to store (x,y,z) vector representation
  4917. * A Vector3 is the main object used in 3D geometry
  4918. * It can represent etiher the coordinates of a point the space, either a direction
  4919. * Reminder: Babylon.js uses a left handed forward facing system
  4920. */
  4921. var Vector3 = /** @class */ (function () {
  4922. /**
  4923. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  4924. * @param x defines the first coordinates (on X axis)
  4925. * @param y defines the second coordinates (on Y axis)
  4926. * @param z defines the third coordinates (on Z axis)
  4927. */
  4928. function Vector3(
  4929. /**
  4930. * Defines the first coordinates (on X axis)
  4931. */
  4932. x,
  4933. /**
  4934. * Defines the second coordinates (on Y axis)
  4935. */
  4936. y,
  4937. /**
  4938. * Defines the third coordinates (on Z axis)
  4939. */
  4940. z) {
  4941. if (x === void 0) { x = 0; }
  4942. if (y === void 0) { y = 0; }
  4943. if (z === void 0) { z = 0; }
  4944. this.x = x;
  4945. this.y = y;
  4946. this.z = z;
  4947. }
  4948. /**
  4949. * Creates a string representation of the Vector3
  4950. * @returns a string with the Vector3 coordinates.
  4951. */
  4952. Vector3.prototype.toString = function () {
  4953. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  4954. };
  4955. /**
  4956. * Gets the class name
  4957. * @returns the string "Vector3"
  4958. */
  4959. Vector3.prototype.getClassName = function () {
  4960. return "Vector3";
  4961. };
  4962. /**
  4963. * Creates the Vector3 hash code
  4964. * @returns a number which tends to be unique between Vector3 instances
  4965. */
  4966. Vector3.prototype.getHashCode = function () {
  4967. var hash = this.x || 0;
  4968. hash = (hash * 397) ^ (this.y || 0);
  4969. hash = (hash * 397) ^ (this.z || 0);
  4970. return hash;
  4971. };
  4972. // Operators
  4973. /**
  4974. * Creates an array containing three elements : the coordinates of the Vector3
  4975. * @returns a new array of numbers
  4976. */
  4977. Vector3.prototype.asArray = function () {
  4978. var result = [];
  4979. this.toArray(result, 0);
  4980. return result;
  4981. };
  4982. /**
  4983. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  4984. * @param array defines the destination array
  4985. * @param index defines the offset in the destination array
  4986. * @returns the current Vector3
  4987. */
  4988. Vector3.prototype.toArray = function (array, index) {
  4989. if (index === void 0) { index = 0; }
  4990. array[index] = this.x;
  4991. array[index + 1] = this.y;
  4992. array[index + 2] = this.z;
  4993. return this;
  4994. };
  4995. /**
  4996. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  4997. * @returns a new Quaternion object, computed from the Vector3 coordinates
  4998. */
  4999. Vector3.prototype.toQuaternion = function () {
  5000. return BABYLON.Quaternion.RotationYawPitchRoll(this.y, this.x, this.z);
  5001. };
  5002. /**
  5003. * Adds the given vector to the current Vector3
  5004. * @param otherVector defines the second operand
  5005. * @returns the current updated Vector3
  5006. */
  5007. Vector3.prototype.addInPlace = function (otherVector) {
  5008. return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z);
  5009. };
  5010. /**
  5011. * Adds the given coordinates to the current Vector3
  5012. * @param x defines the x coordinate of the operand
  5013. * @param y defines the y coordinate of the operand
  5014. * @param z defines the z coordinate of the operand
  5015. * @returns the current updated Vector3
  5016. */
  5017. Vector3.prototype.addInPlaceFromFloats = function (x, y, z) {
  5018. this.x += x;
  5019. this.y += y;
  5020. this.z += z;
  5021. return this;
  5022. };
  5023. /**
  5024. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  5025. * @param otherVector defines the second operand
  5026. * @returns the resulting Vector3
  5027. */
  5028. Vector3.prototype.add = function (otherVector) {
  5029. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5030. };
  5031. /**
  5032. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  5033. * @param otherVector defines the second operand
  5034. * @param result defines the Vector3 object where to store the result
  5035. * @returns the current Vector3
  5036. */
  5037. Vector3.prototype.addToRef = function (otherVector, result) {
  5038. return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5039. };
  5040. /**
  5041. * Subtract the given vector from the current Vector3
  5042. * @param otherVector defines the second operand
  5043. * @returns the current updated Vector3
  5044. */
  5045. Vector3.prototype.subtractInPlace = function (otherVector) {
  5046. this.x -= otherVector.x;
  5047. this.y -= otherVector.y;
  5048. this.z -= otherVector.z;
  5049. return this;
  5050. };
  5051. /**
  5052. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  5053. * @param otherVector defines the second operand
  5054. * @returns the resulting Vector3
  5055. */
  5056. Vector3.prototype.subtract = function (otherVector) {
  5057. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  5058. };
  5059. /**
  5060. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  5061. * @param otherVector defines the second operand
  5062. * @param result defines the Vector3 object where to store the result
  5063. * @returns the current Vector3
  5064. */
  5065. Vector3.prototype.subtractToRef = function (otherVector, result) {
  5066. return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result);
  5067. };
  5068. /**
  5069. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  5070. * @param x defines the x coordinate of the operand
  5071. * @param y defines the y coordinate of the operand
  5072. * @param z defines the z coordinate of the operand
  5073. * @returns the resulting Vector3
  5074. */
  5075. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  5076. return new Vector3(this.x - x, this.y - y, this.z - z);
  5077. };
  5078. /**
  5079. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  5080. * @param x defines the x coordinate of the operand
  5081. * @param y defines the y coordinate of the operand
  5082. * @param z defines the z coordinate of the operand
  5083. * @param result defines the Vector3 object where to store the result
  5084. * @returns the current Vector3
  5085. */
  5086. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  5087. return result.copyFromFloats(this.x - x, this.y - y, this.z - z);
  5088. };
  5089. /**
  5090. * Gets a new Vector3 set with the current Vector3 negated coordinates
  5091. * @returns a new Vector3
  5092. */
  5093. Vector3.prototype.negate = function () {
  5094. return new Vector3(-this.x, -this.y, -this.z);
  5095. };
  5096. /**
  5097. * Multiplies the Vector3 coordinates by the float "scale"
  5098. * @param scale defines the multiplier factor
  5099. * @returns the current updated Vector3
  5100. */
  5101. Vector3.prototype.scaleInPlace = function (scale) {
  5102. this.x *= scale;
  5103. this.y *= scale;
  5104. this.z *= scale;
  5105. return this;
  5106. };
  5107. /**
  5108. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  5109. * @param scale defines the multiplier factor
  5110. * @returns a new Vector3
  5111. */
  5112. Vector3.prototype.scale = function (scale) {
  5113. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  5114. };
  5115. /**
  5116. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  5117. * @param scale defines the multiplier factor
  5118. * @param result defines the Vector3 object where to store the result
  5119. * @returns the current Vector3
  5120. */
  5121. Vector3.prototype.scaleToRef = function (scale, result) {
  5122. return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5123. };
  5124. /**
  5125. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  5126. * @param scale defines the scale factor
  5127. * @param result defines the Vector3 object where to store the result
  5128. * @returns the unmodified current Vector3
  5129. */
  5130. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  5131. return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5132. };
  5133. /**
  5134. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  5135. * @param otherVector defines the second operand
  5136. * @returns true if both vectors are equals
  5137. */
  5138. Vector3.prototype.equals = function (otherVector) {
  5139. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  5140. };
  5141. /**
  5142. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  5143. * @param otherVector defines the second operand
  5144. * @param epsilon defines the minimal distance to define values as equals
  5145. * @returns true if both vectors are distant less than epsilon
  5146. */
  5147. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  5148. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  5149. 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);
  5150. };
  5151. /**
  5152. * Returns true if the current Vector3 coordinates equals the given floats
  5153. * @param x defines the x coordinate of the operand
  5154. * @param y defines the y coordinate of the operand
  5155. * @param z defines the z coordinate of the operand
  5156. * @returns true if both vectors are equals
  5157. */
  5158. Vector3.prototype.equalsToFloats = function (x, y, z) {
  5159. return this.x === x && this.y === y && this.z === z;
  5160. };
  5161. /**
  5162. * Multiplies the current Vector3 coordinates by the given ones
  5163. * @param otherVector defines the second operand
  5164. * @returns the current updated Vector3
  5165. */
  5166. Vector3.prototype.multiplyInPlace = function (otherVector) {
  5167. this.x *= otherVector.x;
  5168. this.y *= otherVector.y;
  5169. this.z *= otherVector.z;
  5170. return this;
  5171. };
  5172. /**
  5173. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  5174. * @param otherVector defines the second operand
  5175. * @returns the new Vector3
  5176. */
  5177. Vector3.prototype.multiply = function (otherVector) {
  5178. return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z);
  5179. };
  5180. /**
  5181. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  5182. * @param otherVector defines the second operand
  5183. * @param result defines the Vector3 object where to store the result
  5184. * @returns the current Vector3
  5185. */
  5186. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  5187. return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  5188. };
  5189. /**
  5190. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  5191. * @param x defines the x coordinate of the operand
  5192. * @param y defines the y coordinate of the operand
  5193. * @param z defines the z coordinate of the operand
  5194. * @returns the new Vector3
  5195. */
  5196. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  5197. return new Vector3(this.x * x, this.y * y, this.z * z);
  5198. };
  5199. /**
  5200. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  5201. * @param otherVector defines the second operand
  5202. * @returns the new Vector3
  5203. */
  5204. Vector3.prototype.divide = function (otherVector) {
  5205. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5206. };
  5207. /**
  5208. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  5209. * @param otherVector defines the second operand
  5210. * @param result defines the Vector3 object where to store the result
  5211. * @returns the current Vector3
  5212. */
  5213. Vector3.prototype.divideToRef = function (otherVector, result) {
  5214. return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5215. };
  5216. /**
  5217. * Divides the current Vector3 coordinates by the given ones.
  5218. * @param otherVector defines the second operand
  5219. * @returns the current updated Vector3
  5220. */
  5221. Vector3.prototype.divideInPlace = function (otherVector) {
  5222. return this.divideToRef(otherVector, this);
  5223. };
  5224. /**
  5225. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  5226. * @param other defines the second operand
  5227. * @returns the current updated Vector3
  5228. */
  5229. Vector3.prototype.minimizeInPlace = function (other) {
  5230. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  5231. };
  5232. /**
  5233. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  5234. * @param other defines the second operand
  5235. * @returns the current updated Vector3
  5236. */
  5237. Vector3.prototype.maximizeInPlace = function (other) {
  5238. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  5239. };
  5240. /**
  5241. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  5242. * @param x defines the x coordinate of the operand
  5243. * @param y defines the y coordinate of the operand
  5244. * @param z defines the z coordinate of the operand
  5245. * @returns the current updated Vector3
  5246. */
  5247. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  5248. if (x < this.x) {
  5249. this.x = x;
  5250. }
  5251. if (y < this.y) {
  5252. this.y = y;
  5253. }
  5254. if (z < this.z) {
  5255. this.z = z;
  5256. }
  5257. return this;
  5258. };
  5259. /**
  5260. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  5261. * @param x defines the x coordinate of the operand
  5262. * @param y defines the y coordinate of the operand
  5263. * @param z defines the z coordinate of the operand
  5264. * @returns the current updated Vector3
  5265. */
  5266. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  5267. if (x > this.x) {
  5268. this.x = x;
  5269. }
  5270. if (y > this.y) {
  5271. this.y = y;
  5272. }
  5273. if (z > this.z) {
  5274. this.z = z;
  5275. }
  5276. return this;
  5277. };
  5278. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  5279. /**
  5280. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  5281. */
  5282. get: function () {
  5283. var absX = Math.abs(this.x);
  5284. var absY = Math.abs(this.y);
  5285. if (absX !== absY) {
  5286. return true;
  5287. }
  5288. var absZ = Math.abs(this.z);
  5289. if (absX !== absZ) {
  5290. return true;
  5291. }
  5292. if (absY !== absZ) {
  5293. return true;
  5294. }
  5295. return false;
  5296. },
  5297. enumerable: true,
  5298. configurable: true
  5299. });
  5300. /**
  5301. * Gets a new Vector3 from current Vector3 floored values
  5302. * @returns a new Vector3
  5303. */
  5304. Vector3.prototype.floor = function () {
  5305. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  5306. };
  5307. /**
  5308. * Gets a new Vector3 from current Vector3 floored values
  5309. * @returns a new Vector3
  5310. */
  5311. Vector3.prototype.fract = function () {
  5312. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  5313. };
  5314. // Properties
  5315. /**
  5316. * Gets the length of the Vector3
  5317. * @returns the length of the Vecto3
  5318. */
  5319. Vector3.prototype.length = function () {
  5320. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  5321. };
  5322. /**
  5323. * Gets the squared length of the Vector3
  5324. * @returns squared length of the Vector3
  5325. */
  5326. Vector3.prototype.lengthSquared = function () {
  5327. return (this.x * this.x + this.y * this.y + this.z * this.z);
  5328. };
  5329. /**
  5330. * Normalize the current Vector3.
  5331. * Please note that this is an in place operation.
  5332. * @returns the current updated Vector3
  5333. */
  5334. Vector3.prototype.normalize = function () {
  5335. return this.normalizeFromLength(this.length());
  5336. };
  5337. /**
  5338. * Normalize the current Vector3 with the given input length.
  5339. * Please note that this is an in place operation.
  5340. * @param len the length of the vector
  5341. * @returns the current updated Vector3
  5342. */
  5343. Vector3.prototype.normalizeFromLength = function (len) {
  5344. if (len === 0 || len === 1.0) {
  5345. return this;
  5346. }
  5347. return this.scaleInPlace(1.0 / len);
  5348. };
  5349. /**
  5350. * Normalize the current Vector3 to a new vector
  5351. * @returns the new Vector3
  5352. */
  5353. Vector3.prototype.normalizeToNew = function () {
  5354. var normalized = new Vector3(0, 0, 0);
  5355. this.normalizeToRef(normalized);
  5356. return normalized;
  5357. };
  5358. /**
  5359. * Normalize the current Vector3 to the reference
  5360. * @param reference define the Vector3 to update
  5361. * @returns the updated Vector3
  5362. */
  5363. Vector3.prototype.normalizeToRef = function (reference) {
  5364. var len = this.length();
  5365. if (len === 0 || len === 1.0) {
  5366. return reference.copyFromFloats(this.x, this.y, this.z);
  5367. }
  5368. return this.scaleToRef(1.0 / len, reference);
  5369. };
  5370. /**
  5371. * Creates a new Vector3 copied from the current Vector3
  5372. * @returns the new Vector3
  5373. */
  5374. Vector3.prototype.clone = function () {
  5375. return new Vector3(this.x, this.y, this.z);
  5376. };
  5377. /**
  5378. * Copies the given vector coordinates to the current Vector3 ones
  5379. * @param source defines the source Vector3
  5380. * @returns the current updated Vector3
  5381. */
  5382. Vector3.prototype.copyFrom = function (source) {
  5383. return this.copyFromFloats(source.x, source.y, source.z);
  5384. };
  5385. /**
  5386. * Copies the given floats to the current Vector3 coordinates
  5387. * @param x defines the x coordinate of the operand
  5388. * @param y defines the y coordinate of the operand
  5389. * @param z defines the z coordinate of the operand
  5390. * @returns the current updated Vector3
  5391. */
  5392. Vector3.prototype.copyFromFloats = function (x, y, z) {
  5393. this.x = x;
  5394. this.y = y;
  5395. this.z = z;
  5396. return this;
  5397. };
  5398. /**
  5399. * Copies the given floats to the current Vector3 coordinates
  5400. * @param x defines the x coordinate of the operand
  5401. * @param y defines the y coordinate of the operand
  5402. * @param z defines the z coordinate of the operand
  5403. * @returns the current updated Vector3
  5404. */
  5405. Vector3.prototype.set = function (x, y, z) {
  5406. return this.copyFromFloats(x, y, z);
  5407. };
  5408. /**
  5409. * Copies the given float to the current Vector3 coordinates
  5410. * @param v defines the x, y and z coordinates of the operand
  5411. * @returns the current updated Vector3
  5412. */
  5413. Vector3.prototype.setAll = function (v) {
  5414. this.x = this.y = this.z = v;
  5415. return this;
  5416. };
  5417. // Statics
  5418. /**
  5419. * Get the clip factor between two vectors
  5420. * @param vector0 defines the first operand
  5421. * @param vector1 defines the second operand
  5422. * @param axis defines the axis to use
  5423. * @param size defines the size along the axis
  5424. * @returns the clip factor
  5425. */
  5426. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  5427. var d0 = Vector3.Dot(vector0, axis) - size;
  5428. var d1 = Vector3.Dot(vector1, axis) - size;
  5429. var s = d0 / (d0 - d1);
  5430. return s;
  5431. };
  5432. /**
  5433. * Get angle between two vectors
  5434. * @param vector0 angle between vector0 and vector1
  5435. * @param vector1 angle between vector0 and vector1
  5436. * @param normal direction of the normal
  5437. * @return the angle between vector0 and vector1
  5438. */
  5439. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  5440. var v0 = vector0.normalizeToRef(MathTmp.Vector3[1]);
  5441. var v1 = vector1.normalizeToRef(MathTmp.Vector3[2]);
  5442. var dot = Vector3.Dot(v0, v1);
  5443. var n = MathTmp.Vector3[3];
  5444. Vector3.CrossToRef(v0, v1, n);
  5445. if (Vector3.Dot(n, normal) > 0) {
  5446. return Math.acos(dot);
  5447. }
  5448. return -Math.acos(dot);
  5449. };
  5450. /**
  5451. * Returns a new Vector3 set from the index "offset" of the given array
  5452. * @param array defines the source array
  5453. * @param offset defines the offset in the source array
  5454. * @returns the new Vector3
  5455. */
  5456. Vector3.FromArray = function (array, offset) {
  5457. if (!offset) {
  5458. offset = 0;
  5459. }
  5460. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  5461. };
  5462. /**
  5463. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  5464. * This function is deprecated. Use FromArray instead
  5465. * @param array defines the source array
  5466. * @param offset defines the offset in the source array
  5467. * @returns the new Vector3
  5468. */
  5469. Vector3.FromFloatArray = function (array, offset) {
  5470. return Vector3.FromArray(array, offset);
  5471. };
  5472. /**
  5473. * Sets the given vector "result" with the element values from the index "offset" of the given array
  5474. * @param array defines the source array
  5475. * @param offset defines the offset in the source array
  5476. * @param result defines the Vector3 where to store the result
  5477. */
  5478. Vector3.FromArrayToRef = function (array, offset, result) {
  5479. result.x = array[offset];
  5480. result.y = array[offset + 1];
  5481. result.z = array[offset + 2];
  5482. };
  5483. /**
  5484. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  5485. * This function is deprecated. Use FromArrayToRef instead.
  5486. * @param array defines the source array
  5487. * @param offset defines the offset in the source array
  5488. * @param result defines the Vector3 where to store the result
  5489. */
  5490. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  5491. return Vector3.FromArrayToRef(array, offset, result);
  5492. };
  5493. /**
  5494. * Sets the given vector "result" with the given floats.
  5495. * @param x defines the x coordinate of the source
  5496. * @param y defines the y coordinate of the source
  5497. * @param z defines the z coordinate of the source
  5498. * @param result defines the Vector3 where to store the result
  5499. */
  5500. Vector3.FromFloatsToRef = function (x, y, z, result) {
  5501. result.copyFromFloats(x, y, z);
  5502. };
  5503. /**
  5504. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  5505. * @returns a new empty Vector3
  5506. */
  5507. Vector3.Zero = function () {
  5508. return new Vector3(0.0, 0.0, 0.0);
  5509. };
  5510. /**
  5511. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  5512. * @returns a new unit Vector3
  5513. */
  5514. Vector3.One = function () {
  5515. return new Vector3(1.0, 1.0, 1.0);
  5516. };
  5517. /**
  5518. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  5519. * @returns a new up Vector3
  5520. */
  5521. Vector3.Up = function () {
  5522. return new Vector3(0.0, 1.0, 0.0);
  5523. };
  5524. /**
  5525. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  5526. * @returns a new down Vector3
  5527. */
  5528. Vector3.Down = function () {
  5529. return new Vector3(0.0, -1.0, 0.0);
  5530. };
  5531. /**
  5532. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  5533. * @returns a new forward Vector3
  5534. */
  5535. Vector3.Forward = function () {
  5536. return new Vector3(0.0, 0.0, 1.0);
  5537. };
  5538. /**
  5539. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  5540. * @returns a new forward Vector3
  5541. */
  5542. Vector3.Backward = function () {
  5543. return new Vector3(0.0, 0.0, -1.0);
  5544. };
  5545. /**
  5546. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  5547. * @returns a new right Vector3
  5548. */
  5549. Vector3.Right = function () {
  5550. return new Vector3(1.0, 0.0, 0.0);
  5551. };
  5552. /**
  5553. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  5554. * @returns a new left Vector3
  5555. */
  5556. Vector3.Left = function () {
  5557. return new Vector3(-1.0, 0.0, 0.0);
  5558. };
  5559. /**
  5560. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  5561. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5562. * @param vector defines the Vector3 to transform
  5563. * @param transformation defines the transformation matrix
  5564. * @returns the transformed Vector3
  5565. */
  5566. Vector3.TransformCoordinates = function (vector, transformation) {
  5567. var result = Vector3.Zero();
  5568. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  5569. return result;
  5570. };
  5571. /**
  5572. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  5573. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5574. * @param vector defines the Vector3 to transform
  5575. * @param transformation defines the transformation matrix
  5576. * @param result defines the Vector3 where to store the result
  5577. */
  5578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  5579. return Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5580. };
  5581. /**
  5582. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  5583. * This method computes tranformed coordinates only, not transformed direction vectors
  5584. * @param x define the x coordinate of the source vector
  5585. * @param y define the y coordinate of the source vector
  5586. * @param z define the z coordinate of the source vector
  5587. * @param transformation defines the transformation matrix
  5588. * @param result defines the Vector3 where to store the result
  5589. */
  5590. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  5591. var m = transformation.m;
  5592. var rx = x * m[0] + y * m[4] + z * m[8] + m[12];
  5593. var ry = x * m[1] + y * m[5] + z * m[9] + m[13];
  5594. var rz = x * m[2] + y * m[6] + z * m[10] + m[14];
  5595. var rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
  5596. result.x = rx * rw;
  5597. result.y = ry * rw;
  5598. result.z = rz * rw;
  5599. };
  5600. /**
  5601. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  5602. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5603. * @param vector defines the Vector3 to transform
  5604. * @param transformation defines the transformation matrix
  5605. * @returns the new Vector3
  5606. */
  5607. Vector3.TransformNormal = function (vector, transformation) {
  5608. var result = Vector3.Zero();
  5609. Vector3.TransformNormalToRef(vector, transformation, result);
  5610. return result;
  5611. };
  5612. /**
  5613. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  5614. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5615. * @param vector defines the Vector3 to transform
  5616. * @param transformation defines the transformation matrix
  5617. * @param result defines the Vector3 where to store the result
  5618. */
  5619. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  5620. this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5621. };
  5622. /**
  5623. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  5624. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5625. * @param x define the x coordinate of the source vector
  5626. * @param y define the y coordinate of the source vector
  5627. * @param z define the z coordinate of the source vector
  5628. * @param transformation defines the transformation matrix
  5629. * @param result defines the Vector3 where to store the result
  5630. */
  5631. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  5632. var m = transformation.m;
  5633. result.x = x * m[0] + y * m[4] + z * m[8];
  5634. result.y = x * m[1] + y * m[5] + z * m[9];
  5635. result.z = x * m[2] + y * m[6] + z * m[10];
  5636. };
  5637. /**
  5638. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  5639. * @param value1 defines the first control point
  5640. * @param value2 defines the second control point
  5641. * @param value3 defines the third control point
  5642. * @param value4 defines the fourth control point
  5643. * @param amount defines the amount on the spline to use
  5644. * @returns the new Vector3
  5645. */
  5646. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  5647. var squared = amount * amount;
  5648. var cubed = amount * squared;
  5649. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  5650. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  5651. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  5652. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  5653. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  5654. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  5655. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  5656. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  5657. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  5658. return new Vector3(x, y, z);
  5659. };
  5660. /**
  5661. * 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"
  5662. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5663. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5664. * @param value defines the current value
  5665. * @param min defines the lower range value
  5666. * @param max defines the upper range value
  5667. * @returns the new Vector3
  5668. */
  5669. Vector3.Clamp = function (value, min, max) {
  5670. var x = value.x;
  5671. x = (x > max.x) ? max.x : x;
  5672. x = (x < min.x) ? min.x : x;
  5673. var y = value.y;
  5674. y = (y > max.y) ? max.y : y;
  5675. y = (y < min.y) ? min.y : y;
  5676. var z = value.z;
  5677. z = (z > max.z) ? max.z : z;
  5678. z = (z < min.z) ? min.z : z;
  5679. return new Vector3(x, y, z);
  5680. };
  5681. /**
  5682. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  5683. * @param value1 defines the first control point
  5684. * @param tangent1 defines the first tangent vector
  5685. * @param value2 defines the second control point
  5686. * @param tangent2 defines the second tangent vector
  5687. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  5688. * @returns the new Vector3
  5689. */
  5690. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5691. var squared = amount * amount;
  5692. var cubed = amount * squared;
  5693. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5694. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5695. var part3 = (cubed - (2.0 * squared)) + amount;
  5696. var part4 = cubed - squared;
  5697. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5698. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5699. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5700. return new Vector3(x, y, z);
  5701. };
  5702. /**
  5703. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  5704. * @param start defines the start value
  5705. * @param end defines the end value
  5706. * @param amount max defines amount between both (between 0 and 1)
  5707. * @returns the new Vector3
  5708. */
  5709. Vector3.Lerp = function (start, end, amount) {
  5710. var result = new Vector3(0, 0, 0);
  5711. Vector3.LerpToRef(start, end, amount, result);
  5712. return result;
  5713. };
  5714. /**
  5715. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  5716. * @param start defines the start value
  5717. * @param end defines the end value
  5718. * @param amount max defines amount between both (between 0 and 1)
  5719. * @param result defines the Vector3 where to store the result
  5720. */
  5721. Vector3.LerpToRef = function (start, end, amount, result) {
  5722. result.x = start.x + ((end.x - start.x) * amount);
  5723. result.y = start.y + ((end.y - start.y) * amount);
  5724. result.z = start.z + ((end.z - start.z) * amount);
  5725. };
  5726. /**
  5727. * Returns the dot product (float) between the vectors "left" and "right"
  5728. * @param left defines the left operand
  5729. * @param right defines the right operand
  5730. * @returns the dot product
  5731. */
  5732. Vector3.Dot = function (left, right) {
  5733. return (left.x * right.x + left.y * right.y + left.z * right.z);
  5734. };
  5735. /**
  5736. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  5737. * The cross product is then orthogonal to both "left" and "right"
  5738. * @param left defines the left operand
  5739. * @param right defines the right operand
  5740. * @returns the cross product
  5741. */
  5742. Vector3.Cross = function (left, right) {
  5743. var result = Vector3.Zero();
  5744. Vector3.CrossToRef(left, right, result);
  5745. return result;
  5746. };
  5747. /**
  5748. * Sets the given vector "result" with the cross product of "left" and "right"
  5749. * The cross product is then orthogonal to both "left" and "right"
  5750. * @param left defines the left operand
  5751. * @param right defines the right operand
  5752. * @param result defines the Vector3 where to store the result
  5753. */
  5754. Vector3.CrossToRef = function (left, right, result) {
  5755. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  5756. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  5757. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  5758. result.copyFrom(MathTmp.Vector3[0]);
  5759. };
  5760. /**
  5761. * Returns a new Vector3 as the normalization of the given vector
  5762. * @param vector defines the Vector3 to normalize
  5763. * @returns the new Vector3
  5764. */
  5765. Vector3.Normalize = function (vector) {
  5766. var result = Vector3.Zero();
  5767. Vector3.NormalizeToRef(vector, result);
  5768. return result;
  5769. };
  5770. /**
  5771. * Sets the given vector "result" with the normalization of the given first vector
  5772. * @param vector defines the Vector3 to normalize
  5773. * @param result defines the Vector3 where to store the result
  5774. */
  5775. Vector3.NormalizeToRef = function (vector, result) {
  5776. vector.normalizeToRef(result);
  5777. };
  5778. /**
  5779. * Project a Vector3 onto screen space
  5780. * @param vector defines the Vector3 to project
  5781. * @param world defines the world matrix to use
  5782. * @param transform defines the transform (view x projection) matrix to use
  5783. * @param viewport defines the screen viewport to use
  5784. * @returns the new Vector3
  5785. */
  5786. Vector3.Project = function (vector, world, transform, viewport) {
  5787. var cw = viewport.width;
  5788. var ch = viewport.height;
  5789. var cx = viewport.x;
  5790. var cy = viewport.y;
  5791. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  5792. 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);
  5793. var matrix = MathTmp.Matrix[0];
  5794. world.multiplyToRef(transform, matrix);
  5795. matrix.multiplyToRef(viewportMatrix, matrix);
  5796. return Vector3.TransformCoordinates(vector, matrix);
  5797. };
  5798. /**
  5799. * Unproject from screen space to object space
  5800. * @param source defines the screen space Vector3 to use
  5801. * @param viewportWidth defines the current width of the viewport
  5802. * @param viewportHeight defines the current height of the viewport
  5803. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5804. * @param transform defines the transform (view x projection) matrix to use
  5805. * @returns the new Vector3
  5806. */
  5807. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  5808. var matrix = MathTmp.Matrix[0];
  5809. world.multiplyToRef(transform, matrix);
  5810. matrix.invert();
  5811. source.x = source.x / viewportWidth * 2 - 1;
  5812. source.y = -(source.y / viewportHeight * 2 - 1);
  5813. var vector = Vector3.TransformCoordinates(source, matrix);
  5814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  5815. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5816. vector = vector.scale(1.0 / num);
  5817. }
  5818. return vector;
  5819. };
  5820. /**
  5821. * Unproject from screen space to object space
  5822. * @param source defines the screen space Vector3 to use
  5823. * @param viewportWidth defines the current width of the viewport
  5824. * @param viewportHeight defines the current height of the viewport
  5825. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5826. * @param view defines the view matrix to use
  5827. * @param projection defines the projection matrix to use
  5828. * @returns the new Vector3
  5829. */
  5830. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  5831. var result = Vector3.Zero();
  5832. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  5833. return result;
  5834. };
  5835. /**
  5836. * Unproject from screen space to object space
  5837. * @param source defines the screen space Vector3 to use
  5838. * @param viewportWidth defines the current width of the viewport
  5839. * @param viewportHeight defines the current height of the viewport
  5840. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5841. * @param view defines the view matrix to use
  5842. * @param projection defines the projection matrix to use
  5843. * @param result defines the Vector3 where to store the result
  5844. */
  5845. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  5846. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  5847. };
  5848. /**
  5849. * Unproject from screen space to object space
  5850. * @param sourceX defines the screen space x coordinate to use
  5851. * @param sourceY defines the screen space y coordinate to use
  5852. * @param sourceZ defines the screen space z coordinate to use
  5853. * @param viewportWidth defines the current width of the viewport
  5854. * @param viewportHeight defines the current height of the viewport
  5855. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5856. * @param view defines the view matrix to use
  5857. * @param projection defines the projection matrix to use
  5858. * @param result defines the Vector3 where to store the result
  5859. */
  5860. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  5861. var matrix = MathTmp.Matrix[0];
  5862. world.multiplyToRef(view, matrix);
  5863. matrix.multiplyToRef(projection, matrix);
  5864. matrix.invert();
  5865. var screenSource = MathTmp.Vector3[0];
  5866. screenSource.x = sourceX / viewportWidth * 2 - 1;
  5867. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5868. screenSource.z = 2 * sourceZ - 1.0;
  5869. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  5870. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  5871. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5872. result.scaleInPlace(1.0 / num);
  5873. }
  5874. };
  5875. /**
  5876. * Gets the minimal coordinate values between two Vector3
  5877. * @param left defines the first operand
  5878. * @param right defines the second operand
  5879. * @returns the new Vector3
  5880. */
  5881. Vector3.Minimize = function (left, right) {
  5882. var min = left.clone();
  5883. min.minimizeInPlace(right);
  5884. return min;
  5885. };
  5886. /**
  5887. * Gets the maximal coordinate values between two Vector3
  5888. * @param left defines the first operand
  5889. * @param right defines the second operand
  5890. * @returns the new Vector3
  5891. */
  5892. Vector3.Maximize = function (left, right) {
  5893. var max = left.clone();
  5894. max.maximizeInPlace(right);
  5895. return max;
  5896. };
  5897. /**
  5898. * Returns the distance between the vectors "value1" and "value2"
  5899. * @param value1 defines the first operand
  5900. * @param value2 defines the second operand
  5901. * @returns the distance
  5902. */
  5903. Vector3.Distance = function (value1, value2) {
  5904. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  5905. };
  5906. /**
  5907. * Returns the squared distance between the vectors "value1" and "value2"
  5908. * @param value1 defines the first operand
  5909. * @param value2 defines the second operand
  5910. * @returns the squared distance
  5911. */
  5912. Vector3.DistanceSquared = function (value1, value2) {
  5913. var x = value1.x - value2.x;
  5914. var y = value1.y - value2.y;
  5915. var z = value1.z - value2.z;
  5916. return (x * x) + (y * y) + (z * z);
  5917. };
  5918. /**
  5919. * Returns a new Vector3 located at the center between "value1" and "value2"
  5920. * @param value1 defines the first operand
  5921. * @param value2 defines the second operand
  5922. * @returns the new Vector3
  5923. */
  5924. Vector3.Center = function (value1, value2) {
  5925. var center = value1.add(value2);
  5926. center.scaleInPlace(0.5);
  5927. return center;
  5928. };
  5929. /**
  5930. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  5931. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  5932. * to something in order to rotate it from its local system to the given target system
  5933. * Note: axis1, axis2 and axis3 are normalized during this operation
  5934. * @param axis1 defines the first axis
  5935. * @param axis2 defines the second axis
  5936. * @param axis3 defines the third axis
  5937. * @returns a new Vector3
  5938. */
  5939. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  5940. var rotation = Vector3.Zero();
  5941. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  5942. return rotation;
  5943. };
  5944. /**
  5945. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  5946. * @param axis1 defines the first axis
  5947. * @param axis2 defines the second axis
  5948. * @param axis3 defines the third axis
  5949. * @param ref defines the Vector3 where to store the result
  5950. */
  5951. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5952. var quat = MathTmp.Quaternion[0];
  5953. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5954. quat.toEulerAnglesToRef(ref);
  5955. };
  5956. return Vector3;
  5957. }());
  5958. BABYLON.Vector3 = Vector3;
  5959. /**
  5960. * Vector4 class created for EulerAngle class conversion to Quaternion
  5961. */
  5962. var Vector4 = /** @class */ (function () {
  5963. /**
  5964. * Creates a Vector4 object from the given floats.
  5965. * @param x x value of the vector
  5966. * @param y y value of the vector
  5967. * @param z z value of the vector
  5968. * @param w w value of the vector
  5969. */
  5970. function Vector4(
  5971. /** x value of the vector */
  5972. x,
  5973. /** y value of the vector */
  5974. y,
  5975. /** z value of the vector */
  5976. z,
  5977. /** w value of the vector */
  5978. w) {
  5979. this.x = x;
  5980. this.y = y;
  5981. this.z = z;
  5982. this.w = w;
  5983. }
  5984. /**
  5985. * Returns the string with the Vector4 coordinates.
  5986. * @returns a string containing all the vector values
  5987. */
  5988. Vector4.prototype.toString = function () {
  5989. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  5990. };
  5991. /**
  5992. * Returns the string "Vector4".
  5993. * @returns "Vector4"
  5994. */
  5995. Vector4.prototype.getClassName = function () {
  5996. return "Vector4";
  5997. };
  5998. /**
  5999. * Returns the Vector4 hash code.
  6000. * @returns a unique hash code
  6001. */
  6002. Vector4.prototype.getHashCode = function () {
  6003. var hash = this.x || 0;
  6004. hash = (hash * 397) ^ (this.y || 0);
  6005. hash = (hash * 397) ^ (this.z || 0);
  6006. hash = (hash * 397) ^ (this.w || 0);
  6007. return hash;
  6008. };
  6009. // Operators
  6010. /**
  6011. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  6012. * @returns the resulting array
  6013. */
  6014. Vector4.prototype.asArray = function () {
  6015. var result = new Array();
  6016. this.toArray(result, 0);
  6017. return result;
  6018. };
  6019. /**
  6020. * Populates the given array from the given index with the Vector4 coordinates.
  6021. * @param array array to populate
  6022. * @param index index of the array to start at (default: 0)
  6023. * @returns the Vector4.
  6024. */
  6025. Vector4.prototype.toArray = function (array, index) {
  6026. if (index === undefined) {
  6027. index = 0;
  6028. }
  6029. array[index] = this.x;
  6030. array[index + 1] = this.y;
  6031. array[index + 2] = this.z;
  6032. array[index + 3] = this.w;
  6033. return this;
  6034. };
  6035. /**
  6036. * Adds the given vector to the current Vector4.
  6037. * @param otherVector the vector to add
  6038. * @returns the updated Vector4.
  6039. */
  6040. Vector4.prototype.addInPlace = function (otherVector) {
  6041. this.x += otherVector.x;
  6042. this.y += otherVector.y;
  6043. this.z += otherVector.z;
  6044. this.w += otherVector.w;
  6045. return this;
  6046. };
  6047. /**
  6048. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  6049. * @param otherVector the vector to add
  6050. * @returns the resulting vector
  6051. */
  6052. Vector4.prototype.add = function (otherVector) {
  6053. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  6054. };
  6055. /**
  6056. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  6057. * @param otherVector the vector to add
  6058. * @param result the vector to store the result
  6059. * @returns the current Vector4.
  6060. */
  6061. Vector4.prototype.addToRef = function (otherVector, result) {
  6062. result.x = this.x + otherVector.x;
  6063. result.y = this.y + otherVector.y;
  6064. result.z = this.z + otherVector.z;
  6065. result.w = this.w + otherVector.w;
  6066. return this;
  6067. };
  6068. /**
  6069. * Subtract in place the given vector from the current Vector4.
  6070. * @param otherVector the vector to subtract
  6071. * @returns the updated Vector4.
  6072. */
  6073. Vector4.prototype.subtractInPlace = function (otherVector) {
  6074. this.x -= otherVector.x;
  6075. this.y -= otherVector.y;
  6076. this.z -= otherVector.z;
  6077. this.w -= otherVector.w;
  6078. return this;
  6079. };
  6080. /**
  6081. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  6082. * @param otherVector the vector to add
  6083. * @returns the new vector with the result
  6084. */
  6085. Vector4.prototype.subtract = function (otherVector) {
  6086. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  6087. };
  6088. /**
  6089. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  6090. * @param otherVector the vector to subtract
  6091. * @param result the vector to store the result
  6092. * @returns the current Vector4.
  6093. */
  6094. Vector4.prototype.subtractToRef = function (otherVector, result) {
  6095. result.x = this.x - otherVector.x;
  6096. result.y = this.y - otherVector.y;
  6097. result.z = this.z - otherVector.z;
  6098. result.w = this.w - otherVector.w;
  6099. return this;
  6100. };
  6101. /**
  6102. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6103. */
  6104. /**
  6105. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6106. * @param x value to subtract
  6107. * @param y value to subtract
  6108. * @param z value to subtract
  6109. * @param w value to subtract
  6110. * @returns new vector containing the result
  6111. */
  6112. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  6113. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  6114. };
  6115. /**
  6116. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6117. * @param x value to subtract
  6118. * @param y value to subtract
  6119. * @param z value to subtract
  6120. * @param w value to subtract
  6121. * @param result the vector to store the result in
  6122. * @returns the current Vector4.
  6123. */
  6124. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  6125. result.x = this.x - x;
  6126. result.y = this.y - y;
  6127. result.z = this.z - z;
  6128. result.w = this.w - w;
  6129. return this;
  6130. };
  6131. /**
  6132. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  6133. * @returns a new vector with the negated values
  6134. */
  6135. Vector4.prototype.negate = function () {
  6136. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  6137. };
  6138. /**
  6139. * Multiplies the current Vector4 coordinates by scale (float).
  6140. * @param scale the number to scale with
  6141. * @returns the updated Vector4.
  6142. */
  6143. Vector4.prototype.scaleInPlace = function (scale) {
  6144. this.x *= scale;
  6145. this.y *= scale;
  6146. this.z *= scale;
  6147. this.w *= scale;
  6148. return this;
  6149. };
  6150. /**
  6151. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  6152. * @param scale the number to scale with
  6153. * @returns a new vector with the result
  6154. */
  6155. Vector4.prototype.scale = function (scale) {
  6156. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  6157. };
  6158. /**
  6159. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  6160. * @param scale the number to scale with
  6161. * @param result a vector to store the result in
  6162. * @returns the current Vector4.
  6163. */
  6164. Vector4.prototype.scaleToRef = function (scale, result) {
  6165. result.x = this.x * scale;
  6166. result.y = this.y * scale;
  6167. result.z = this.z * scale;
  6168. result.w = this.w * scale;
  6169. return this;
  6170. };
  6171. /**
  6172. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  6173. * @param scale defines the scale factor
  6174. * @param result defines the Vector4 object where to store the result
  6175. * @returns the unmodified current Vector4
  6176. */
  6177. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  6178. result.x += this.x * scale;
  6179. result.y += this.y * scale;
  6180. result.z += this.z * scale;
  6181. result.w += this.w * scale;
  6182. return this;
  6183. };
  6184. /**
  6185. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  6186. * @param otherVector the vector to compare against
  6187. * @returns true if they are equal
  6188. */
  6189. Vector4.prototype.equals = function (otherVector) {
  6190. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  6191. };
  6192. /**
  6193. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  6194. * @param otherVector vector to compare against
  6195. * @param epsilon (Default: very small number)
  6196. * @returns true if they are equal
  6197. */
  6198. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  6199. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  6200. return otherVector
  6201. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  6202. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  6203. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  6204. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  6205. };
  6206. /**
  6207. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  6208. * @param x x value to compare against
  6209. * @param y y value to compare against
  6210. * @param z z value to compare against
  6211. * @param w w value to compare against
  6212. * @returns true if equal
  6213. */
  6214. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  6215. return this.x === x && this.y === y && this.z === z && this.w === w;
  6216. };
  6217. /**
  6218. * Multiplies in place the current Vector4 by the given one.
  6219. * @param otherVector vector to multiple with
  6220. * @returns the updated Vector4.
  6221. */
  6222. Vector4.prototype.multiplyInPlace = function (otherVector) {
  6223. this.x *= otherVector.x;
  6224. this.y *= otherVector.y;
  6225. this.z *= otherVector.z;
  6226. this.w *= otherVector.w;
  6227. return this;
  6228. };
  6229. /**
  6230. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  6231. * @param otherVector vector to multiple with
  6232. * @returns resulting new vector
  6233. */
  6234. Vector4.prototype.multiply = function (otherVector) {
  6235. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  6236. };
  6237. /**
  6238. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  6239. * @param otherVector vector to multiple with
  6240. * @param result vector to store the result
  6241. * @returns the current Vector4.
  6242. */
  6243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  6244. result.x = this.x * otherVector.x;
  6245. result.y = this.y * otherVector.y;
  6246. result.z = this.z * otherVector.z;
  6247. result.w = this.w * otherVector.w;
  6248. return this;
  6249. };
  6250. /**
  6251. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  6252. * @param x x value multiply with
  6253. * @param y y value multiply with
  6254. * @param z z value multiply with
  6255. * @param w w value multiply with
  6256. * @returns resulting new vector
  6257. */
  6258. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  6259. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  6260. };
  6261. /**
  6262. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  6263. * @param otherVector vector to devide with
  6264. * @returns resulting new vector
  6265. */
  6266. Vector4.prototype.divide = function (otherVector) {
  6267. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  6268. };
  6269. /**
  6270. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  6271. * @param otherVector vector to devide with
  6272. * @param result vector to store the result
  6273. * @returns the current Vector4.
  6274. */
  6275. Vector4.prototype.divideToRef = function (otherVector, result) {
  6276. result.x = this.x / otherVector.x;
  6277. result.y = this.y / otherVector.y;
  6278. result.z = this.z / otherVector.z;
  6279. result.w = this.w / otherVector.w;
  6280. return this;
  6281. };
  6282. /**
  6283. * Divides the current Vector3 coordinates by the given ones.
  6284. * @param otherVector vector to devide with
  6285. * @returns the updated Vector3.
  6286. */
  6287. Vector4.prototype.divideInPlace = function (otherVector) {
  6288. return this.divideToRef(otherVector, this);
  6289. };
  6290. /**
  6291. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  6292. * @param other defines the second operand
  6293. * @returns the current updated Vector4
  6294. */
  6295. Vector4.prototype.minimizeInPlace = function (other) {
  6296. if (other.x < this.x) {
  6297. this.x = other.x;
  6298. }
  6299. if (other.y < this.y) {
  6300. this.y = other.y;
  6301. }
  6302. if (other.z < this.z) {
  6303. this.z = other.z;
  6304. }
  6305. if (other.w < this.w) {
  6306. this.w = other.w;
  6307. }
  6308. return this;
  6309. };
  6310. /**
  6311. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  6312. * @param other defines the second operand
  6313. * @returns the current updated Vector4
  6314. */
  6315. Vector4.prototype.maximizeInPlace = function (other) {
  6316. if (other.x > this.x) {
  6317. this.x = other.x;
  6318. }
  6319. if (other.y > this.y) {
  6320. this.y = other.y;
  6321. }
  6322. if (other.z > this.z) {
  6323. this.z = other.z;
  6324. }
  6325. if (other.w > this.w) {
  6326. this.w = other.w;
  6327. }
  6328. return this;
  6329. };
  6330. /**
  6331. * Gets a new Vector4 from current Vector4 floored values
  6332. * @returns a new Vector4
  6333. */
  6334. Vector4.prototype.floor = function () {
  6335. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  6336. };
  6337. /**
  6338. * Gets a new Vector4 from current Vector3 floored values
  6339. * @returns a new Vector4
  6340. */
  6341. Vector4.prototype.fract = function () {
  6342. 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));
  6343. };
  6344. // Properties
  6345. /**
  6346. * Returns the Vector4 length (float).
  6347. * @returns the length
  6348. */
  6349. Vector4.prototype.length = function () {
  6350. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6351. };
  6352. /**
  6353. * Returns the Vector4 squared length (float).
  6354. * @returns the length squared
  6355. */
  6356. Vector4.prototype.lengthSquared = function () {
  6357. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6358. };
  6359. // Methods
  6360. /**
  6361. * Normalizes in place the Vector4.
  6362. * @returns the updated Vector4.
  6363. */
  6364. Vector4.prototype.normalize = function () {
  6365. var len = this.length();
  6366. if (len === 0) {
  6367. return this;
  6368. }
  6369. return this.scaleInPlace(1.0 / len);
  6370. };
  6371. /**
  6372. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  6373. * @returns this converted to a new vector3
  6374. */
  6375. Vector4.prototype.toVector3 = function () {
  6376. return new Vector3(this.x, this.y, this.z);
  6377. };
  6378. /**
  6379. * Returns a new Vector4 copied from the current one.
  6380. * @returns the new cloned vector
  6381. */
  6382. Vector4.prototype.clone = function () {
  6383. return new Vector4(this.x, this.y, this.z, this.w);
  6384. };
  6385. /**
  6386. * Updates the current Vector4 with the given one coordinates.
  6387. * @param source the source vector to copy from
  6388. * @returns the updated Vector4.
  6389. */
  6390. Vector4.prototype.copyFrom = function (source) {
  6391. this.x = source.x;
  6392. this.y = source.y;
  6393. this.z = source.z;
  6394. this.w = source.w;
  6395. return this;
  6396. };
  6397. /**
  6398. * Updates the current Vector4 coordinates with the given floats.
  6399. * @param x float to copy from
  6400. * @param y float to copy from
  6401. * @param z float to copy from
  6402. * @param w float to copy from
  6403. * @returns the updated Vector4.
  6404. */
  6405. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  6406. this.x = x;
  6407. this.y = y;
  6408. this.z = z;
  6409. this.w = w;
  6410. return this;
  6411. };
  6412. /**
  6413. * Updates the current Vector4 coordinates with the given floats.
  6414. * @param x float to set from
  6415. * @param y float to set from
  6416. * @param z float to set from
  6417. * @param w float to set from
  6418. * @returns the updated Vector4.
  6419. */
  6420. Vector4.prototype.set = function (x, y, z, w) {
  6421. return this.copyFromFloats(x, y, z, w);
  6422. };
  6423. /**
  6424. * Copies the given float to the current Vector3 coordinates
  6425. * @param v defines the x, y, z and w coordinates of the operand
  6426. * @returns the current updated Vector3
  6427. */
  6428. Vector4.prototype.setAll = function (v) {
  6429. this.x = this.y = this.z = this.w = v;
  6430. return this;
  6431. };
  6432. // Statics
  6433. /**
  6434. * Returns a new Vector4 set from the starting index of the given array.
  6435. * @param array the array to pull values from
  6436. * @param offset the offset into the array to start at
  6437. * @returns the new vector
  6438. */
  6439. Vector4.FromArray = function (array, offset) {
  6440. if (!offset) {
  6441. offset = 0;
  6442. }
  6443. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  6444. };
  6445. /**
  6446. * Updates the given vector "result" from the starting index of the given array.
  6447. * @param array the array to pull values from
  6448. * @param offset the offset into the array to start at
  6449. * @param result the vector to store the result in
  6450. */
  6451. Vector4.FromArrayToRef = function (array, offset, result) {
  6452. result.x = array[offset];
  6453. result.y = array[offset + 1];
  6454. result.z = array[offset + 2];
  6455. result.w = array[offset + 3];
  6456. };
  6457. /**
  6458. * Updates the given vector "result" from the starting index of the given Float32Array.
  6459. * @param array the array to pull values from
  6460. * @param offset the offset into the array to start at
  6461. * @param result the vector to store the result in
  6462. */
  6463. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  6464. Vector4.FromArrayToRef(array, offset, result);
  6465. };
  6466. /**
  6467. * Updates the given vector "result" coordinates from the given floats.
  6468. * @param x float to set from
  6469. * @param y float to set from
  6470. * @param z float to set from
  6471. * @param w float to set from
  6472. * @param result the vector to the floats in
  6473. */
  6474. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  6475. result.x = x;
  6476. result.y = y;
  6477. result.z = z;
  6478. result.w = w;
  6479. };
  6480. /**
  6481. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  6482. * @returns the new vector
  6483. */
  6484. Vector4.Zero = function () {
  6485. return new Vector4(0.0, 0.0, 0.0, 0.0);
  6486. };
  6487. /**
  6488. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  6489. * @returns the new vector
  6490. */
  6491. Vector4.One = function () {
  6492. return new Vector4(1.0, 1.0, 1.0, 1.0);
  6493. };
  6494. /**
  6495. * Returns a new normalized Vector4 from the given one.
  6496. * @param vector the vector to normalize
  6497. * @returns the vector
  6498. */
  6499. Vector4.Normalize = function (vector) {
  6500. var result = Vector4.Zero();
  6501. Vector4.NormalizeToRef(vector, result);
  6502. return result;
  6503. };
  6504. /**
  6505. * Updates the given vector "result" from the normalization of the given one.
  6506. * @param vector the vector to normalize
  6507. * @param result the vector to store the result in
  6508. */
  6509. Vector4.NormalizeToRef = function (vector, result) {
  6510. result.copyFrom(vector);
  6511. result.normalize();
  6512. };
  6513. /**
  6514. * Returns a vector with the minimum values from the left and right vectors
  6515. * @param left left vector to minimize
  6516. * @param right right vector to minimize
  6517. * @returns a new vector with the minimum of the left and right vector values
  6518. */
  6519. Vector4.Minimize = function (left, right) {
  6520. var min = left.clone();
  6521. min.minimizeInPlace(right);
  6522. return min;
  6523. };
  6524. /**
  6525. * Returns a vector with the maximum values from the left and right vectors
  6526. * @param left left vector to maximize
  6527. * @param right right vector to maximize
  6528. * @returns a new vector with the maximum of the left and right vector values
  6529. */
  6530. Vector4.Maximize = function (left, right) {
  6531. var max = left.clone();
  6532. max.maximizeInPlace(right);
  6533. return max;
  6534. };
  6535. /**
  6536. * Returns the distance (float) between the vectors "value1" and "value2".
  6537. * @param value1 value to calulate the distance between
  6538. * @param value2 value to calulate the distance between
  6539. * @return the distance between the two vectors
  6540. */
  6541. Vector4.Distance = function (value1, value2) {
  6542. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  6543. };
  6544. /**
  6545. * Returns the squared distance (float) between the vectors "value1" and "value2".
  6546. * @param value1 value to calulate the distance between
  6547. * @param value2 value to calulate the distance between
  6548. * @return the distance between the two vectors squared
  6549. */
  6550. Vector4.DistanceSquared = function (value1, value2) {
  6551. var x = value1.x - value2.x;
  6552. var y = value1.y - value2.y;
  6553. var z = value1.z - value2.z;
  6554. var w = value1.w - value2.w;
  6555. return (x * x) + (y * y) + (z * z) + (w * w);
  6556. };
  6557. /**
  6558. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  6559. * @param value1 value to calulate the center between
  6560. * @param value2 value to calulate the center between
  6561. * @return the center between the two vectors
  6562. */
  6563. Vector4.Center = function (value1, value2) {
  6564. var center = value1.add(value2);
  6565. center.scaleInPlace(0.5);
  6566. return center;
  6567. };
  6568. /**
  6569. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  6570. * This methods computes transformed normalized direction vectors only.
  6571. * @param vector the vector to transform
  6572. * @param transformation the transformation matrix to apply
  6573. * @returns the new vector
  6574. */
  6575. Vector4.TransformNormal = function (vector, transformation) {
  6576. var result = Vector4.Zero();
  6577. Vector4.TransformNormalToRef(vector, transformation, result);
  6578. return result;
  6579. };
  6580. /**
  6581. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  6582. * This methods computes transformed normalized direction vectors only.
  6583. * @param vector the vector to transform
  6584. * @param transformation the transformation matrix to apply
  6585. * @param result the vector to store the result in
  6586. */
  6587. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  6588. var m = transformation.m;
  6589. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  6590. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  6591. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  6592. result.x = x;
  6593. result.y = y;
  6594. result.z = z;
  6595. result.w = vector.w;
  6596. };
  6597. /**
  6598. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  6599. * This methods computes transformed normalized direction vectors only.
  6600. * @param x value to transform
  6601. * @param y value to transform
  6602. * @param z value to transform
  6603. * @param w value to transform
  6604. * @param transformation the transformation matrix to apply
  6605. * @param result the vector to store the results in
  6606. */
  6607. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  6608. var m = transformation.m;
  6609. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  6610. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  6611. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  6612. result.w = w;
  6613. };
  6614. return Vector4;
  6615. }());
  6616. BABYLON.Vector4 = Vector4;
  6617. /**
  6618. * Size containing widht and height
  6619. */
  6620. var Size = /** @class */ (function () {
  6621. /**
  6622. * Creates a Size object from the given width and height (floats).
  6623. * @param width width of the new size
  6624. * @param height height of the new size
  6625. */
  6626. function Size(width, height) {
  6627. this.width = width;
  6628. this.height = height;
  6629. }
  6630. /**
  6631. * Returns a string with the Size width and height
  6632. * @returns a string with the Size width and height
  6633. */
  6634. Size.prototype.toString = function () {
  6635. return "{W: " + this.width + ", H: " + this.height + "}";
  6636. };
  6637. /**
  6638. * "Size"
  6639. * @returns the string "Size"
  6640. */
  6641. Size.prototype.getClassName = function () {
  6642. return "Size";
  6643. };
  6644. /**
  6645. * Returns the Size hash code.
  6646. * @returns a hash code for a unique width and height
  6647. */
  6648. Size.prototype.getHashCode = function () {
  6649. var hash = this.width || 0;
  6650. hash = (hash * 397) ^ (this.height || 0);
  6651. return hash;
  6652. };
  6653. /**
  6654. * Updates the current size from the given one.
  6655. * @param src the given size
  6656. */
  6657. Size.prototype.copyFrom = function (src) {
  6658. this.width = src.width;
  6659. this.height = src.height;
  6660. };
  6661. /**
  6662. * Updates in place the current Size from the given floats.
  6663. * @param width width of the new size
  6664. * @param height height of the new size
  6665. * @returns the updated Size.
  6666. */
  6667. Size.prototype.copyFromFloats = function (width, height) {
  6668. this.width = width;
  6669. this.height = height;
  6670. return this;
  6671. };
  6672. /**
  6673. * Updates in place the current Size from the given floats.
  6674. * @param width width to set
  6675. * @param height height to set
  6676. * @returns the updated Size.
  6677. */
  6678. Size.prototype.set = function (width, height) {
  6679. return this.copyFromFloats(width, height);
  6680. };
  6681. /**
  6682. * Multiplies the width and height by numbers
  6683. * @param w factor to multiple the width by
  6684. * @param h factor to multiple the height by
  6685. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  6686. */
  6687. Size.prototype.multiplyByFloats = function (w, h) {
  6688. return new Size(this.width * w, this.height * h);
  6689. };
  6690. /**
  6691. * Clones the size
  6692. * @returns a new Size copied from the given one.
  6693. */
  6694. Size.prototype.clone = function () {
  6695. return new Size(this.width, this.height);
  6696. };
  6697. /**
  6698. * True if the current Size and the given one width and height are strictly equal.
  6699. * @param other the other size to compare against
  6700. * @returns True if the current Size and the given one width and height are strictly equal.
  6701. */
  6702. Size.prototype.equals = function (other) {
  6703. if (!other) {
  6704. return false;
  6705. }
  6706. return (this.width === other.width) && (this.height === other.height);
  6707. };
  6708. Object.defineProperty(Size.prototype, "surface", {
  6709. /**
  6710. * The surface of the Size : width * height (float).
  6711. */
  6712. get: function () {
  6713. return this.width * this.height;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. /**
  6719. * Create a new size of zero
  6720. * @returns a new Size set to (0.0, 0.0)
  6721. */
  6722. Size.Zero = function () {
  6723. return new Size(0.0, 0.0);
  6724. };
  6725. /**
  6726. * Sums the width and height of two sizes
  6727. * @param otherSize size to add to this size
  6728. * @returns a new Size set as the addition result of the current Size and the given one.
  6729. */
  6730. Size.prototype.add = function (otherSize) {
  6731. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  6732. return r;
  6733. };
  6734. /**
  6735. * Subtracts the width and height of two
  6736. * @param otherSize size to subtract to this size
  6737. * @returns a new Size set as the subtraction result of the given one from the current Size.
  6738. */
  6739. Size.prototype.subtract = function (otherSize) {
  6740. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  6741. return r;
  6742. };
  6743. /**
  6744. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  6745. * @param start starting size to lerp between
  6746. * @param end end size to lerp between
  6747. * @param amount amount to lerp between the start and end values
  6748. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  6749. */
  6750. Size.Lerp = function (start, end, amount) {
  6751. var w = start.width + ((end.width - start.width) * amount);
  6752. var h = start.height + ((end.height - start.height) * amount);
  6753. return new Size(w, h);
  6754. };
  6755. return Size;
  6756. }());
  6757. BABYLON.Size = Size;
  6758. /**
  6759. * Class used to store quaternion data
  6760. * @see https://en.wikipedia.org/wiki/Quaternion
  6761. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  6762. */
  6763. var Quaternion = /** @class */ (function () {
  6764. /**
  6765. * Creates a new Quaternion from the given floats
  6766. * @param x defines the first component (0 by default)
  6767. * @param y defines the second component (0 by default)
  6768. * @param z defines the third component (0 by default)
  6769. * @param w defines the fourth component (1.0 by default)
  6770. */
  6771. function Quaternion(
  6772. /** defines the first component (0 by default) */
  6773. x,
  6774. /** defines the second component (0 by default) */
  6775. y,
  6776. /** defines the third component (0 by default) */
  6777. z,
  6778. /** defines the fourth component (1.0 by default) */
  6779. w) {
  6780. if (x === void 0) { x = 0.0; }
  6781. if (y === void 0) { y = 0.0; }
  6782. if (z === void 0) { z = 0.0; }
  6783. if (w === void 0) { w = 1.0; }
  6784. this.x = x;
  6785. this.y = y;
  6786. this.z = z;
  6787. this.w = w;
  6788. }
  6789. /**
  6790. * Gets a string representation for the current quaternion
  6791. * @returns a string with the Quaternion coordinates
  6792. */
  6793. Quaternion.prototype.toString = function () {
  6794. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6795. };
  6796. /**
  6797. * Gets the class name of the quaternion
  6798. * @returns the string "Quaternion"
  6799. */
  6800. Quaternion.prototype.getClassName = function () {
  6801. return "Quaternion";
  6802. };
  6803. /**
  6804. * Gets a hash code for this quaternion
  6805. * @returns the quaternion hash code
  6806. */
  6807. Quaternion.prototype.getHashCode = function () {
  6808. var hash = this.x || 0;
  6809. hash = (hash * 397) ^ (this.y || 0);
  6810. hash = (hash * 397) ^ (this.z || 0);
  6811. hash = (hash * 397) ^ (this.w || 0);
  6812. return hash;
  6813. };
  6814. /**
  6815. * Copy the quaternion to an array
  6816. * @returns a new array populated with 4 elements from the quaternion coordinates
  6817. */
  6818. Quaternion.prototype.asArray = function () {
  6819. return [this.x, this.y, this.z, this.w];
  6820. };
  6821. /**
  6822. * Check if two quaternions are equals
  6823. * @param otherQuaternion defines the second operand
  6824. * @return true if the current quaternion and the given one coordinates are strictly equals
  6825. */
  6826. Quaternion.prototype.equals = function (otherQuaternion) {
  6827. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  6828. };
  6829. /**
  6830. * Clone the current quaternion
  6831. * @returns a new quaternion copied from the current one
  6832. */
  6833. Quaternion.prototype.clone = function () {
  6834. return new Quaternion(this.x, this.y, this.z, this.w);
  6835. };
  6836. /**
  6837. * Copy a quaternion to the current one
  6838. * @param other defines the other quaternion
  6839. * @returns the updated current quaternion
  6840. */
  6841. Quaternion.prototype.copyFrom = function (other) {
  6842. this.x = other.x;
  6843. this.y = other.y;
  6844. this.z = other.z;
  6845. this.w = other.w;
  6846. return this;
  6847. };
  6848. /**
  6849. * Updates the current quaternion with the given float coordinates
  6850. * @param x defines the x coordinate
  6851. * @param y defines the y coordinate
  6852. * @param z defines the z coordinate
  6853. * @param w defines the w coordinate
  6854. * @returns the updated current quaternion
  6855. */
  6856. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  6857. this.x = x;
  6858. this.y = y;
  6859. this.z = z;
  6860. this.w = w;
  6861. return this;
  6862. };
  6863. /**
  6864. * Updates the current quaternion from the given float coordinates
  6865. * @param x defines the x coordinate
  6866. * @param y defines the y coordinate
  6867. * @param z defines the z coordinate
  6868. * @param w defines the w coordinate
  6869. * @returns the updated current quaternion
  6870. */
  6871. Quaternion.prototype.set = function (x, y, z, w) {
  6872. return this.copyFromFloats(x, y, z, w);
  6873. };
  6874. /**
  6875. * Adds two quaternions
  6876. * @param other defines the second operand
  6877. * @returns a new quaternion as the addition result of the given one and the current quaternion
  6878. */
  6879. Quaternion.prototype.add = function (other) {
  6880. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  6881. };
  6882. /**
  6883. * Add a quaternion to the current one
  6884. * @param other defines the quaternion to add
  6885. * @returns the current quaternion
  6886. */
  6887. Quaternion.prototype.addInPlace = function (other) {
  6888. this.x += other.x;
  6889. this.y += other.y;
  6890. this.z += other.z;
  6891. this.w += other.w;
  6892. return this;
  6893. };
  6894. /**
  6895. * Subtract two quaternions
  6896. * @param other defines the second operand
  6897. * @returns a new quaternion as the subtraction result of the given one from the current one
  6898. */
  6899. Quaternion.prototype.subtract = function (other) {
  6900. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  6901. };
  6902. /**
  6903. * Multiplies the current quaternion by a scale factor
  6904. * @param value defines the scale factor
  6905. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  6906. */
  6907. Quaternion.prototype.scale = function (value) {
  6908. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  6909. };
  6910. /**
  6911. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  6912. * @param scale defines the scale factor
  6913. * @param result defines the Quaternion object where to store the result
  6914. * @returns the unmodified current quaternion
  6915. */
  6916. Quaternion.prototype.scaleToRef = function (scale, result) {
  6917. result.x = this.x * scale;
  6918. result.y = this.y * scale;
  6919. result.z = this.z * scale;
  6920. result.w = this.w * scale;
  6921. return this;
  6922. };
  6923. /**
  6924. * Multiplies in place the current quaternion by a scale factor
  6925. * @param value defines the scale factor
  6926. * @returns the current modified quaternion
  6927. */
  6928. Quaternion.prototype.scaleInPlace = function (value) {
  6929. this.x *= value;
  6930. this.y *= value;
  6931. this.z *= value;
  6932. this.w *= value;
  6933. return this;
  6934. };
  6935. /**
  6936. * Scale the current quaternion values by a factor and add the result to a given quaternion
  6937. * @param scale defines the scale factor
  6938. * @param result defines the Quaternion object where to store the result
  6939. * @returns the unmodified current quaternion
  6940. */
  6941. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  6942. result.x += this.x * scale;
  6943. result.y += this.y * scale;
  6944. result.z += this.z * scale;
  6945. result.w += this.w * scale;
  6946. return this;
  6947. };
  6948. /**
  6949. * Multiplies two quaternions
  6950. * @param q1 defines the second operand
  6951. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  6952. */
  6953. Quaternion.prototype.multiply = function (q1) {
  6954. var result = new Quaternion(0, 0, 0, 1.0);
  6955. this.multiplyToRef(q1, result);
  6956. return result;
  6957. };
  6958. /**
  6959. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  6960. * @param q1 defines the second operand
  6961. * @param result defines the target quaternion
  6962. * @returns the current quaternion
  6963. */
  6964. Quaternion.prototype.multiplyToRef = function (q1, result) {
  6965. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  6966. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  6967. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  6968. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  6969. result.copyFromFloats(x, y, z, w);
  6970. return this;
  6971. };
  6972. /**
  6973. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  6974. * @param q1 defines the second operand
  6975. * @returns the currentupdated quaternion
  6976. */
  6977. Quaternion.prototype.multiplyInPlace = function (q1) {
  6978. this.multiplyToRef(q1, this);
  6979. return this;
  6980. };
  6981. /**
  6982. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  6983. * @param ref defines the target quaternion
  6984. * @returns the current quaternion
  6985. */
  6986. Quaternion.prototype.conjugateToRef = function (ref) {
  6987. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  6988. return this;
  6989. };
  6990. /**
  6991. * Conjugates in place (1-q) the current quaternion
  6992. * @returns the current updated quaternion
  6993. */
  6994. Quaternion.prototype.conjugateInPlace = function () {
  6995. this.x *= -1;
  6996. this.y *= -1;
  6997. this.z *= -1;
  6998. return this;
  6999. };
  7000. /**
  7001. * Conjugates in place (1-q) the current quaternion
  7002. * @returns a new quaternion
  7003. */
  7004. Quaternion.prototype.conjugate = function () {
  7005. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  7006. return result;
  7007. };
  7008. /**
  7009. * Gets length of current quaternion
  7010. * @returns the quaternion length (float)
  7011. */
  7012. Quaternion.prototype.length = function () {
  7013. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  7014. };
  7015. /**
  7016. * Normalize in place the current quaternion
  7017. * @returns the current updated quaternion
  7018. */
  7019. Quaternion.prototype.normalize = function () {
  7020. var length = 1.0 / this.length();
  7021. this.x *= length;
  7022. this.y *= length;
  7023. this.z *= length;
  7024. this.w *= length;
  7025. return this;
  7026. };
  7027. /**
  7028. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  7029. * @param order is a reserved parameter and is ignore for now
  7030. * @returns a new Vector3 containing the Euler angles
  7031. */
  7032. Quaternion.prototype.toEulerAngles = function (order) {
  7033. if (order === void 0) { order = "YZX"; }
  7034. var result = Vector3.Zero();
  7035. this.toEulerAnglesToRef(result, order);
  7036. return result;
  7037. };
  7038. /**
  7039. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  7040. * @param result defines the vector which will be filled with the Euler angles
  7041. * @param order is a reserved parameter and is ignore for now
  7042. * @returns the current unchanged quaternion
  7043. */
  7044. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  7045. if (order === void 0) { order = "YZX"; }
  7046. var qz = this.z;
  7047. var qx = this.x;
  7048. var qy = this.y;
  7049. var qw = this.w;
  7050. var sqw = qw * qw;
  7051. var sqz = qz * qz;
  7052. var sqx = qx * qx;
  7053. var sqy = qy * qy;
  7054. var zAxisY = qy * qz - qx * qw;
  7055. var limit = .4999999;
  7056. if (zAxisY < -limit) {
  7057. result.y = 2 * Math.atan2(qy, qw);
  7058. result.x = Math.PI / 2;
  7059. result.z = 0;
  7060. }
  7061. else if (zAxisY > limit) {
  7062. result.y = 2 * Math.atan2(qy, qw);
  7063. result.x = -Math.PI / 2;
  7064. result.z = 0;
  7065. }
  7066. else {
  7067. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  7068. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  7069. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  7070. }
  7071. return this;
  7072. };
  7073. /**
  7074. * Updates the given rotation matrix with the current quaternion values
  7075. * @param result defines the target matrix
  7076. * @returns the current unchanged quaternion
  7077. */
  7078. Quaternion.prototype.toRotationMatrix = function (result) {
  7079. var xx = this.x * this.x;
  7080. var yy = this.y * this.y;
  7081. var zz = this.z * this.z;
  7082. var xy = this.x * this.y;
  7083. var zw = this.z * this.w;
  7084. var zx = this.z * this.x;
  7085. var yw = this.y * this.w;
  7086. var yz = this.y * this.z;
  7087. var xw = this.x * this.w;
  7088. result.m[0] = 1.0 - (2.0 * (yy + zz));
  7089. result.m[1] = 2.0 * (xy + zw);
  7090. result.m[2] = 2.0 * (zx - yw);
  7091. result.m[3] = 0;
  7092. result.m[4] = 2.0 * (xy - zw);
  7093. result.m[5] = 1.0 - (2.0 * (zz + xx));
  7094. result.m[6] = 2.0 * (yz + xw);
  7095. result.m[7] = 0;
  7096. result.m[8] = 2.0 * (zx + yw);
  7097. result.m[9] = 2.0 * (yz - xw);
  7098. result.m[10] = 1.0 - (2.0 * (yy + xx));
  7099. result.m[11] = 0;
  7100. result.m[12] = 0;
  7101. result.m[13] = 0;
  7102. result.m[14] = 0;
  7103. result.m[15] = 1.0;
  7104. result._markAsUpdated();
  7105. return this;
  7106. };
  7107. /**
  7108. * Updates the current quaternion from the given rotation matrix values
  7109. * @param matrix defines the source matrix
  7110. * @returns the current updated quaternion
  7111. */
  7112. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  7113. Quaternion.FromRotationMatrixToRef(matrix, this);
  7114. return this;
  7115. };
  7116. // Statics
  7117. /**
  7118. * Creates a new quaternion from a rotation matrix
  7119. * @param matrix defines the source matrix
  7120. * @returns a new quaternion created from the given rotation matrix values
  7121. */
  7122. Quaternion.FromRotationMatrix = function (matrix) {
  7123. var result = new Quaternion();
  7124. Quaternion.FromRotationMatrixToRef(matrix, result);
  7125. return result;
  7126. };
  7127. /**
  7128. * Updates the given quaternion with the given rotation matrix values
  7129. * @param matrix defines the source matrix
  7130. * @param result defines the target quaternion
  7131. */
  7132. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  7133. var data = matrix.m;
  7134. var m11 = data[0], m12 = data[4], m13 = data[8];
  7135. var m21 = data[1], m22 = data[5], m23 = data[9];
  7136. var m31 = data[2], m32 = data[6], m33 = data[10];
  7137. var trace = m11 + m22 + m33;
  7138. var s;
  7139. if (trace > 0) {
  7140. s = 0.5 / Math.sqrt(trace + 1.0);
  7141. result.w = 0.25 / s;
  7142. result.x = (m32 - m23) * s;
  7143. result.y = (m13 - m31) * s;
  7144. result.z = (m21 - m12) * s;
  7145. }
  7146. else if (m11 > m22 && m11 > m33) {
  7147. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7148. result.w = (m32 - m23) / s;
  7149. result.x = 0.25 * s;
  7150. result.y = (m12 + m21) / s;
  7151. result.z = (m13 + m31) / s;
  7152. }
  7153. else if (m22 > m33) {
  7154. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7155. result.w = (m13 - m31) / s;
  7156. result.x = (m12 + m21) / s;
  7157. result.y = 0.25 * s;
  7158. result.z = (m23 + m32) / s;
  7159. }
  7160. else {
  7161. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7162. result.w = (m21 - m12) / s;
  7163. result.x = (m13 + m31) / s;
  7164. result.y = (m23 + m32) / s;
  7165. result.z = 0.25 * s;
  7166. }
  7167. };
  7168. /**
  7169. * Returns the dot product (float) between the quaternions "left" and "right"
  7170. * @param left defines the left operand
  7171. * @param right defines the right operand
  7172. * @returns the dot product
  7173. */
  7174. Quaternion.Dot = function (left, right) {
  7175. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  7176. };
  7177. /**
  7178. * Checks if the two quaternions are close to each other
  7179. * @param quat0 defines the first quaternion to check
  7180. * @param quat1 defines the second quaternion to check
  7181. * @returns true if the two quaternions are close to each other
  7182. */
  7183. Quaternion.AreClose = function (quat0, quat1) {
  7184. var dot = Quaternion.Dot(quat0, quat1);
  7185. return dot >= 0;
  7186. };
  7187. /**
  7188. * Creates an empty quaternion
  7189. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  7190. */
  7191. Quaternion.Zero = function () {
  7192. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  7193. };
  7194. /**
  7195. * Inverse a given quaternion
  7196. * @param q defines the source quaternion
  7197. * @returns a new quaternion as the inverted current quaternion
  7198. */
  7199. Quaternion.Inverse = function (q) {
  7200. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  7201. };
  7202. /**
  7203. * Creates an identity quaternion
  7204. * @returns the identity quaternion
  7205. */
  7206. Quaternion.Identity = function () {
  7207. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  7208. };
  7209. /**
  7210. * Gets a boolean indicating if the given quaternion is identity
  7211. * @param quaternion defines the quaternion to check
  7212. * @returns true if the quaternion is identity
  7213. */
  7214. Quaternion.IsIdentity = function (quaternion) {
  7215. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  7216. };
  7217. /**
  7218. * Creates a quaternion from a rotation around an axis
  7219. * @param axis defines the axis to use
  7220. * @param angle defines the angle to use
  7221. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  7222. */
  7223. Quaternion.RotationAxis = function (axis, angle) {
  7224. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  7225. };
  7226. /**
  7227. * Creates a rotation around an axis and stores it into the given quaternion
  7228. * @param axis defines the axis to use
  7229. * @param angle defines the angle to use
  7230. * @param result defines the target quaternion
  7231. * @returns the target quaternion
  7232. */
  7233. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  7234. var sin = Math.sin(angle / 2);
  7235. axis.normalize();
  7236. result.w = Math.cos(angle / 2);
  7237. result.x = axis.x * sin;
  7238. result.y = axis.y * sin;
  7239. result.z = axis.z * sin;
  7240. return result;
  7241. };
  7242. /**
  7243. * Creates a new quaternion from data stored into an array
  7244. * @param array defines the data source
  7245. * @param offset defines the offset in the source array where the data starts
  7246. * @returns a new quaternion
  7247. */
  7248. Quaternion.FromArray = function (array, offset) {
  7249. if (!offset) {
  7250. offset = 0;
  7251. }
  7252. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  7253. };
  7254. /**
  7255. * Creates a new quaternion from the given Euler float angles (y, x, z)
  7256. * @param yaw defines the rotation around Y axis
  7257. * @param pitch defines the rotation around X axis
  7258. * @param roll defines the rotation around Z axis
  7259. * @returns the new quaternion
  7260. */
  7261. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  7262. var q = new Quaternion();
  7263. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  7264. return q;
  7265. };
  7266. /**
  7267. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  7268. * @param yaw defines the rotation around Y axis
  7269. * @param pitch defines the rotation around X axis
  7270. * @param roll defines the rotation around Z axis
  7271. * @param result defines the target quaternion
  7272. */
  7273. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  7274. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  7275. var halfRoll = roll * 0.5;
  7276. var halfPitch = pitch * 0.5;
  7277. var halfYaw = yaw * 0.5;
  7278. var sinRoll = Math.sin(halfRoll);
  7279. var cosRoll = Math.cos(halfRoll);
  7280. var sinPitch = Math.sin(halfPitch);
  7281. var cosPitch = Math.cos(halfPitch);
  7282. var sinYaw = Math.sin(halfYaw);
  7283. var cosYaw = Math.cos(halfYaw);
  7284. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  7285. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  7286. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  7287. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  7288. };
  7289. /**
  7290. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  7291. * @param alpha defines the rotation around first axis
  7292. * @param beta defines the rotation around second axis
  7293. * @param gamma defines the rotation around third axis
  7294. * @returns the new quaternion
  7295. */
  7296. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  7297. var result = new Quaternion();
  7298. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  7299. return result;
  7300. };
  7301. /**
  7302. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  7303. * @param alpha defines the rotation around first axis
  7304. * @param beta defines the rotation around second axis
  7305. * @param gamma defines the rotation around third axis
  7306. * @param result defines the target quaternion
  7307. */
  7308. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  7309. // Produces a quaternion from Euler angles in the z-x-z orientation
  7310. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  7311. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  7312. var halfBeta = beta * 0.5;
  7313. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7314. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7315. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7316. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7317. };
  7318. /**
  7319. * 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)
  7320. * @param axis1 defines the first axis
  7321. * @param axis2 defines the second axis
  7322. * @param axis3 defines the third axis
  7323. * @returns the new quaternion
  7324. */
  7325. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  7326. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  7327. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  7328. return quat;
  7329. };
  7330. /**
  7331. * 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
  7332. * @param axis1 defines the first axis
  7333. * @param axis2 defines the second axis
  7334. * @param axis3 defines the third axis
  7335. * @param ref defines the target quaternion
  7336. */
  7337. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  7338. var rotMat = MathTmp.Matrix[0];
  7339. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  7340. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  7341. };
  7342. /**
  7343. * Interpolates between two quaternions
  7344. * @param left defines first quaternion
  7345. * @param right defines second quaternion
  7346. * @param amount defines the gradient to use
  7347. * @returns the new interpolated quaternion
  7348. */
  7349. Quaternion.Slerp = function (left, right, amount) {
  7350. var result = Quaternion.Identity();
  7351. Quaternion.SlerpToRef(left, right, amount, result);
  7352. return result;
  7353. };
  7354. /**
  7355. * Interpolates between two quaternions and stores it into a target quaternion
  7356. * @param left defines first quaternion
  7357. * @param right defines second quaternion
  7358. * @param amount defines the gradient to use
  7359. * @param result defines the target quaternion
  7360. */
  7361. Quaternion.SlerpToRef = function (left, right, amount, result) {
  7362. var num2;
  7363. var num3;
  7364. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  7365. var flag = false;
  7366. if (num4 < 0) {
  7367. flag = true;
  7368. num4 = -num4;
  7369. }
  7370. if (num4 > 0.999999) {
  7371. num3 = 1 - amount;
  7372. num2 = flag ? -amount : amount;
  7373. }
  7374. else {
  7375. var num5 = Math.acos(num4);
  7376. var num6 = (1.0 / Math.sin(num5));
  7377. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  7378. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  7379. }
  7380. result.x = (num3 * left.x) + (num2 * right.x);
  7381. result.y = (num3 * left.y) + (num2 * right.y);
  7382. result.z = (num3 * left.z) + (num2 * right.z);
  7383. result.w = (num3 * left.w) + (num2 * right.w);
  7384. };
  7385. /**
  7386. * Interpolate between two quaternions using Hermite interpolation
  7387. * @param value1 defines first quaternion
  7388. * @param tangent1 defines the incoming tangent
  7389. * @param value2 defines second quaternion
  7390. * @param tangent2 defines the outgoing tangent
  7391. * @param amount defines the target quaternion
  7392. * @returns the new interpolated quaternion
  7393. */
  7394. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7395. var squared = amount * amount;
  7396. var cubed = amount * squared;
  7397. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7398. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7399. var part3 = (cubed - (2.0 * squared)) + amount;
  7400. var part4 = cubed - squared;
  7401. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  7402. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  7403. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  7404. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  7405. return new Quaternion(x, y, z, w);
  7406. };
  7407. return Quaternion;
  7408. }());
  7409. BABYLON.Quaternion = Quaternion;
  7410. /**
  7411. * Class used to store matrix data (4x4)
  7412. */
  7413. var Matrix = /** @class */ (function () {
  7414. /**
  7415. * Creates an empty matrix (filled with zeros)
  7416. */
  7417. function Matrix() {
  7418. this._isIdentity = false;
  7419. this._isIdentityDirty = true;
  7420. this._isIdentity3x2 = true;
  7421. this._isIdentity3x2Dirty = true;
  7422. /**
  7423. * Gets or sets the internal data of the matrix
  7424. */
  7425. this.m = new Float32Array(16);
  7426. this._markAsUpdated();
  7427. }
  7428. /** @hidden */
  7429. Matrix.prototype._markAsUpdated = function () {
  7430. this.updateFlag = Matrix._updateFlagSeed++;
  7431. this._isIdentityDirty = true;
  7432. this._isIdentity3x2Dirty = true;
  7433. };
  7434. // Properties
  7435. /**
  7436. * Check if the current matrix is identity
  7437. * @returns true is the matrix is the identity matrix
  7438. */
  7439. Matrix.prototype.isIdentity = function () {
  7440. if (this._isIdentityDirty) {
  7441. this._isIdentityDirty = false;
  7442. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0) {
  7443. this._isIdentity = false;
  7444. }
  7445. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  7446. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  7447. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  7448. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  7449. this._isIdentity = false;
  7450. }
  7451. else {
  7452. this._isIdentity = true;
  7453. }
  7454. }
  7455. return this._isIdentity;
  7456. };
  7457. /**
  7458. * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
  7459. * @returns true is the matrix is the identity matrix
  7460. */
  7461. Matrix.prototype.isIdentityAs3x2 = function () {
  7462. if (this._isIdentity3x2Dirty) {
  7463. this._isIdentity3x2Dirty = false;
  7464. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  7465. this._isIdentity3x2 = false;
  7466. }
  7467. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  7468. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  7469. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[10] !== 0.0 || this.m[11] !== 0.0 ||
  7470. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  7471. this._isIdentity3x2 = false;
  7472. }
  7473. else {
  7474. this._isIdentity3x2 = true;
  7475. }
  7476. }
  7477. return this._isIdentity3x2;
  7478. };
  7479. /**
  7480. * Gets the determinant of the matrix
  7481. * @returns the matrix determinant
  7482. */
  7483. Matrix.prototype.determinant = function () {
  7484. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  7485. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  7486. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  7487. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  7488. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  7489. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  7490. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  7491. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  7492. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  7493. };
  7494. // Methods
  7495. /**
  7496. * Returns the matrix as a Float32Array
  7497. * @returns the matrix underlying array
  7498. */
  7499. Matrix.prototype.toArray = function () {
  7500. return this.m;
  7501. };
  7502. /**
  7503. * Returns the matrix as a Float32Array
  7504. * @returns the matrix underlying array.
  7505. */
  7506. Matrix.prototype.asArray = function () {
  7507. return this.toArray();
  7508. };
  7509. /**
  7510. * Inverts the current matrix in place
  7511. * @returns the current inverted matrix
  7512. */
  7513. Matrix.prototype.invert = function () {
  7514. this.invertToRef(this);
  7515. return this;
  7516. };
  7517. /**
  7518. * Sets all the matrix elements to zero
  7519. * @returns the current matrix
  7520. */
  7521. Matrix.prototype.reset = function () {
  7522. for (var index = 0; index < 16; index++) {
  7523. this.m[index] = 0.0;
  7524. }
  7525. this._markAsUpdated();
  7526. return this;
  7527. };
  7528. /**
  7529. * Adds the current matrix with a second one
  7530. * @param other defines the matrix to add
  7531. * @returns a new matrix as the addition of the current matrix and the given one
  7532. */
  7533. Matrix.prototype.add = function (other) {
  7534. var result = new Matrix();
  7535. this.addToRef(other, result);
  7536. return result;
  7537. };
  7538. /**
  7539. * Sets the given matrix "result" to the addition of the current matrix and the given one
  7540. * @param other defines the matrix to add
  7541. * @param result defines the target matrix
  7542. * @returns the current matrix
  7543. */
  7544. Matrix.prototype.addToRef = function (other, result) {
  7545. for (var index = 0; index < 16; index++) {
  7546. result.m[index] = this.m[index] + other.m[index];
  7547. }
  7548. result._markAsUpdated();
  7549. return this;
  7550. };
  7551. /**
  7552. * Adds in place the given matrix to the current matrix
  7553. * @param other defines the second operand
  7554. * @returns the current updated matrix
  7555. */
  7556. Matrix.prototype.addToSelf = function (other) {
  7557. for (var index = 0; index < 16; index++) {
  7558. this.m[index] += other.m[index];
  7559. }
  7560. this._markAsUpdated();
  7561. return this;
  7562. };
  7563. /**
  7564. * Sets the given matrix to the current inverted Matrix
  7565. * @param other defines the target matrix
  7566. * @returns the unmodified current matrix
  7567. */
  7568. Matrix.prototype.invertToRef = function (other) {
  7569. var l1 = this.m[0];
  7570. var l2 = this.m[1];
  7571. var l3 = this.m[2];
  7572. var l4 = this.m[3];
  7573. var l5 = this.m[4];
  7574. var l6 = this.m[5];
  7575. var l7 = this.m[6];
  7576. var l8 = this.m[7];
  7577. var l9 = this.m[8];
  7578. var l10 = this.m[9];
  7579. var l11 = this.m[10];
  7580. var l12 = this.m[11];
  7581. var l13 = this.m[12];
  7582. var l14 = this.m[13];
  7583. var l15 = this.m[14];
  7584. var l16 = this.m[15];
  7585. var l17 = (l11 * l16) - (l12 * l15);
  7586. var l18 = (l10 * l16) - (l12 * l14);
  7587. var l19 = (l10 * l15) - (l11 * l14);
  7588. var l20 = (l9 * l16) - (l12 * l13);
  7589. var l21 = (l9 * l15) - (l11 * l13);
  7590. var l22 = (l9 * l14) - (l10 * l13);
  7591. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  7592. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  7593. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  7594. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  7595. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  7596. var l28 = (l7 * l16) - (l8 * l15);
  7597. var l29 = (l6 * l16) - (l8 * l14);
  7598. var l30 = (l6 * l15) - (l7 * l14);
  7599. var l31 = (l5 * l16) - (l8 * l13);
  7600. var l32 = (l5 * l15) - (l7 * l13);
  7601. var l33 = (l5 * l14) - (l6 * l13);
  7602. var l34 = (l7 * l12) - (l8 * l11);
  7603. var l35 = (l6 * l12) - (l8 * l10);
  7604. var l36 = (l6 * l11) - (l7 * l10);
  7605. var l37 = (l5 * l12) - (l8 * l9);
  7606. var l38 = (l5 * l11) - (l7 * l9);
  7607. var l39 = (l5 * l10) - (l6 * l9);
  7608. other.m[0] = l23 * l27;
  7609. other.m[4] = l24 * l27;
  7610. other.m[8] = l25 * l27;
  7611. other.m[12] = l26 * l27;
  7612. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  7613. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  7614. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  7615. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  7616. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  7617. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  7618. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  7619. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  7620. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  7621. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  7622. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  7623. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  7624. other._markAsUpdated();
  7625. return this;
  7626. };
  7627. /**
  7628. * Inserts the translation vector (using 3 floats) in the current matrix
  7629. * @param x defines the 1st component of the translation
  7630. * @param y defines the 2nd component of the translation
  7631. * @param z defines the 3rd component of the translation
  7632. * @returns the current updated matrix
  7633. */
  7634. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  7635. this.m[12] = x;
  7636. this.m[13] = y;
  7637. this.m[14] = z;
  7638. this._markAsUpdated();
  7639. return this;
  7640. };
  7641. /**
  7642. * Inserts the translation vector in the current matrix
  7643. * @param vector3 defines the translation to insert
  7644. * @returns the current updated matrix
  7645. */
  7646. Matrix.prototype.setTranslation = function (vector3) {
  7647. this.m[12] = vector3.x;
  7648. this.m[13] = vector3.y;
  7649. this.m[14] = vector3.z;
  7650. this._markAsUpdated();
  7651. return this;
  7652. };
  7653. /**
  7654. * Gets the translation value of the current matrix
  7655. * @returns a new Vector3 as the extracted translation from the matrix
  7656. */
  7657. Matrix.prototype.getTranslation = function () {
  7658. return new Vector3(this.m[12], this.m[13], this.m[14]);
  7659. };
  7660. /**
  7661. * Fill a Vector3 with the extracted translation from the matrix
  7662. * @param result defines the Vector3 where to store the translation
  7663. * @returns the current matrix
  7664. */
  7665. Matrix.prototype.getTranslationToRef = function (result) {
  7666. result.x = this.m[12];
  7667. result.y = this.m[13];
  7668. result.z = this.m[14];
  7669. return this;
  7670. };
  7671. /**
  7672. * Remove rotation and scaling part from the matrix
  7673. * @returns the updated matrix
  7674. */
  7675. Matrix.prototype.removeRotationAndScaling = function () {
  7676. this.setRowFromFloats(0, 1, 0, 0, 0);
  7677. this.setRowFromFloats(1, 0, 1, 0, 0);
  7678. this.setRowFromFloats(2, 0, 0, 1, 0);
  7679. return this;
  7680. };
  7681. /**
  7682. * Multiply two matrices
  7683. * @param other defines the second operand
  7684. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  7685. */
  7686. Matrix.prototype.multiply = function (other) {
  7687. var result = new Matrix();
  7688. this.multiplyToRef(other, result);
  7689. return result;
  7690. };
  7691. /**
  7692. * Copy the current matrix from the given one
  7693. * @param other defines the source matrix
  7694. * @returns the current updated matrix
  7695. */
  7696. Matrix.prototype.copyFrom = function (other) {
  7697. for (var index = 0; index < 16; index++) {
  7698. this.m[index] = other.m[index];
  7699. }
  7700. this._markAsUpdated();
  7701. return this;
  7702. };
  7703. /**
  7704. * Populates the given array from the starting index with the current matrix values
  7705. * @param array defines the target array
  7706. * @param offset defines the offset in the target array where to start storing values
  7707. * @returns the current matrix
  7708. */
  7709. Matrix.prototype.copyToArray = function (array, offset) {
  7710. if (offset === void 0) { offset = 0; }
  7711. for (var index = 0; index < 16; index++) {
  7712. array[offset + index] = this.m[index];
  7713. }
  7714. return this;
  7715. };
  7716. /**
  7717. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  7718. * @param other defines the second operand
  7719. * @param result defines the matrix where to store the multiplication
  7720. * @returns the current matrix
  7721. */
  7722. Matrix.prototype.multiplyToRef = function (other, result) {
  7723. this.multiplyToArray(other, result.m, 0);
  7724. result._markAsUpdated();
  7725. return this;
  7726. };
  7727. /**
  7728. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  7729. * @param other defines the second operand
  7730. * @param result defines the array where to store the multiplication
  7731. * @param offset defines the offset in the target array where to start storing values
  7732. * @returns the current matrix
  7733. */
  7734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  7735. var tm0 = this.m[0];
  7736. var tm1 = this.m[1];
  7737. var tm2 = this.m[2];
  7738. var tm3 = this.m[3];
  7739. var tm4 = this.m[4];
  7740. var tm5 = this.m[5];
  7741. var tm6 = this.m[6];
  7742. var tm7 = this.m[7];
  7743. var tm8 = this.m[8];
  7744. var tm9 = this.m[9];
  7745. var tm10 = this.m[10];
  7746. var tm11 = this.m[11];
  7747. var tm12 = this.m[12];
  7748. var tm13 = this.m[13];
  7749. var tm14 = this.m[14];
  7750. var tm15 = this.m[15];
  7751. var om0 = other.m[0];
  7752. var om1 = other.m[1];
  7753. var om2 = other.m[2];
  7754. var om3 = other.m[3];
  7755. var om4 = other.m[4];
  7756. var om5 = other.m[5];
  7757. var om6 = other.m[6];
  7758. var om7 = other.m[7];
  7759. var om8 = other.m[8];
  7760. var om9 = other.m[9];
  7761. var om10 = other.m[10];
  7762. var om11 = other.m[11];
  7763. var om12 = other.m[12];
  7764. var om13 = other.m[13];
  7765. var om14 = other.m[14];
  7766. var om15 = other.m[15];
  7767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  7768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  7769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  7770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  7771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  7772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  7773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  7774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  7775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  7776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  7777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  7778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  7779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  7780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  7781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  7782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  7783. return this;
  7784. };
  7785. /**
  7786. * Check equality between this matrix and a second one
  7787. * @param value defines the second matrix to compare
  7788. * @returns true is the current matrix and the given one values are strictly equal
  7789. */
  7790. Matrix.prototype.equals = function (value) {
  7791. return value &&
  7792. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  7793. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  7794. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  7795. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  7796. };
  7797. /**
  7798. * Clone the current matrix
  7799. * @returns a new matrix from the current matrix
  7800. */
  7801. Matrix.prototype.clone = function () {
  7802. 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]);
  7803. };
  7804. /**
  7805. * Returns the name of the current matrix class
  7806. * @returns the string "Matrix"
  7807. */
  7808. Matrix.prototype.getClassName = function () {
  7809. return "Matrix";
  7810. };
  7811. /**
  7812. * Gets the hash code of the current matrix
  7813. * @returns the hash code
  7814. */
  7815. Matrix.prototype.getHashCode = function () {
  7816. var hash = this.m[0] || 0;
  7817. for (var i = 1; i < 16; i++) {
  7818. hash = (hash * 397) ^ (this.m[i] || 0);
  7819. }
  7820. return hash;
  7821. };
  7822. /**
  7823. * Decomposes the current Matrix into a translation, rotation and scaling components
  7824. * @param scale defines the scale vector3 given as a reference to update
  7825. * @param rotation defines the rotation quaternion given as a reference to update
  7826. * @param translation defines the translation vector3 given as a reference to update
  7827. * @returns true if operation was successful
  7828. */
  7829. Matrix.prototype.decompose = function (scale, rotation, translation) {
  7830. if (translation) {
  7831. translation.x = this.m[12];
  7832. translation.y = this.m[13];
  7833. translation.z = this.m[14];
  7834. }
  7835. scale = scale || MathTmp.Vector3[0];
  7836. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  7837. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  7838. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  7839. if (this.determinant() <= 0) {
  7840. scale.y *= -1;
  7841. }
  7842. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  7843. if (rotation) {
  7844. rotation.x = 0;
  7845. rotation.y = 0;
  7846. rotation.z = 0;
  7847. rotation.w = 1;
  7848. }
  7849. return false;
  7850. }
  7851. if (rotation) {
  7852. 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]);
  7853. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  7854. }
  7855. return true;
  7856. };
  7857. /**
  7858. * Gets specific row of the matrix
  7859. * @param index defines the number of the row to get
  7860. * @returns the index-th row of the current matrix as a new Vector4
  7861. */
  7862. Matrix.prototype.getRow = function (index) {
  7863. if (index < 0 || index > 3) {
  7864. return null;
  7865. }
  7866. var i = index * 4;
  7867. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  7868. };
  7869. /**
  7870. * Sets the index-th row of the current matrix to the vector4 values
  7871. * @param index defines the number of the row to set
  7872. * @param row defines the target vector4
  7873. * @returns the updated current matrix
  7874. */
  7875. Matrix.prototype.setRow = function (index, row) {
  7876. if (index < 0 || index > 3) {
  7877. return this;
  7878. }
  7879. var i = index * 4;
  7880. this.m[i + 0] = row.x;
  7881. this.m[i + 1] = row.y;
  7882. this.m[i + 2] = row.z;
  7883. this.m[i + 3] = row.w;
  7884. this._markAsUpdated();
  7885. return this;
  7886. };
  7887. /**
  7888. * Compute the transpose of the matrix
  7889. * @returns the new transposed matrix
  7890. */
  7891. Matrix.prototype.transpose = function () {
  7892. return Matrix.Transpose(this);
  7893. };
  7894. /**
  7895. * Compute the transpose of the matrix and store it in a given matrix
  7896. * @param result defines the target matrix
  7897. * @returns the current matrix
  7898. */
  7899. Matrix.prototype.transposeToRef = function (result) {
  7900. Matrix.TransposeToRef(this, result);
  7901. return this;
  7902. };
  7903. /**
  7904. * Sets the index-th row of the current matrix with the given 4 x float values
  7905. * @param index defines the row index
  7906. * @param x defines the x component to set
  7907. * @param y defines the y component to set
  7908. * @param z defines the z component to set
  7909. * @param w defines the w component to set
  7910. * @returns the updated current matrix
  7911. */
  7912. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  7913. if (index < 0 || index > 3) {
  7914. return this;
  7915. }
  7916. var i = index * 4;
  7917. this.m[i + 0] = x;
  7918. this.m[i + 1] = y;
  7919. this.m[i + 2] = z;
  7920. this.m[i + 3] = w;
  7921. this._markAsUpdated();
  7922. return this;
  7923. };
  7924. /**
  7925. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  7926. * @param scale defines the scale factor
  7927. * @returns a new matrix
  7928. */
  7929. Matrix.prototype.scale = function (scale) {
  7930. var result = new Matrix();
  7931. this.scaleToRef(scale, result);
  7932. return result;
  7933. };
  7934. /**
  7935. * Scale the current matrix values by a factor to a given result matrix
  7936. * @param scale defines the scale factor
  7937. * @param result defines the matrix to store the result
  7938. * @returns the current matrix
  7939. */
  7940. Matrix.prototype.scaleToRef = function (scale, result) {
  7941. for (var index = 0; index < 16; index++) {
  7942. result.m[index] = this.m[index] * scale;
  7943. }
  7944. result._markAsUpdated();
  7945. return this;
  7946. };
  7947. /**
  7948. * Scale the current matrix values by a factor and add the result to a given matrix
  7949. * @param scale defines the scale factor
  7950. * @param result defines the Matrix to store the result
  7951. * @returns the current matrix
  7952. */
  7953. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  7954. for (var index = 0; index < 16; index++) {
  7955. result.m[index] += this.m[index] * scale;
  7956. }
  7957. result._markAsUpdated();
  7958. return this;
  7959. };
  7960. /**
  7961. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  7962. * @param ref matrix to store the result
  7963. */
  7964. Matrix.prototype.toNormalMatrix = function (ref) {
  7965. this.invertToRef(ref);
  7966. ref.transpose();
  7967. var m = ref.m;
  7968. 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);
  7969. };
  7970. /**
  7971. * Gets only rotation part of the current matrix
  7972. * @returns a new matrix sets to the extracted rotation matrix from the current one
  7973. */
  7974. Matrix.prototype.getRotationMatrix = function () {
  7975. var result = Matrix.Identity();
  7976. this.getRotationMatrixToRef(result);
  7977. return result;
  7978. };
  7979. /**
  7980. * Extracts the rotation matrix from the current one and sets it as the given "result"
  7981. * @param result defines the target matrix to store data to
  7982. * @returns the current matrix
  7983. */
  7984. Matrix.prototype.getRotationMatrixToRef = function (result) {
  7985. var m = this.m;
  7986. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  7987. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  7988. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  7989. if (this.determinant() <= 0) {
  7990. sy *= -1;
  7991. }
  7992. if (sx === 0 || sy === 0 || sz === 0) {
  7993. Matrix.IdentityToRef(result);
  7994. }
  7995. else {
  7996. 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);
  7997. }
  7998. return this;
  7999. };
  8000. /**
  8001. * Toggles model matrix from being right handed to left handed in place and vice versa
  8002. */
  8003. Matrix.prototype.toggleModelMatrixHandInPlace = function () {
  8004. var _this = this;
  8005. [2, 6, 8, 9, 14].forEach(function (num) {
  8006. _this.m[num] *= -1;
  8007. });
  8008. };
  8009. /**
  8010. * Toggles projection matrix from being right handed to left handed in place and vice versa
  8011. */
  8012. Matrix.prototype.toggleProjectionMatrixHandInPlace = function () {
  8013. var _this = this;
  8014. [8, 9, 10, 11].forEach(function (num) {
  8015. _this.m[num] *= -1;
  8016. });
  8017. };
  8018. // Statics
  8019. /**
  8020. * Creates a matrix from an array
  8021. * @param array defines the source array
  8022. * @param offset defines an offset in the source array
  8023. * @returns a new Matrix set from the starting index of the given array
  8024. */
  8025. Matrix.FromArray = function (array, offset) {
  8026. var result = new Matrix();
  8027. if (!offset) {
  8028. offset = 0;
  8029. }
  8030. Matrix.FromArrayToRef(array, offset, result);
  8031. return result;
  8032. };
  8033. /**
  8034. * Copy the content of an array into a given matrix
  8035. * @param array defines the source array
  8036. * @param offset defines an offset in the source array
  8037. * @param result defines the target matrix
  8038. */
  8039. Matrix.FromArrayToRef = function (array, offset, result) {
  8040. for (var index = 0; index < 16; index++) {
  8041. result.m[index] = array[index + offset];
  8042. }
  8043. result._markAsUpdated();
  8044. };
  8045. /**
  8046. * Stores an array into a matrix after having multiplied each component by a given factor
  8047. * @param array defines the source array
  8048. * @param offset defines the offset in the source array
  8049. * @param scale defines the scaling factor
  8050. * @param result defines the target matrix
  8051. */
  8052. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  8053. for (var index = 0; index < 16; index++) {
  8054. result.m[index] = array[index + offset] * scale;
  8055. }
  8056. result._markAsUpdated();
  8057. };
  8058. /**
  8059. * Stores a list of values (16) inside a given matrix
  8060. * @param initialM11 defines 1st value of 1st row
  8061. * @param initialM12 defines 2nd value of 1st row
  8062. * @param initialM13 defines 3rd value of 1st row
  8063. * @param initialM14 defines 4th value of 1st row
  8064. * @param initialM21 defines 1st value of 2nd row
  8065. * @param initialM22 defines 2nd value of 2nd row
  8066. * @param initialM23 defines 3rd value of 2nd row
  8067. * @param initialM24 defines 4th value of 2nd row
  8068. * @param initialM31 defines 1st value of 3rd row
  8069. * @param initialM32 defines 2nd value of 3rd row
  8070. * @param initialM33 defines 3rd value of 3rd row
  8071. * @param initialM34 defines 4th value of 3rd row
  8072. * @param initialM41 defines 1st value of 4th row
  8073. * @param initialM42 defines 2nd value of 4th row
  8074. * @param initialM43 defines 3rd value of 4th row
  8075. * @param initialM44 defines 4th value of 4th row
  8076. * @param result defines the target matrix
  8077. */
  8078. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  8079. result.m[0] = initialM11;
  8080. result.m[1] = initialM12;
  8081. result.m[2] = initialM13;
  8082. result.m[3] = initialM14;
  8083. result.m[4] = initialM21;
  8084. result.m[5] = initialM22;
  8085. result.m[6] = initialM23;
  8086. result.m[7] = initialM24;
  8087. result.m[8] = initialM31;
  8088. result.m[9] = initialM32;
  8089. result.m[10] = initialM33;
  8090. result.m[11] = initialM34;
  8091. result.m[12] = initialM41;
  8092. result.m[13] = initialM42;
  8093. result.m[14] = initialM43;
  8094. result.m[15] = initialM44;
  8095. result._markAsUpdated();
  8096. };
  8097. Object.defineProperty(Matrix, "IdentityReadOnly", {
  8098. /**
  8099. * Gets an identity matrix that must not be updated
  8100. */
  8101. get: function () {
  8102. return Matrix._identityReadOnly;
  8103. },
  8104. enumerable: true,
  8105. configurable: true
  8106. });
  8107. /**
  8108. * Creates new matrix from a list of values (16)
  8109. * @param initialM11 defines 1st value of 1st row
  8110. * @param initialM12 defines 2nd value of 1st row
  8111. * @param initialM13 defines 3rd value of 1st row
  8112. * @param initialM14 defines 4th value of 1st row
  8113. * @param initialM21 defines 1st value of 2nd row
  8114. * @param initialM22 defines 2nd value of 2nd row
  8115. * @param initialM23 defines 3rd value of 2nd row
  8116. * @param initialM24 defines 4th value of 2nd row
  8117. * @param initialM31 defines 1st value of 3rd row
  8118. * @param initialM32 defines 2nd value of 3rd row
  8119. * @param initialM33 defines 3rd value of 3rd row
  8120. * @param initialM34 defines 4th value of 3rd row
  8121. * @param initialM41 defines 1st value of 4th row
  8122. * @param initialM42 defines 2nd value of 4th row
  8123. * @param initialM43 defines 3rd value of 4th row
  8124. * @param initialM44 defines 4th value of 4th row
  8125. * @returns the new matrix
  8126. */
  8127. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  8128. var result = new Matrix();
  8129. result.m[0] = initialM11;
  8130. result.m[1] = initialM12;
  8131. result.m[2] = initialM13;
  8132. result.m[3] = initialM14;
  8133. result.m[4] = initialM21;
  8134. result.m[5] = initialM22;
  8135. result.m[6] = initialM23;
  8136. result.m[7] = initialM24;
  8137. result.m[8] = initialM31;
  8138. result.m[9] = initialM32;
  8139. result.m[10] = initialM33;
  8140. result.m[11] = initialM34;
  8141. result.m[12] = initialM41;
  8142. result.m[13] = initialM42;
  8143. result.m[14] = initialM43;
  8144. result.m[15] = initialM44;
  8145. return result;
  8146. };
  8147. /**
  8148. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8149. * @param scale defines the scale vector3
  8150. * @param rotation defines the rotation quaternion
  8151. * @param translation defines the translation vector3
  8152. * @returns a new matrix
  8153. */
  8154. Matrix.Compose = function (scale, rotation, translation) {
  8155. var result = Matrix.Identity();
  8156. Matrix.ComposeToRef(scale, rotation, translation, result);
  8157. return result;
  8158. };
  8159. /**
  8160. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8161. * @param scale defines the scale vector3
  8162. * @param rotation defines the rotation quaternion
  8163. * @param translation defines the translation vector3
  8164. * @param result defines the target matrix
  8165. */
  8166. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  8167. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  8168. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  8169. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  8170. result.setTranslation(translation);
  8171. };
  8172. /**
  8173. * Creates a new identity matrix
  8174. * @returns a new identity matrix
  8175. */
  8176. Matrix.Identity = function () {
  8177. 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);
  8178. };
  8179. /**
  8180. * Creates a new identity matrix and stores the result in a given matrix
  8181. * @param result defines the target matrix
  8182. */
  8183. Matrix.IdentityToRef = function (result) {
  8184. 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);
  8185. };
  8186. /**
  8187. * Creates a new zero matrix
  8188. * @returns a new zero matrix
  8189. */
  8190. Matrix.Zero = function () {
  8191. 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);
  8192. };
  8193. /**
  8194. * Creates a new rotation matrix for "angle" radians around the X axis
  8195. * @param angle defines the angle (in radians) to use
  8196. * @return the new matrix
  8197. */
  8198. Matrix.RotationX = function (angle) {
  8199. var result = new Matrix();
  8200. Matrix.RotationXToRef(angle, result);
  8201. return result;
  8202. };
  8203. /**
  8204. * Creates a new matrix as the invert of a given matrix
  8205. * @param source defines the source matrix
  8206. * @returns the new matrix
  8207. */
  8208. Matrix.Invert = function (source) {
  8209. var result = new Matrix();
  8210. source.invertToRef(result);
  8211. return result;
  8212. };
  8213. /**
  8214. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  8215. * @param angle defines the angle (in radians) to use
  8216. * @param result defines the target matrix
  8217. */
  8218. Matrix.RotationXToRef = function (angle, result) {
  8219. var s = Math.sin(angle);
  8220. var c = Math.cos(angle);
  8221. result.m[0] = 1.0;
  8222. result.m[15] = 1.0;
  8223. result.m[5] = c;
  8224. result.m[10] = c;
  8225. result.m[9] = -s;
  8226. result.m[6] = s;
  8227. result.m[1] = 0.0;
  8228. result.m[2] = 0.0;
  8229. result.m[3] = 0.0;
  8230. result.m[4] = 0.0;
  8231. result.m[7] = 0.0;
  8232. result.m[8] = 0.0;
  8233. result.m[11] = 0.0;
  8234. result.m[12] = 0.0;
  8235. result.m[13] = 0.0;
  8236. result.m[14] = 0.0;
  8237. result._markAsUpdated();
  8238. };
  8239. /**
  8240. * Creates a new rotation matrix for "angle" radians around the Y axis
  8241. * @param angle defines the angle (in radians) to use
  8242. * @return the new matrix
  8243. */
  8244. Matrix.RotationY = function (angle) {
  8245. var result = new Matrix();
  8246. Matrix.RotationYToRef(angle, result);
  8247. return result;
  8248. };
  8249. /**
  8250. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  8251. * @param angle defines the angle (in radians) to use
  8252. * @param result defines the target matrix
  8253. */
  8254. Matrix.RotationYToRef = function (angle, result) {
  8255. var s = Math.sin(angle);
  8256. var c = Math.cos(angle);
  8257. result.m[5] = 1.0;
  8258. result.m[15] = 1.0;
  8259. result.m[0] = c;
  8260. result.m[2] = -s;
  8261. result.m[8] = s;
  8262. result.m[10] = c;
  8263. result.m[1] = 0.0;
  8264. result.m[3] = 0.0;
  8265. result.m[4] = 0.0;
  8266. result.m[6] = 0.0;
  8267. result.m[7] = 0.0;
  8268. result.m[9] = 0.0;
  8269. result.m[11] = 0.0;
  8270. result.m[12] = 0.0;
  8271. result.m[13] = 0.0;
  8272. result.m[14] = 0.0;
  8273. result._markAsUpdated();
  8274. };
  8275. /**
  8276. * Creates a new rotation matrix for "angle" radians around the Z axis
  8277. * @param angle defines the angle (in radians) to use
  8278. * @return the new matrix
  8279. */
  8280. Matrix.RotationZ = function (angle) {
  8281. var result = new Matrix();
  8282. Matrix.RotationZToRef(angle, result);
  8283. return result;
  8284. };
  8285. /**
  8286. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  8287. * @param angle defines the angle (in radians) to use
  8288. * @param result defines the target matrix
  8289. */
  8290. Matrix.RotationZToRef = function (angle, result) {
  8291. var s = Math.sin(angle);
  8292. var c = Math.cos(angle);
  8293. result.m[10] = 1.0;
  8294. result.m[15] = 1.0;
  8295. result.m[0] = c;
  8296. result.m[1] = s;
  8297. result.m[4] = -s;
  8298. result.m[5] = c;
  8299. result.m[2] = 0.0;
  8300. result.m[3] = 0.0;
  8301. result.m[6] = 0.0;
  8302. result.m[7] = 0.0;
  8303. result.m[8] = 0.0;
  8304. result.m[9] = 0.0;
  8305. result.m[11] = 0.0;
  8306. result.m[12] = 0.0;
  8307. result.m[13] = 0.0;
  8308. result.m[14] = 0.0;
  8309. result._markAsUpdated();
  8310. };
  8311. /**
  8312. * Creates a new rotation matrix for "angle" radians around the given axis
  8313. * @param axis defines the axis to use
  8314. * @param angle defines the angle (in radians) to use
  8315. * @return the new matrix
  8316. */
  8317. Matrix.RotationAxis = function (axis, angle) {
  8318. var result = Matrix.Zero();
  8319. Matrix.RotationAxisToRef(axis, angle, result);
  8320. return result;
  8321. };
  8322. /**
  8323. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  8324. * @param axis defines the axis to use
  8325. * @param angle defines the angle (in radians) to use
  8326. * @param result defines the target matrix
  8327. */
  8328. Matrix.RotationAxisToRef = function (axis, angle, result) {
  8329. var s = Math.sin(-angle);
  8330. var c = Math.cos(-angle);
  8331. var c1 = 1 - c;
  8332. axis.normalize();
  8333. result.m[0] = (axis.x * axis.x) * c1 + c;
  8334. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  8335. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  8336. result.m[3] = 0.0;
  8337. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  8338. result.m[5] = (axis.y * axis.y) * c1 + c;
  8339. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  8340. result.m[7] = 0.0;
  8341. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  8342. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  8343. result.m[10] = (axis.z * axis.z) * c1 + c;
  8344. result.m[11] = 0.0;
  8345. result.m[15] = 1.0;
  8346. result._markAsUpdated();
  8347. };
  8348. /**
  8349. * Creates a rotation matrix
  8350. * @param yaw defines the yaw angle in radians (Y axis)
  8351. * @param pitch defines the pitch angle in radians (X axis)
  8352. * @param roll defines the roll angle in radians (X axis)
  8353. * @returns the new rotation matrix
  8354. */
  8355. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  8356. var result = new Matrix();
  8357. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  8358. return result;
  8359. };
  8360. /**
  8361. * Creates a rotation matrix and stores it in a given matrix
  8362. * @param yaw defines the yaw angle in radians (Y axis)
  8363. * @param pitch defines the pitch angle in radians (X axis)
  8364. * @param roll defines the roll angle in radians (X axis)
  8365. * @param result defines the target matrix
  8366. */
  8367. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  8368. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  8369. this._tempQuaternion.toRotationMatrix(result);
  8370. };
  8371. /**
  8372. * Creates a scaling matrix
  8373. * @param x defines the scale factor on X axis
  8374. * @param y defines the scale factor on Y axis
  8375. * @param z defines the scale factor on Z axis
  8376. * @returns the new matrix
  8377. */
  8378. Matrix.Scaling = function (x, y, z) {
  8379. var result = Matrix.Zero();
  8380. Matrix.ScalingToRef(x, y, z, result);
  8381. return result;
  8382. };
  8383. /**
  8384. * Creates a scaling matrix and stores it in a given matrix
  8385. * @param x defines the scale factor on X axis
  8386. * @param y defines the scale factor on Y axis
  8387. * @param z defines the scale factor on Z axis
  8388. * @param result defines the target matrix
  8389. */
  8390. Matrix.ScalingToRef = function (x, y, z, result) {
  8391. result.m[0] = x;
  8392. result.m[1] = 0.0;
  8393. result.m[2] = 0.0;
  8394. result.m[3] = 0.0;
  8395. result.m[4] = 0.0;
  8396. result.m[5] = y;
  8397. result.m[6] = 0.0;
  8398. result.m[7] = 0.0;
  8399. result.m[8] = 0.0;
  8400. result.m[9] = 0.0;
  8401. result.m[10] = z;
  8402. result.m[11] = 0.0;
  8403. result.m[12] = 0.0;
  8404. result.m[13] = 0.0;
  8405. result.m[14] = 0.0;
  8406. result.m[15] = 1.0;
  8407. result._markAsUpdated();
  8408. };
  8409. /**
  8410. * Creates a translation matrix
  8411. * @param x defines the translation on X axis
  8412. * @param y defines the translation on Y axis
  8413. * @param z defines the translationon Z axis
  8414. * @returns the new matrix
  8415. */
  8416. Matrix.Translation = function (x, y, z) {
  8417. var result = Matrix.Identity();
  8418. Matrix.TranslationToRef(x, y, z, result);
  8419. return result;
  8420. };
  8421. /**
  8422. * Creates a translation matrix and stores it in a given matrix
  8423. * @param x defines the translation on X axis
  8424. * @param y defines the translation on Y axis
  8425. * @param z defines the translationon Z axis
  8426. * @param result defines the target matrix
  8427. */
  8428. Matrix.TranslationToRef = function (x, y, z, result) {
  8429. 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);
  8430. };
  8431. /**
  8432. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8433. * @param startValue defines the start value
  8434. * @param endValue defines the end value
  8435. * @param gradient defines the gradient factor
  8436. * @returns the new matrix
  8437. */
  8438. Matrix.Lerp = function (startValue, endValue, gradient) {
  8439. var result = Matrix.Zero();
  8440. Matrix.LerpToRef(startValue, endValue, gradient, result);
  8441. return result;
  8442. };
  8443. /**
  8444. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8445. * @param startValue defines the start value
  8446. * @param endValue defines the end value
  8447. * @param gradient defines the gradient factor
  8448. * @param result defines the Matrix object where to store data
  8449. */
  8450. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  8451. for (var index = 0; index < 16; index++) {
  8452. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  8453. }
  8454. result._markAsUpdated();
  8455. };
  8456. /**
  8457. * Builds a new matrix whose values are computed by:
  8458. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8459. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8460. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8461. * @param startValue defines the first matrix
  8462. * @param endValue defines the second matrix
  8463. * @param gradient defines the gradient between the two matrices
  8464. * @returns the new matrix
  8465. */
  8466. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  8467. var result = Matrix.Zero();
  8468. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  8469. return result;
  8470. };
  8471. /**
  8472. * Update a matrix to values which are computed by:
  8473. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8474. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8475. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8476. * @param startValue defines the first matrix
  8477. * @param endValue defines the second matrix
  8478. * @param gradient defines the gradient between the two matrices
  8479. * @param result defines the target matrix
  8480. */
  8481. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  8482. var startScale = MathTmp.Vector3[0];
  8483. var startRotation = MathTmp.Quaternion[0];
  8484. var startTranslation = MathTmp.Vector3[1];
  8485. startValue.decompose(startScale, startRotation, startTranslation);
  8486. var endScale = MathTmp.Vector3[2];
  8487. var endRotation = MathTmp.Quaternion[1];
  8488. var endTranslation = MathTmp.Vector3[3];
  8489. endValue.decompose(endScale, endRotation, endTranslation);
  8490. var resultScale = MathTmp.Vector3[4];
  8491. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  8492. var resultRotation = MathTmp.Quaternion[2];
  8493. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  8494. var resultTranslation = MathTmp.Vector3[5];
  8495. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  8496. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  8497. };
  8498. /**
  8499. * 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"
  8500. * This function works in left handed mode
  8501. * @param eye defines the final position of the entity
  8502. * @param target defines where the entity should look at
  8503. * @param up defines the up vector for the entity
  8504. * @returns the new matrix
  8505. */
  8506. Matrix.LookAtLH = function (eye, target, up) {
  8507. var result = Matrix.Zero();
  8508. Matrix.LookAtLHToRef(eye, target, up, result);
  8509. return result;
  8510. };
  8511. /**
  8512. * 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".
  8513. * This function works in left handed mode
  8514. * @param eye defines the final position of the entity
  8515. * @param target defines where the entity should look at
  8516. * @param up defines the up vector for the entity
  8517. * @param result defines the target matrix
  8518. */
  8519. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  8520. // Z axis
  8521. target.subtractToRef(eye, this._zAxis);
  8522. this._zAxis.normalize();
  8523. // X axis
  8524. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  8525. if (this._xAxis.lengthSquared() === 0) {
  8526. this._xAxis.x = 1.0;
  8527. }
  8528. else {
  8529. this._xAxis.normalize();
  8530. }
  8531. // Y axis
  8532. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  8533. this._yAxis.normalize();
  8534. // Eye angles
  8535. var ex = -Vector3.Dot(this._xAxis, eye);
  8536. var ey = -Vector3.Dot(this._yAxis, eye);
  8537. var ez = -Vector3.Dot(this._zAxis, eye);
  8538. 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);
  8539. };
  8540. /**
  8541. * 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"
  8542. * This function works in right handed mode
  8543. * @param eye defines the final position of the entity
  8544. * @param target defines where the entity should look at
  8545. * @param up defines the up vector for the entity
  8546. * @returns the new matrix
  8547. */
  8548. Matrix.LookAtRH = function (eye, target, up) {
  8549. var result = Matrix.Zero();
  8550. Matrix.LookAtRHToRef(eye, target, up, result);
  8551. return result;
  8552. };
  8553. /**
  8554. * 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".
  8555. * This function works in right handed mode
  8556. * @param eye defines the final position of the entity
  8557. * @param target defines where the entity should look at
  8558. * @param up defines the up vector for the entity
  8559. * @param result defines the target matrix
  8560. */
  8561. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  8562. // Z axis
  8563. eye.subtractToRef(target, this._zAxis);
  8564. this._zAxis.normalize();
  8565. // X axis
  8566. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  8567. if (this._xAxis.lengthSquared() === 0) {
  8568. this._xAxis.x = 1.0;
  8569. }
  8570. else {
  8571. this._xAxis.normalize();
  8572. }
  8573. // Y axis
  8574. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  8575. this._yAxis.normalize();
  8576. // Eye angles
  8577. var ex = -Vector3.Dot(this._xAxis, eye);
  8578. var ey = -Vector3.Dot(this._yAxis, eye);
  8579. var ez = -Vector3.Dot(this._zAxis, eye);
  8580. 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);
  8581. };
  8582. /**
  8583. * Create a left-handed orthographic projection matrix
  8584. * @param width defines the viewport width
  8585. * @param height defines the viewport height
  8586. * @param znear defines the near clip plane
  8587. * @param zfar defines the far clip plane
  8588. * @returns a new matrix as a left-handed orthographic projection matrix
  8589. */
  8590. Matrix.OrthoLH = function (width, height, znear, zfar) {
  8591. var matrix = Matrix.Zero();
  8592. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  8593. return matrix;
  8594. };
  8595. /**
  8596. * Store a left-handed orthographic projection to a given matrix
  8597. * @param width defines the viewport width
  8598. * @param height defines the viewport height
  8599. * @param znear defines the near clip plane
  8600. * @param zfar defines the far clip plane
  8601. * @param result defines the target matrix
  8602. */
  8603. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  8604. var n = znear;
  8605. var f = zfar;
  8606. var a = 2.0 / width;
  8607. var b = 2.0 / height;
  8608. var c = 2.0 / (f - n);
  8609. var d = -(f + n) / (f - n);
  8610. 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);
  8611. };
  8612. /**
  8613. * Create a left-handed orthographic projection matrix
  8614. * @param left defines the viewport left coordinate
  8615. * @param right defines the viewport right coordinate
  8616. * @param bottom defines the viewport bottom coordinate
  8617. * @param top defines the viewport top coordinate
  8618. * @param znear defines the near clip plane
  8619. * @param zfar defines the far clip plane
  8620. * @returns a new matrix as a left-handed orthographic projection matrix
  8621. */
  8622. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  8623. var matrix = Matrix.Zero();
  8624. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  8625. return matrix;
  8626. };
  8627. /**
  8628. * Stores a left-handed orthographic projection into a given matrix
  8629. * @param left defines the viewport left coordinate
  8630. * @param right defines the viewport right coordinate
  8631. * @param bottom defines the viewport bottom coordinate
  8632. * @param top defines the viewport top coordinate
  8633. * @param znear defines the near clip plane
  8634. * @param zfar defines the far clip plane
  8635. * @param result defines the target matrix
  8636. */
  8637. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8638. var n = znear;
  8639. var f = zfar;
  8640. var a = 2.0 / (right - left);
  8641. var b = 2.0 / (top - bottom);
  8642. var c = 2.0 / (f - n);
  8643. var d = -(f + n) / (f - n);
  8644. var i0 = (left + right) / (left - right);
  8645. var i1 = (top + bottom) / (bottom - top);
  8646. 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);
  8647. };
  8648. /**
  8649. * Creates a right-handed orthographic projection matrix
  8650. * @param left defines the viewport left coordinate
  8651. * @param right defines the viewport right coordinate
  8652. * @param bottom defines the viewport bottom coordinate
  8653. * @param top defines the viewport top coordinate
  8654. * @param znear defines the near clip plane
  8655. * @param zfar defines the far clip plane
  8656. * @returns a new matrix as a right-handed orthographic projection matrix
  8657. */
  8658. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  8659. var matrix = Matrix.Zero();
  8660. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  8661. return matrix;
  8662. };
  8663. /**
  8664. * Stores a right-handed orthographic projection into a given matrix
  8665. * @param left defines the viewport left coordinate
  8666. * @param right defines the viewport right coordinate
  8667. * @param bottom defines the viewport bottom coordinate
  8668. * @param top defines the viewport top coordinate
  8669. * @param znear defines the near clip plane
  8670. * @param zfar defines the far clip plane
  8671. * @param result defines the target matrix
  8672. */
  8673. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8674. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  8675. result.m[10] *= -1.0;
  8676. };
  8677. /**
  8678. * Creates a left-handed perspective projection matrix
  8679. * @param width defines the viewport width
  8680. * @param height defines the viewport height
  8681. * @param znear defines the near clip plane
  8682. * @param zfar defines the far clip plane
  8683. * @returns a new matrix as a left-handed perspective projection matrix
  8684. */
  8685. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  8686. var matrix = Matrix.Zero();
  8687. var n = znear;
  8688. var f = zfar;
  8689. var a = 2.0 * n / width;
  8690. var b = 2.0 * n / height;
  8691. var c = (f + n) / (f - n);
  8692. var d = -2.0 * f * n / (f - n);
  8693. 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);
  8694. return matrix;
  8695. };
  8696. /**
  8697. * Creates a left-handed perspective projection matrix
  8698. * @param fov defines the horizontal field of view
  8699. * @param aspect defines the aspect ratio
  8700. * @param znear defines the near clip plane
  8701. * @param zfar defines the far clip plane
  8702. * @returns a new matrix as a left-handed perspective projection matrix
  8703. */
  8704. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  8705. var matrix = Matrix.Zero();
  8706. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  8707. return matrix;
  8708. };
  8709. /**
  8710. * Stores a left-handed perspective projection into a given matrix
  8711. * @param fov defines the horizontal field of view
  8712. * @param aspect defines the aspect ratio
  8713. * @param znear defines the near clip plane
  8714. * @param zfar defines the far clip plane
  8715. * @param result defines the target matrix
  8716. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8717. */
  8718. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8719. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8720. var n = znear;
  8721. var f = zfar;
  8722. var t = 1.0 / (Math.tan(fov * 0.5));
  8723. var a = isVerticalFovFixed ? (t / aspect) : t;
  8724. var b = isVerticalFovFixed ? t : (t * aspect);
  8725. var c = (f + n) / (f - n);
  8726. var d = -2.0 * f * n / (f - n);
  8727. 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);
  8728. };
  8729. /**
  8730. * Creates a right-handed perspective projection matrix
  8731. * @param fov defines the horizontal field of view
  8732. * @param aspect defines the aspect ratio
  8733. * @param znear defines the near clip plane
  8734. * @param zfar defines the far clip plane
  8735. * @returns a new matrix as a right-handed perspective projection matrix
  8736. */
  8737. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  8738. var matrix = Matrix.Zero();
  8739. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  8740. return matrix;
  8741. };
  8742. /**
  8743. * Stores a right-handed perspective projection into a given matrix
  8744. * @param fov defines the horizontal field of view
  8745. * @param aspect defines the aspect ratio
  8746. * @param znear defines the near clip plane
  8747. * @param zfar defines the far clip plane
  8748. * @param result defines the target matrix
  8749. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8750. */
  8751. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8752. //alternatively this could be expressed as:
  8753. // m = PerspectiveFovLHToRef
  8754. // m[10] *= -1.0;
  8755. // m[11] *= -1.0;
  8756. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8757. var n = znear;
  8758. var f = zfar;
  8759. var t = 1.0 / (Math.tan(fov * 0.5));
  8760. var a = isVerticalFovFixed ? (t / aspect) : t;
  8761. var b = isVerticalFovFixed ? t : (t * aspect);
  8762. var c = -(f + n) / (f - n);
  8763. var d = -2 * f * n / (f - n);
  8764. 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);
  8765. };
  8766. /**
  8767. * Stores a perspective projection for WebVR info a given matrix
  8768. * @param fov defines the field of view
  8769. * @param znear defines the near clip plane
  8770. * @param zfar defines the far clip plane
  8771. * @param result defines the target matrix
  8772. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  8773. */
  8774. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  8775. if (rightHanded === void 0) { rightHanded = false; }
  8776. var rightHandedFactor = rightHanded ? -1 : 1;
  8777. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  8778. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  8779. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  8780. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  8781. var xScale = 2.0 / (leftTan + rightTan);
  8782. var yScale = 2.0 / (upTan + downTan);
  8783. result.m[0] = xScale;
  8784. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  8785. result.m[5] = yScale;
  8786. result.m[6] = result.m[7] = 0.0;
  8787. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  8788. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  8789. result.m[10] = -zfar / (znear - zfar);
  8790. result.m[11] = 1.0 * rightHandedFactor;
  8791. result.m[12] = result.m[13] = result.m[15] = 0.0;
  8792. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  8793. result._markAsUpdated();
  8794. };
  8795. /**
  8796. * Computes a complete transformation matrix
  8797. * @param viewport defines the viewport to use
  8798. * @param world defines the world matrix
  8799. * @param view defines the view matrix
  8800. * @param projection defines the projection matrix
  8801. * @param zmin defines the near clip plane
  8802. * @param zmax defines the far clip plane
  8803. * @returns the transformation matrix
  8804. */
  8805. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  8806. var cw = viewport.width;
  8807. var ch = viewport.height;
  8808. var cx = viewport.x;
  8809. var cy = viewport.y;
  8810. 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);
  8811. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  8812. };
  8813. /**
  8814. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  8815. * @param matrix defines the matrix to use
  8816. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  8817. */
  8818. Matrix.GetAsMatrix2x2 = function (matrix) {
  8819. return new Float32Array([
  8820. matrix.m[0], matrix.m[1],
  8821. matrix.m[4], matrix.m[5]
  8822. ]);
  8823. };
  8824. /**
  8825. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  8826. * @param matrix defines the matrix to use
  8827. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  8828. */
  8829. Matrix.GetAsMatrix3x3 = function (matrix) {
  8830. return new Float32Array([
  8831. matrix.m[0], matrix.m[1], matrix.m[2],
  8832. matrix.m[4], matrix.m[5], matrix.m[6],
  8833. matrix.m[8], matrix.m[9], matrix.m[10]
  8834. ]);
  8835. };
  8836. /**
  8837. * Compute the transpose of a given matrix
  8838. * @param matrix defines the matrix to transpose
  8839. * @returns the new matrix
  8840. */
  8841. Matrix.Transpose = function (matrix) {
  8842. var result = new Matrix();
  8843. Matrix.TransposeToRef(matrix, result);
  8844. return result;
  8845. };
  8846. /**
  8847. * Compute the transpose of a matrix and store it in a target matrix
  8848. * @param matrix defines the matrix to transpose
  8849. * @param result defines the target matrix
  8850. */
  8851. Matrix.TransposeToRef = function (matrix, result) {
  8852. result.m[0] = matrix.m[0];
  8853. result.m[1] = matrix.m[4];
  8854. result.m[2] = matrix.m[8];
  8855. result.m[3] = matrix.m[12];
  8856. result.m[4] = matrix.m[1];
  8857. result.m[5] = matrix.m[5];
  8858. result.m[6] = matrix.m[9];
  8859. result.m[7] = matrix.m[13];
  8860. result.m[8] = matrix.m[2];
  8861. result.m[9] = matrix.m[6];
  8862. result.m[10] = matrix.m[10];
  8863. result.m[11] = matrix.m[14];
  8864. result.m[12] = matrix.m[3];
  8865. result.m[13] = matrix.m[7];
  8866. result.m[14] = matrix.m[11];
  8867. result.m[15] = matrix.m[15];
  8868. };
  8869. /**
  8870. * Computes a reflection matrix from a plane
  8871. * @param plane defines the reflection plane
  8872. * @returns a new matrix
  8873. */
  8874. Matrix.Reflection = function (plane) {
  8875. var matrix = new Matrix();
  8876. Matrix.ReflectionToRef(plane, matrix);
  8877. return matrix;
  8878. };
  8879. /**
  8880. * Computes a reflection matrix from a plane
  8881. * @param plane defines the reflection plane
  8882. * @param result defines the target matrix
  8883. */
  8884. Matrix.ReflectionToRef = function (plane, result) {
  8885. plane.normalize();
  8886. var x = plane.normal.x;
  8887. var y = plane.normal.y;
  8888. var z = plane.normal.z;
  8889. var temp = -2 * x;
  8890. var temp2 = -2 * y;
  8891. var temp3 = -2 * z;
  8892. result.m[0] = (temp * x) + 1;
  8893. result.m[1] = temp2 * x;
  8894. result.m[2] = temp3 * x;
  8895. result.m[3] = 0.0;
  8896. result.m[4] = temp * y;
  8897. result.m[5] = (temp2 * y) + 1;
  8898. result.m[6] = temp3 * y;
  8899. result.m[7] = 0.0;
  8900. result.m[8] = temp * z;
  8901. result.m[9] = temp2 * z;
  8902. result.m[10] = (temp3 * z) + 1;
  8903. result.m[11] = 0.0;
  8904. result.m[12] = temp * plane.d;
  8905. result.m[13] = temp2 * plane.d;
  8906. result.m[14] = temp3 * plane.d;
  8907. result.m[15] = 1.0;
  8908. result._markAsUpdated();
  8909. };
  8910. /**
  8911. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  8912. * @param xaxis defines the value of the 1st axis
  8913. * @param yaxis defines the value of the 2nd axis
  8914. * @param zaxis defines the value of the 3rd axis
  8915. * @param result defines the target matrix
  8916. */
  8917. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  8918. result.m[0] = xaxis.x;
  8919. result.m[1] = xaxis.y;
  8920. result.m[2] = xaxis.z;
  8921. result.m[3] = 0.0;
  8922. result.m[4] = yaxis.x;
  8923. result.m[5] = yaxis.y;
  8924. result.m[6] = yaxis.z;
  8925. result.m[7] = 0.0;
  8926. result.m[8] = zaxis.x;
  8927. result.m[9] = zaxis.y;
  8928. result.m[10] = zaxis.z;
  8929. result.m[11] = 0.0;
  8930. result.m[12] = 0.0;
  8931. result.m[13] = 0.0;
  8932. result.m[14] = 0.0;
  8933. result.m[15] = 1.0;
  8934. result._markAsUpdated();
  8935. };
  8936. /**
  8937. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  8938. * @param quat defines the quaternion to use
  8939. * @param result defines the target matrix
  8940. */
  8941. Matrix.FromQuaternionToRef = function (quat, result) {
  8942. var xx = quat.x * quat.x;
  8943. var yy = quat.y * quat.y;
  8944. var zz = quat.z * quat.z;
  8945. var xy = quat.x * quat.y;
  8946. var zw = quat.z * quat.w;
  8947. var zx = quat.z * quat.x;
  8948. var yw = quat.y * quat.w;
  8949. var yz = quat.y * quat.z;
  8950. var xw = quat.x * quat.w;
  8951. result.m[0] = 1.0 - (2.0 * (yy + zz));
  8952. result.m[1] = 2.0 * (xy + zw);
  8953. result.m[2] = 2.0 * (zx - yw);
  8954. result.m[3] = 0.0;
  8955. result.m[4] = 2.0 * (xy - zw);
  8956. result.m[5] = 1.0 - (2.0 * (zz + xx));
  8957. result.m[6] = 2.0 * (yz + xw);
  8958. result.m[7] = 0.0;
  8959. result.m[8] = 2.0 * (zx + yw);
  8960. result.m[9] = 2.0 * (yz - xw);
  8961. result.m[10] = 1.0 - (2.0 * (yy + xx));
  8962. result.m[11] = 0.0;
  8963. result.m[12] = 0.0;
  8964. result.m[13] = 0.0;
  8965. result.m[14] = 0.0;
  8966. result.m[15] = 1.0;
  8967. result._markAsUpdated();
  8968. };
  8969. Matrix._tempQuaternion = new Quaternion();
  8970. Matrix._xAxis = Vector3.Zero();
  8971. Matrix._yAxis = Vector3.Zero();
  8972. Matrix._zAxis = Vector3.Zero();
  8973. Matrix._updateFlagSeed = 0;
  8974. Matrix._identityReadOnly = Matrix.Identity();
  8975. return Matrix;
  8976. }());
  8977. BABYLON.Matrix = Matrix;
  8978. /**
  8979. * Represens a plane by the equation ax + by + cz + d = 0
  8980. */
  8981. var Plane = /** @class */ (function () {
  8982. /**
  8983. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  8984. * @param a a component of the plane
  8985. * @param b b component of the plane
  8986. * @param c c component of the plane
  8987. * @param d d component of the plane
  8988. */
  8989. function Plane(a, b, c, d) {
  8990. this.normal = new Vector3(a, b, c);
  8991. this.d = d;
  8992. }
  8993. /**
  8994. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  8995. */
  8996. Plane.prototype.asArray = function () {
  8997. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  8998. };
  8999. // Methods
  9000. /**
  9001. * @returns a new plane copied from the current Plane.
  9002. */
  9003. Plane.prototype.clone = function () {
  9004. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  9005. };
  9006. /**
  9007. * @returns the string "Plane".
  9008. */
  9009. Plane.prototype.getClassName = function () {
  9010. return "Plane";
  9011. };
  9012. /**
  9013. * @returns the Plane hash code.
  9014. */
  9015. Plane.prototype.getHashCode = function () {
  9016. var hash = this.normal.getHashCode();
  9017. hash = (hash * 397) ^ (this.d || 0);
  9018. return hash;
  9019. };
  9020. /**
  9021. * Normalize the current Plane in place.
  9022. * @returns the updated Plane.
  9023. */
  9024. Plane.prototype.normalize = function () {
  9025. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  9026. var magnitude = 0.0;
  9027. if (norm !== 0) {
  9028. magnitude = 1.0 / norm;
  9029. }
  9030. this.normal.x *= magnitude;
  9031. this.normal.y *= magnitude;
  9032. this.normal.z *= magnitude;
  9033. this.d *= magnitude;
  9034. return this;
  9035. };
  9036. /**
  9037. * Applies a transformation the plane and returns the result
  9038. * @param transformation the transformation matrix to be applied to the plane
  9039. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  9040. */
  9041. Plane.prototype.transform = function (transformation) {
  9042. var transposedMatrix = Matrix.Transpose(transformation);
  9043. var x = this.normal.x;
  9044. var y = this.normal.y;
  9045. var z = this.normal.z;
  9046. var d = this.d;
  9047. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  9048. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  9049. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  9050. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  9051. return new Plane(normalX, normalY, normalZ, finalD);
  9052. };
  9053. /**
  9054. * Calcualtte the dot product between the point and the plane normal
  9055. * @param point point to calculate the dot product with
  9056. * @returns the dot product (float) of the point coordinates and the plane normal.
  9057. */
  9058. Plane.prototype.dotCoordinate = function (point) {
  9059. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  9060. };
  9061. /**
  9062. * Updates the current Plane from the plane defined by the three given points.
  9063. * @param point1 one of the points used to contruct the plane
  9064. * @param point2 one of the points used to contruct the plane
  9065. * @param point3 one of the points used to contruct the plane
  9066. * @returns the updated Plane.
  9067. */
  9068. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  9069. var x1 = point2.x - point1.x;
  9070. var y1 = point2.y - point1.y;
  9071. var z1 = point2.z - point1.z;
  9072. var x2 = point3.x - point1.x;
  9073. var y2 = point3.y - point1.y;
  9074. var z2 = point3.z - point1.z;
  9075. var yz = (y1 * z2) - (z1 * y2);
  9076. var xz = (z1 * x2) - (x1 * z2);
  9077. var xy = (x1 * y2) - (y1 * x2);
  9078. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9079. var invPyth;
  9080. if (pyth !== 0) {
  9081. invPyth = 1.0 / pyth;
  9082. }
  9083. else {
  9084. invPyth = 0.0;
  9085. }
  9086. this.normal.x = yz * invPyth;
  9087. this.normal.y = xz * invPyth;
  9088. this.normal.z = xy * invPyth;
  9089. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  9090. return this;
  9091. };
  9092. /**
  9093. * Checks if the plane is facing a given direction
  9094. * @param direction the direction to check if the plane is facing
  9095. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  9096. * @returns True is the vector "direction" is the same side than the plane normal.
  9097. */
  9098. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  9099. var dot = Vector3.Dot(this.normal, direction);
  9100. return (dot <= epsilon);
  9101. };
  9102. /**
  9103. * Calculates the distance to a point
  9104. * @param point point to calculate distance to
  9105. * @returns the signed distance (float) from the given point to the Plane.
  9106. */
  9107. Plane.prototype.signedDistanceTo = function (point) {
  9108. return Vector3.Dot(point, this.normal) + this.d;
  9109. };
  9110. // Statics
  9111. /**
  9112. * Creates a plane from an array
  9113. * @param array the array to create a plane from
  9114. * @returns a new Plane from the given array.
  9115. */
  9116. Plane.FromArray = function (array) {
  9117. return new Plane(array[0], array[1], array[2], array[3]);
  9118. };
  9119. /**
  9120. * Creates a plane from three points
  9121. * @param point1 point used to create the plane
  9122. * @param point2 point used to create the plane
  9123. * @param point3 point used to create the plane
  9124. * @returns a new Plane defined by the three given points.
  9125. */
  9126. Plane.FromPoints = function (point1, point2, point3) {
  9127. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9128. result.copyFromPoints(point1, point2, point3);
  9129. return result;
  9130. };
  9131. /**
  9132. * Creates a plane from an origin point and a normal
  9133. * @param origin origin of the plane to be constructed
  9134. * @param normal normal of the plane to be constructed
  9135. * @returns a new Plane the normal vector to this plane at the given origin point.
  9136. * Note : the vector "normal" is updated because normalized.
  9137. */
  9138. Plane.FromPositionAndNormal = function (origin, normal) {
  9139. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9140. normal.normalize();
  9141. result.normal = normal;
  9142. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9143. return result;
  9144. };
  9145. /**
  9146. * Calculates the distance from a plane and a point
  9147. * @param origin origin of the plane to be constructed
  9148. * @param normal normal of the plane to be constructed
  9149. * @param point point to calculate distance to
  9150. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  9151. */
  9152. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  9153. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9154. return Vector3.Dot(point, normal) + d;
  9155. };
  9156. return Plane;
  9157. }());
  9158. BABYLON.Plane = Plane;
  9159. /**
  9160. * Class used to represent a viewport on screen
  9161. */
  9162. var Viewport = /** @class */ (function () {
  9163. /**
  9164. * Creates a Viewport object located at (x, y) and sized (width, height)
  9165. * @param x defines viewport left coordinate
  9166. * @param y defines viewport top coordinate
  9167. * @param width defines the viewport width
  9168. * @param height defines the viewport height
  9169. */
  9170. function Viewport(
  9171. /** viewport left coordinate */
  9172. x,
  9173. /** viewport top coordinate */
  9174. y,
  9175. /**viewport width */
  9176. width,
  9177. /** viewport height */
  9178. height) {
  9179. this.x = x;
  9180. this.y = y;
  9181. this.width = width;
  9182. this.height = height;
  9183. }
  9184. /**
  9185. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  9186. * @param renderWidthOrEngine defines either an engine or the rendering width
  9187. * @param renderHeight defines the rendering height
  9188. * @returns a new Viewport
  9189. */
  9190. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  9191. if (renderWidthOrEngine.getRenderWidth) {
  9192. var engine = renderWidthOrEngine;
  9193. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  9194. }
  9195. var renderWidth = renderWidthOrEngine;
  9196. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  9197. };
  9198. /**
  9199. * Returns a new Viewport copied from the current one
  9200. * @returns a new Viewport
  9201. */
  9202. Viewport.prototype.clone = function () {
  9203. return new Viewport(this.x, this.y, this.width, this.height);
  9204. };
  9205. return Viewport;
  9206. }());
  9207. BABYLON.Viewport = Viewport;
  9208. /**
  9209. * Reprasents a camera frustum
  9210. */
  9211. var Frustum = /** @class */ (function () {
  9212. function Frustum() {
  9213. }
  9214. /**
  9215. * Gets the planes representing the frustum
  9216. * @param transform matrix to be applied to the returned planes
  9217. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  9218. */
  9219. Frustum.GetPlanes = function (transform) {
  9220. var frustumPlanes = [];
  9221. for (var index = 0; index < 6; index++) {
  9222. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  9223. }
  9224. Frustum.GetPlanesToRef(transform, frustumPlanes);
  9225. return frustumPlanes;
  9226. };
  9227. /**
  9228. * Gets the near frustum plane transformed by the transform matrix
  9229. * @param transform transformation matrix to be applied to the resulting frustum plane
  9230. * @param frustumPlane the resuling frustum plane
  9231. */
  9232. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  9233. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  9234. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  9235. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  9236. frustumPlane.d = transform.m[15] + transform.m[14];
  9237. frustumPlane.normalize();
  9238. };
  9239. /**
  9240. * Gets the far frustum plane transformed by the transform matrix
  9241. * @param transform transformation matrix to be applied to the resulting frustum plane
  9242. * @param frustumPlane the resuling frustum plane
  9243. */
  9244. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  9245. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  9246. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  9247. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  9248. frustumPlane.d = transform.m[15] - transform.m[14];
  9249. frustumPlane.normalize();
  9250. };
  9251. /**
  9252. * Gets the left frustum plane transformed by the transform matrix
  9253. * @param transform transformation matrix to be applied to the resulting frustum plane
  9254. * @param frustumPlane the resuling frustum plane
  9255. */
  9256. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  9257. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  9258. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  9259. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  9260. frustumPlane.d = transform.m[15] + transform.m[12];
  9261. frustumPlane.normalize();
  9262. };
  9263. /**
  9264. * Gets the right frustum plane transformed by the transform matrix
  9265. * @param transform transformation matrix to be applied to the resulting frustum plane
  9266. * @param frustumPlane the resuling frustum plane
  9267. */
  9268. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  9269. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  9270. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  9271. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  9272. frustumPlane.d = transform.m[15] - transform.m[12];
  9273. frustumPlane.normalize();
  9274. };
  9275. /**
  9276. * Gets the top frustum plane transformed by the transform matrix
  9277. * @param transform transformation matrix to be applied to the resulting frustum plane
  9278. * @param frustumPlane the resuling frustum plane
  9279. */
  9280. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  9281. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  9282. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  9283. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  9284. frustumPlane.d = transform.m[15] - transform.m[13];
  9285. frustumPlane.normalize();
  9286. };
  9287. /**
  9288. * Gets the bottom frustum plane transformed by the transform matrix
  9289. * @param transform transformation matrix to be applied to the resulting frustum plane
  9290. * @param frustumPlane the resuling frustum plane
  9291. */
  9292. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  9293. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  9294. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  9295. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  9296. frustumPlane.d = transform.m[15] + transform.m[13];
  9297. frustumPlane.normalize();
  9298. };
  9299. /**
  9300. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  9301. * @param transform transformation matrix to be applied to the resulting frustum planes
  9302. * @param frustumPlanes the resuling frustum planes
  9303. */
  9304. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  9305. // Near
  9306. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  9307. // Far
  9308. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  9309. // Left
  9310. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  9311. // Right
  9312. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  9313. // Top
  9314. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  9315. // Bottom
  9316. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  9317. };
  9318. return Frustum;
  9319. }());
  9320. BABYLON.Frustum = Frustum;
  9321. /** Defines supported spaces */
  9322. var Space;
  9323. (function (Space) {
  9324. /** Local (object) space */
  9325. Space[Space["LOCAL"] = 0] = "LOCAL";
  9326. /** World space */
  9327. Space[Space["WORLD"] = 1] = "WORLD";
  9328. /** Bone space */
  9329. Space[Space["BONE"] = 2] = "BONE";
  9330. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  9331. /** Defines the 3 main axes */
  9332. var Axis = /** @class */ (function () {
  9333. function Axis() {
  9334. }
  9335. /** X axis */
  9336. Axis.X = new Vector3(1.0, 0.0, 0.0);
  9337. /** Y axis */
  9338. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  9339. /** Z axis */
  9340. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  9341. return Axis;
  9342. }());
  9343. BABYLON.Axis = Axis;
  9344. /** Class used to represent a Bezier curve */
  9345. var BezierCurve = /** @class */ (function () {
  9346. function BezierCurve() {
  9347. }
  9348. /**
  9349. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  9350. * @param t defines the time
  9351. * @param x1 defines the left coordinate on X axis
  9352. * @param y1 defines the left coordinate on Y axis
  9353. * @param x2 defines the right coordinate on X axis
  9354. * @param y2 defines the right coordinate on Y axis
  9355. * @returns the interpolated value
  9356. */
  9357. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  9358. // Extract X (which is equal to time here)
  9359. var f0 = 1 - 3 * x2 + 3 * x1;
  9360. var f1 = 3 * x2 - 6 * x1;
  9361. var f2 = 3 * x1;
  9362. var refinedT = t;
  9363. for (var i = 0; i < 5; i++) {
  9364. var refinedT2 = refinedT * refinedT;
  9365. var refinedT3 = refinedT2 * refinedT;
  9366. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  9367. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  9368. refinedT -= (x - t) * slope;
  9369. refinedT = Math.min(1, Math.max(0, refinedT));
  9370. }
  9371. // Resolve cubic bezier for the given x
  9372. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  9373. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  9374. Math.pow(refinedT, 3);
  9375. };
  9376. return BezierCurve;
  9377. }());
  9378. BABYLON.BezierCurve = BezierCurve;
  9379. /**
  9380. * Defines potential orientation for back face culling
  9381. */
  9382. var Orientation;
  9383. (function (Orientation) {
  9384. /**
  9385. * Clockwise
  9386. */
  9387. Orientation[Orientation["CW"] = 0] = "CW";
  9388. /** Counter clockwise */
  9389. Orientation[Orientation["CCW"] = 1] = "CCW";
  9390. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  9391. /**
  9392. * Defines angle representation
  9393. */
  9394. var Angle = /** @class */ (function () {
  9395. /**
  9396. * Creates an Angle object of "radians" radians (float).
  9397. */
  9398. function Angle(radians) {
  9399. this._radians = radians;
  9400. if (this._radians < 0.0) {
  9401. this._radians += (2.0 * Math.PI);
  9402. }
  9403. }
  9404. /**
  9405. * Get value in degrees
  9406. * @returns the Angle value in degrees (float)
  9407. */
  9408. Angle.prototype.degrees = function () {
  9409. return this._radians * 180.0 / Math.PI;
  9410. };
  9411. /**
  9412. * Get value in radians
  9413. * @returns the Angle value in radians (float)
  9414. */
  9415. Angle.prototype.radians = function () {
  9416. return this._radians;
  9417. };
  9418. /**
  9419. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  9420. * @param a defines first vector
  9421. * @param b defines second vector
  9422. * @returns a new Angle
  9423. */
  9424. Angle.BetweenTwoPoints = function (a, b) {
  9425. var delta = b.subtract(a);
  9426. var theta = Math.atan2(delta.y, delta.x);
  9427. return new Angle(theta);
  9428. };
  9429. /**
  9430. * Gets a new Angle object from the given float in radians
  9431. * @param radians defines the angle value in radians
  9432. * @returns a new Angle
  9433. */
  9434. Angle.FromRadians = function (radians) {
  9435. return new Angle(radians);
  9436. };
  9437. /**
  9438. * Gets a new Angle object from the given float in degrees
  9439. * @param degrees defines the angle value in degrees
  9440. * @returns a new Angle
  9441. */
  9442. Angle.FromDegrees = function (degrees) {
  9443. return new Angle(degrees * Math.PI / 180.0);
  9444. };
  9445. return Angle;
  9446. }());
  9447. BABYLON.Angle = Angle;
  9448. /**
  9449. * This represents an arc in a 2d space.
  9450. */
  9451. var Arc2 = /** @class */ (function () {
  9452. /**
  9453. * Creates an Arc object from the three given points : start, middle and end.
  9454. * @param startPoint Defines the start point of the arc
  9455. * @param midPoint Defines the midlle point of the arc
  9456. * @param endPoint Defines the end point of the arc
  9457. */
  9458. function Arc2(
  9459. /** Defines the start point of the arc */
  9460. startPoint,
  9461. /** Defines the mid point of the arc */
  9462. midPoint,
  9463. /** Defines the end point of the arc */
  9464. endPoint) {
  9465. this.startPoint = startPoint;
  9466. this.midPoint = midPoint;
  9467. this.endPoint = endPoint;
  9468. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  9469. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  9470. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  9471. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  9472. 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);
  9473. this.radius = this.centerPoint.subtract(this.startPoint).length();
  9474. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  9475. var a1 = this.startAngle.degrees();
  9476. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  9477. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  9478. // angles correction
  9479. if (a2 - a1 > +180.0) {
  9480. a2 -= 360.0;
  9481. }
  9482. if (a2 - a1 < -180.0) {
  9483. a2 += 360.0;
  9484. }
  9485. if (a3 - a2 > +180.0) {
  9486. a3 -= 360.0;
  9487. }
  9488. if (a3 - a2 < -180.0) {
  9489. a3 += 360.0;
  9490. }
  9491. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  9492. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  9493. }
  9494. return Arc2;
  9495. }());
  9496. BABYLON.Arc2 = Arc2;
  9497. /**
  9498. * Represents a 2D path made up of multiple 2D points
  9499. */
  9500. var Path2 = /** @class */ (function () {
  9501. /**
  9502. * Creates a Path2 object from the starting 2D coordinates x and y.
  9503. * @param x the starting points x value
  9504. * @param y the starting points y value
  9505. */
  9506. function Path2(x, y) {
  9507. this._points = new Array();
  9508. this._length = 0.0;
  9509. /**
  9510. * If the path start and end point are the same
  9511. */
  9512. this.closed = false;
  9513. this._points.push(new Vector2(x, y));
  9514. }
  9515. /**
  9516. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  9517. * @param x the added points x value
  9518. * @param y the added points y value
  9519. * @returns the updated Path2.
  9520. */
  9521. Path2.prototype.addLineTo = function (x, y) {
  9522. if (this.closed) {
  9523. return this;
  9524. }
  9525. var newPoint = new Vector2(x, y);
  9526. var previousPoint = this._points[this._points.length - 1];
  9527. this._points.push(newPoint);
  9528. this._length += newPoint.subtract(previousPoint).length();
  9529. return this;
  9530. };
  9531. /**
  9532. * 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.
  9533. * @param midX middle point x value
  9534. * @param midY middle point y value
  9535. * @param endX end point x value
  9536. * @param endY end point y value
  9537. * @param numberOfSegments (default: 36)
  9538. * @returns the updated Path2.
  9539. */
  9540. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  9541. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  9542. if (this.closed) {
  9543. return this;
  9544. }
  9545. var startPoint = this._points[this._points.length - 1];
  9546. var midPoint = new Vector2(midX, midY);
  9547. var endPoint = new Vector2(endX, endY);
  9548. var arc = new Arc2(startPoint, midPoint, endPoint);
  9549. var increment = arc.angle.radians() / numberOfSegments;
  9550. if (arc.orientation === Orientation.CW) {
  9551. increment *= -1;
  9552. }
  9553. var currentAngle = arc.startAngle.radians() + increment;
  9554. for (var i = 0; i < numberOfSegments; i++) {
  9555. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  9556. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  9557. this.addLineTo(x, y);
  9558. currentAngle += increment;
  9559. }
  9560. return this;
  9561. };
  9562. /**
  9563. * Closes the Path2.
  9564. * @returns the Path2.
  9565. */
  9566. Path2.prototype.close = function () {
  9567. this.closed = true;
  9568. return this;
  9569. };
  9570. /**
  9571. * Gets the sum of the distance between each sequential point in the path
  9572. * @returns the Path2 total length (float).
  9573. */
  9574. Path2.prototype.length = function () {
  9575. var result = this._length;
  9576. if (!this.closed) {
  9577. var lastPoint = this._points[this._points.length - 1];
  9578. var firstPoint = this._points[0];
  9579. result += (firstPoint.subtract(lastPoint).length());
  9580. }
  9581. return result;
  9582. };
  9583. /**
  9584. * Gets the points which construct the path
  9585. * @returns the Path2 internal array of points.
  9586. */
  9587. Path2.prototype.getPoints = function () {
  9588. return this._points;
  9589. };
  9590. /**
  9591. * Retreives the point at the distance aways from the starting point
  9592. * @param normalizedLengthPosition the length along the path to retreive the point from
  9593. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  9594. */
  9595. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  9596. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  9597. return Vector2.Zero();
  9598. }
  9599. var lengthPosition = normalizedLengthPosition * this.length();
  9600. var previousOffset = 0;
  9601. for (var i = 0; i < this._points.length; i++) {
  9602. var j = (i + 1) % this._points.length;
  9603. var a = this._points[i];
  9604. var b = this._points[j];
  9605. var bToA = b.subtract(a);
  9606. var nextOffset = (bToA.length() + previousOffset);
  9607. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  9608. var dir = bToA.normalize();
  9609. var localOffset = lengthPosition - previousOffset;
  9610. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  9611. }
  9612. previousOffset = nextOffset;
  9613. }
  9614. return Vector2.Zero();
  9615. };
  9616. /**
  9617. * Creates a new path starting from an x and y position
  9618. * @param x starting x value
  9619. * @param y starting y value
  9620. * @returns a new Path2 starting at the coordinates (x, y).
  9621. */
  9622. Path2.StartingAt = function (x, y) {
  9623. return new Path2(x, y);
  9624. };
  9625. return Path2;
  9626. }());
  9627. BABYLON.Path2 = Path2;
  9628. /**
  9629. * Represents a 3D path made up of multiple 3D points
  9630. */
  9631. var Path3D = /** @class */ (function () {
  9632. /**
  9633. * new Path3D(path, normal, raw)
  9634. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  9635. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  9636. * @param path an array of Vector3, the curve axis of the Path3D
  9637. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  9638. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  9639. */
  9640. function Path3D(
  9641. /**
  9642. * an array of Vector3, the curve axis of the Path3D
  9643. */
  9644. path, firstNormal, raw) {
  9645. if (firstNormal === void 0) { firstNormal = null; }
  9646. this.path = path;
  9647. this._curve = new Array();
  9648. this._distances = new Array();
  9649. this._tangents = new Array();
  9650. this._normals = new Array();
  9651. this._binormals = new Array();
  9652. for (var p = 0; p < path.length; p++) {
  9653. this._curve[p] = path[p].clone(); // hard copy
  9654. }
  9655. this._raw = raw || false;
  9656. this._compute(firstNormal);
  9657. }
  9658. /**
  9659. * Returns the Path3D array of successive Vector3 designing its curve.
  9660. * @returns the Path3D array of successive Vector3 designing its curve.
  9661. */
  9662. Path3D.prototype.getCurve = function () {
  9663. return this._curve;
  9664. };
  9665. /**
  9666. * Returns an array populated with tangent vectors on each Path3D curve point.
  9667. * @returns an array populated with tangent vectors on each Path3D curve point.
  9668. */
  9669. Path3D.prototype.getTangents = function () {
  9670. return this._tangents;
  9671. };
  9672. /**
  9673. * Returns an array populated with normal vectors on each Path3D curve point.
  9674. * @returns an array populated with normal vectors on each Path3D curve point.
  9675. */
  9676. Path3D.prototype.getNormals = function () {
  9677. return this._normals;
  9678. };
  9679. /**
  9680. * Returns an array populated with binormal vectors on each Path3D curve point.
  9681. * @returns an array populated with binormal vectors on each Path3D curve point.
  9682. */
  9683. Path3D.prototype.getBinormals = function () {
  9684. return this._binormals;
  9685. };
  9686. /**
  9687. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  9688. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  9689. */
  9690. Path3D.prototype.getDistances = function () {
  9691. return this._distances;
  9692. };
  9693. /**
  9694. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  9695. * @param path path which all values are copied into the curves points
  9696. * @param firstNormal which should be projected onto the curve
  9697. * @returns the same object updated.
  9698. */
  9699. Path3D.prototype.update = function (path, firstNormal) {
  9700. if (firstNormal === void 0) { firstNormal = null; }
  9701. for (var p = 0; p < path.length; p++) {
  9702. this._curve[p].x = path[p].x;
  9703. this._curve[p].y = path[p].y;
  9704. this._curve[p].z = path[p].z;
  9705. }
  9706. this._compute(firstNormal);
  9707. return this;
  9708. };
  9709. // private function compute() : computes tangents, normals and binormals
  9710. Path3D.prototype._compute = function (firstNormal) {
  9711. var l = this._curve.length;
  9712. // first and last tangents
  9713. this._tangents[0] = this._getFirstNonNullVector(0);
  9714. if (!this._raw) {
  9715. this._tangents[0].normalize();
  9716. }
  9717. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  9718. if (!this._raw) {
  9719. this._tangents[l - 1].normalize();
  9720. }
  9721. // normals and binormals at first point : arbitrary vector with _normalVector()
  9722. var tg0 = this._tangents[0];
  9723. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  9724. this._normals[0] = pp0;
  9725. if (!this._raw) {
  9726. this._normals[0].normalize();
  9727. }
  9728. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  9729. if (!this._raw) {
  9730. this._binormals[0].normalize();
  9731. }
  9732. this._distances[0] = 0.0;
  9733. // normals and binormals : next points
  9734. var prev; // previous vector (segment)
  9735. var cur; // current vector (segment)
  9736. var curTang; // current tangent
  9737. // previous normal
  9738. var prevBinor; // previous binormal
  9739. for (var i = 1; i < l; i++) {
  9740. // tangents
  9741. prev = this._getLastNonNullVector(i);
  9742. if (i < l - 1) {
  9743. cur = this._getFirstNonNullVector(i);
  9744. this._tangents[i] = prev.add(cur);
  9745. this._tangents[i].normalize();
  9746. }
  9747. this._distances[i] = this._distances[i - 1] + prev.length();
  9748. // normals and binormals
  9749. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  9750. curTang = this._tangents[i];
  9751. prevBinor = this._binormals[i - 1];
  9752. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  9753. if (!this._raw) {
  9754. this._normals[i].normalize();
  9755. }
  9756. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  9757. if (!this._raw) {
  9758. this._binormals[i].normalize();
  9759. }
  9760. }
  9761. };
  9762. // private function getFirstNonNullVector(index)
  9763. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  9764. Path3D.prototype._getFirstNonNullVector = function (index) {
  9765. var i = 1;
  9766. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  9767. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  9768. i++;
  9769. nNVector = this._curve[index + i].subtract(this._curve[index]);
  9770. }
  9771. return nNVector;
  9772. };
  9773. // private function getLastNonNullVector(index)
  9774. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  9775. Path3D.prototype._getLastNonNullVector = function (index) {
  9776. var i = 1;
  9777. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  9778. while (nLVector.length() === 0 && index > i + 1) {
  9779. i++;
  9780. nLVector = this._curve[index].subtract(this._curve[index - i]);
  9781. }
  9782. return nLVector;
  9783. };
  9784. // private function normalVector(v0, vt, va) :
  9785. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  9786. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  9787. Path3D.prototype._normalVector = function (v0, vt, va) {
  9788. var normal0;
  9789. var tgl = vt.length();
  9790. if (tgl === 0.0) {
  9791. tgl = 1.0;
  9792. }
  9793. if (va === undefined || va === null) {
  9794. var point;
  9795. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  9796. point = new Vector3(0.0, -1.0, 0.0);
  9797. }
  9798. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  9799. point = new Vector3(1.0, 0.0, 0.0);
  9800. }
  9801. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  9802. point = new Vector3(0.0, 0.0, 1.0);
  9803. }
  9804. else {
  9805. point = Vector3.Zero();
  9806. }
  9807. normal0 = Vector3.Cross(vt, point);
  9808. }
  9809. else {
  9810. normal0 = Vector3.Cross(vt, va);
  9811. Vector3.CrossToRef(normal0, vt, normal0);
  9812. }
  9813. normal0.normalize();
  9814. return normal0;
  9815. };
  9816. return Path3D;
  9817. }());
  9818. BABYLON.Path3D = Path3D;
  9819. /**
  9820. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9821. * A Curve3 is designed from a series of successive Vector3.
  9822. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  9823. */
  9824. var Curve3 = /** @class */ (function () {
  9825. /**
  9826. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9827. * A Curve3 is designed from a series of successive Vector3.
  9828. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  9829. * @param points points which make up the curve
  9830. */
  9831. function Curve3(points) {
  9832. this._length = 0.0;
  9833. this._points = points;
  9834. this._length = this._computeLength(points);
  9835. }
  9836. /**
  9837. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  9838. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  9839. * @param v1 (Vector3) the control point
  9840. * @param v2 (Vector3) the end point of the Quadratic Bezier
  9841. * @param nbPoints (integer) the wanted number of points in the curve
  9842. * @returns the created Curve3
  9843. */
  9844. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  9845. nbPoints = nbPoints > 2 ? nbPoints : 3;
  9846. var bez = new Array();
  9847. var equation = function (t, val0, val1, val2) {
  9848. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  9849. return res;
  9850. };
  9851. for (var i = 0; i <= nbPoints; i++) {
  9852. 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)));
  9853. }
  9854. return new Curve3(bez);
  9855. };
  9856. /**
  9857. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  9858. * @param v0 (Vector3) the origin point of the Cubic Bezier
  9859. * @param v1 (Vector3) the first control point
  9860. * @param v2 (Vector3) the second control point
  9861. * @param v3 (Vector3) the end point of the Cubic Bezier
  9862. * @param nbPoints (integer) the wanted number of points in the curve
  9863. * @returns the created Curve3
  9864. */
  9865. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  9866. nbPoints = nbPoints > 3 ? nbPoints : 4;
  9867. var bez = new Array();
  9868. var equation = function (t, val0, val1, val2, val3) {
  9869. 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;
  9870. return res;
  9871. };
  9872. for (var i = 0; i <= nbPoints; i++) {
  9873. 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)));
  9874. }
  9875. return new Curve3(bez);
  9876. };
  9877. /**
  9878. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  9879. * @param p1 (Vector3) the origin point of the Hermite Spline
  9880. * @param t1 (Vector3) the tangent vector at the origin point
  9881. * @param p2 (Vector3) the end point of the Hermite Spline
  9882. * @param t2 (Vector3) the tangent vector at the end point
  9883. * @param nbPoints (integer) the wanted number of points in the curve
  9884. * @returns the created Curve3
  9885. */
  9886. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  9887. var hermite = new Array();
  9888. var step = 1.0 / nbPoints;
  9889. for (var i = 0; i <= nbPoints; i++) {
  9890. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  9891. }
  9892. return new Curve3(hermite);
  9893. };
  9894. /**
  9895. * Returns a Curve3 object along a CatmullRom Spline curve :
  9896. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  9897. * @param nbPoints (integer) the wanted number of points between each curve control points
  9898. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  9899. * @returns the created Curve3
  9900. */
  9901. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  9902. var catmullRom = new Array();
  9903. var step = 1.0 / nbPoints;
  9904. var amount = 0.0;
  9905. if (closed) {
  9906. var pointsCount = points.length;
  9907. for (var i = 0; i < pointsCount; i++) {
  9908. amount = 0;
  9909. for (var c = 0; c < nbPoints; c++) {
  9910. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  9911. amount += step;
  9912. }
  9913. }
  9914. catmullRom.push(catmullRom[0]);
  9915. }
  9916. else {
  9917. var totalPoints = new Array();
  9918. totalPoints.push(points[0].clone());
  9919. Array.prototype.push.apply(totalPoints, points);
  9920. totalPoints.push(points[points.length - 1].clone());
  9921. for (var i = 0; i < totalPoints.length - 3; i++) {
  9922. amount = 0;
  9923. for (var c = 0; c < nbPoints; c++) {
  9924. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9925. amount += step;
  9926. }
  9927. }
  9928. i--;
  9929. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9930. }
  9931. return new Curve3(catmullRom);
  9932. };
  9933. /**
  9934. * @returns the Curve3 stored array of successive Vector3
  9935. */
  9936. Curve3.prototype.getPoints = function () {
  9937. return this._points;
  9938. };
  9939. /**
  9940. * @returns the computed length (float) of the curve.
  9941. */
  9942. Curve3.prototype.length = function () {
  9943. return this._length;
  9944. };
  9945. /**
  9946. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  9947. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  9948. * curveA and curveB keep unchanged.
  9949. * @param curve the curve to continue from this curve
  9950. * @returns the newly constructed curve
  9951. */
  9952. Curve3.prototype.continue = function (curve) {
  9953. var lastPoint = this._points[this._points.length - 1];
  9954. var continuedPoints = this._points.slice();
  9955. var curvePoints = curve.getPoints();
  9956. for (var i = 1; i < curvePoints.length; i++) {
  9957. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  9958. }
  9959. var continuedCurve = new Curve3(continuedPoints);
  9960. return continuedCurve;
  9961. };
  9962. Curve3.prototype._computeLength = function (path) {
  9963. var l = 0;
  9964. for (var i = 1; i < path.length; i++) {
  9965. l += (path[i].subtract(path[i - 1])).length();
  9966. }
  9967. return l;
  9968. };
  9969. return Curve3;
  9970. }());
  9971. BABYLON.Curve3 = Curve3;
  9972. // Vertex formats
  9973. /**
  9974. * Contains position and normal vectors for a vertex
  9975. */
  9976. var PositionNormalVertex = /** @class */ (function () {
  9977. /**
  9978. * Creates a PositionNormalVertex
  9979. * @param position the position of the vertex (defaut: 0,0,0)
  9980. * @param normal the normal of the vertex (defaut: 0,1,0)
  9981. */
  9982. function PositionNormalVertex(
  9983. /** the position of the vertex (defaut: 0,0,0) */
  9984. position,
  9985. /** the normal of the vertex (defaut: 0,1,0) */
  9986. normal) {
  9987. if (position === void 0) { position = Vector3.Zero(); }
  9988. if (normal === void 0) { normal = Vector3.Up(); }
  9989. this.position = position;
  9990. this.normal = normal;
  9991. }
  9992. /**
  9993. * Clones the PositionNormalVertex
  9994. * @returns the cloned PositionNormalVertex
  9995. */
  9996. PositionNormalVertex.prototype.clone = function () {
  9997. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  9998. };
  9999. return PositionNormalVertex;
  10000. }());
  10001. BABYLON.PositionNormalVertex = PositionNormalVertex;
  10002. /**
  10003. * Contains position, normal and uv vectors for a vertex
  10004. */
  10005. var PositionNormalTextureVertex = /** @class */ (function () {
  10006. /**
  10007. * Creates a PositionNormalTextureVertex
  10008. * @param position the position of the vertex (defaut: 0,0,0)
  10009. * @param normal the normal of the vertex (defaut: 0,1,0)
  10010. * @param uv the uv of the vertex (default: 0,0)
  10011. */
  10012. function PositionNormalTextureVertex(
  10013. /** the position of the vertex (defaut: 0,0,0) */
  10014. position,
  10015. /** the normal of the vertex (defaut: 0,1,0) */
  10016. normal,
  10017. /** the uv of the vertex (default: 0,0) */
  10018. uv) {
  10019. if (position === void 0) { position = Vector3.Zero(); }
  10020. if (normal === void 0) { normal = Vector3.Up(); }
  10021. if (uv === void 0) { uv = Vector2.Zero(); }
  10022. this.position = position;
  10023. this.normal = normal;
  10024. this.uv = uv;
  10025. }
  10026. /**
  10027. * Clones the PositionNormalTextureVertex
  10028. * @returns the cloned PositionNormalTextureVertex
  10029. */
  10030. PositionNormalTextureVertex.prototype.clone = function () {
  10031. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  10032. };
  10033. return PositionNormalTextureVertex;
  10034. }());
  10035. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  10036. // Temporary pre-allocated objects for engine internal use
  10037. // usage in any internal function :
  10038. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  10039. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  10040. /**
  10041. * @hidden
  10042. */
  10043. var Tmp = /** @class */ (function () {
  10044. function Tmp() {
  10045. }
  10046. Tmp.Color3 = BABYLON.Tools.BuildArray(3, Color3.Black);
  10047. Tmp.Color4 = BABYLON.Tools.BuildArray(3, function () { return new Color4(0, 0, 0, 0); });
  10048. Tmp.Vector2 = BABYLON.Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  10049. Tmp.Vector3 = BABYLON.Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  10050. Tmp.Vector4 = BABYLON.Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  10051. Tmp.Quaternion = BABYLON.Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  10052. Tmp.Matrix = BABYLON.Tools.BuildArray(8, Matrix.Identity); // 8 temp Matrices at once should be enough
  10053. return Tmp;
  10054. }());
  10055. BABYLON.Tmp = Tmp;
  10056. /**
  10057. * @hidden
  10058. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  10059. */
  10060. var MathTmp = /** @class */ (function () {
  10061. function MathTmp() {
  10062. }
  10063. MathTmp.Vector3 = BABYLON.Tools.BuildArray(6, Vector3.Zero);
  10064. MathTmp.Matrix = BABYLON.Tools.BuildArray(2, Matrix.Identity);
  10065. MathTmp.Quaternion = BABYLON.Tools.BuildArray(3, Quaternion.Zero);
  10066. return MathTmp;
  10067. }());
  10068. })(BABYLON || (BABYLON = {}));
  10069. //# sourceMappingURL=babylon.math.js.map
  10070. var BABYLON;
  10071. (function (BABYLON) {
  10072. /**
  10073. * Scalar computation library
  10074. */
  10075. var Scalar = /** @class */ (function () {
  10076. function Scalar() {
  10077. }
  10078. /**
  10079. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10080. * @param a number
  10081. * @param b number
  10082. * @param epsilon (default = 1.401298E-45)
  10083. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10084. */
  10085. Scalar.WithinEpsilon = function (a, b, epsilon) {
  10086. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  10087. var num = a - b;
  10088. return -epsilon <= num && num <= epsilon;
  10089. };
  10090. /**
  10091. * Returns a string : the upper case translation of the number i to hexadecimal.
  10092. * @param i number
  10093. * @returns the upper case translation of the number i to hexadecimal.
  10094. */
  10095. Scalar.ToHex = function (i) {
  10096. var str = i.toString(16);
  10097. if (i <= 15) {
  10098. return ("0" + str).toUpperCase();
  10099. }
  10100. return str.toUpperCase();
  10101. };
  10102. /**
  10103. * Returns -1 if value is negative and +1 is value is positive.
  10104. * @param value the value
  10105. * @returns the value itself if it's equal to zero.
  10106. */
  10107. Scalar.Sign = function (value) {
  10108. value = +value; // convert to a number
  10109. if (value === 0 || isNaN(value)) {
  10110. return value;
  10111. }
  10112. return value > 0 ? 1 : -1;
  10113. };
  10114. /**
  10115. * Returns the value itself if it's between min and max.
  10116. * Returns min if the value is lower than min.
  10117. * Returns max if the value is greater than max.
  10118. * @param value the value to clmap
  10119. * @param min the min value to clamp to (default: 0)
  10120. * @param max the max value to clamp to (default: 1)
  10121. * @returns the clamped value
  10122. */
  10123. Scalar.Clamp = function (value, min, max) {
  10124. if (min === void 0) { min = 0; }
  10125. if (max === void 0) { max = 1; }
  10126. return Math.min(max, Math.max(min, value));
  10127. };
  10128. /**
  10129. * the log2 of value.
  10130. * @param value the value to compute log2 of
  10131. * @returns the log2 of value.
  10132. */
  10133. Scalar.Log2 = function (value) {
  10134. return Math.log(value) * Math.LOG2E;
  10135. };
  10136. /**
  10137. * Loops the value, so that it is never larger than length and never smaller than 0.
  10138. *
  10139. * This is similar to the modulo operator but it works with floating point numbers.
  10140. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  10141. * With t = 5 and length = 2.5, the result would be 0.0.
  10142. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  10143. * @param value the value
  10144. * @param length the length
  10145. * @returns the looped value
  10146. */
  10147. Scalar.Repeat = function (value, length) {
  10148. return value - Math.floor(value / length) * length;
  10149. };
  10150. /**
  10151. * Normalize the value between 0.0 and 1.0 using min and max values
  10152. * @param value value to normalize
  10153. * @param min max to normalize between
  10154. * @param max min to normalize between
  10155. * @returns the normalized value
  10156. */
  10157. Scalar.Normalize = function (value, min, max) {
  10158. return (value - min) / (max - min);
  10159. };
  10160. /**
  10161. * Denormalize the value from 0.0 and 1.0 using min and max values
  10162. * @param normalized value to denormalize
  10163. * @param min max to denormalize between
  10164. * @param max min to denormalize between
  10165. * @returns the denormalized value
  10166. */
  10167. Scalar.Denormalize = function (normalized, min, max) {
  10168. return (normalized * (max - min) + min);
  10169. };
  10170. /**
  10171. * Calculates the shortest difference between two given angles given in degrees.
  10172. * @param current current angle in degrees
  10173. * @param target target angle in degrees
  10174. * @returns the delta
  10175. */
  10176. Scalar.DeltaAngle = function (current, target) {
  10177. var num = Scalar.Repeat(target - current, 360.0);
  10178. if (num > 180.0) {
  10179. num -= 360.0;
  10180. }
  10181. return num;
  10182. };
  10183. /**
  10184. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  10185. * @param tx value
  10186. * @param length length
  10187. * @returns The returned value will move back and forth between 0 and length
  10188. */
  10189. Scalar.PingPong = function (tx, length) {
  10190. var t = Scalar.Repeat(tx, length * 2.0);
  10191. return length - Math.abs(t - length);
  10192. };
  10193. /**
  10194. * Interpolates between min and max with smoothing at the limits.
  10195. *
  10196. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  10197. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  10198. * @param from from
  10199. * @param to to
  10200. * @param tx value
  10201. * @returns the smooth stepped value
  10202. */
  10203. Scalar.SmoothStep = function (from, to, tx) {
  10204. var t = Scalar.Clamp(tx);
  10205. t = -2.0 * t * t * t + 3.0 * t * t;
  10206. return to * t + from * (1.0 - t);
  10207. };
  10208. /**
  10209. * Moves a value current towards target.
  10210. *
  10211. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  10212. * Negative values of maxDelta pushes the value away from target.
  10213. * @param current current value
  10214. * @param target target value
  10215. * @param maxDelta max distance to move
  10216. * @returns resulting value
  10217. */
  10218. Scalar.MoveTowards = function (current, target, maxDelta) {
  10219. var result = 0;
  10220. if (Math.abs(target - current) <= maxDelta) {
  10221. result = target;
  10222. }
  10223. else {
  10224. result = current + Scalar.Sign(target - current) * maxDelta;
  10225. }
  10226. return result;
  10227. };
  10228. /**
  10229. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10230. *
  10231. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  10232. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  10233. * @param current current value
  10234. * @param target target value
  10235. * @param maxDelta max distance to move
  10236. * @returns resulting angle
  10237. */
  10238. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  10239. var num = Scalar.DeltaAngle(current, target);
  10240. var result = 0;
  10241. if (-maxDelta < num && num < maxDelta) {
  10242. result = target;
  10243. }
  10244. else {
  10245. target = current + num;
  10246. result = Scalar.MoveTowards(current, target, maxDelta);
  10247. }
  10248. return result;
  10249. };
  10250. /**
  10251. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  10252. * @param start start value
  10253. * @param end target value
  10254. * @param amount amount to lerp between
  10255. * @returns the lerped value
  10256. */
  10257. Scalar.Lerp = function (start, end, amount) {
  10258. return start + ((end - start) * amount);
  10259. };
  10260. /**
  10261. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10262. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  10263. * @param start start value
  10264. * @param end target value
  10265. * @param amount amount to lerp between
  10266. * @returns the lerped value
  10267. */
  10268. Scalar.LerpAngle = function (start, end, amount) {
  10269. var num = Scalar.Repeat(end - start, 360.0);
  10270. if (num > 180.0) {
  10271. num -= 360.0;
  10272. }
  10273. return start + num * Scalar.Clamp(amount);
  10274. };
  10275. /**
  10276. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  10277. * @param a start value
  10278. * @param b target value
  10279. * @param value value between a and b
  10280. * @returns the inverseLerp value
  10281. */
  10282. Scalar.InverseLerp = function (a, b, value) {
  10283. var result = 0;
  10284. if (a != b) {
  10285. result = Scalar.Clamp((value - a) / (b - a));
  10286. }
  10287. else {
  10288. result = 0.0;
  10289. }
  10290. return result;
  10291. };
  10292. /**
  10293. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  10294. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  10295. * @param value1 spline value
  10296. * @param tangent1 spline value
  10297. * @param value2 spline value
  10298. * @param tangent2 spline value
  10299. * @param amount input value
  10300. * @returns hermite result
  10301. */
  10302. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  10303. var squared = amount * amount;
  10304. var cubed = amount * squared;
  10305. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  10306. var part2 = (-2.0 * cubed) + (3.0 * squared);
  10307. var part3 = (cubed - (2.0 * squared)) + amount;
  10308. var part4 = cubed - squared;
  10309. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  10310. };
  10311. /**
  10312. * Returns a random float number between and min and max values
  10313. * @param min min value of random
  10314. * @param max max value of random
  10315. * @returns random value
  10316. */
  10317. Scalar.RandomRange = function (min, max) {
  10318. if (min === max) {
  10319. return min;
  10320. }
  10321. return ((Math.random() * (max - min)) + min);
  10322. };
  10323. /**
  10324. * This function returns percentage of a number in a given range.
  10325. *
  10326. * RangeToPercent(40,20,60) will return 0.5 (50%)
  10327. * RangeToPercent(34,0,100) will return 0.34 (34%)
  10328. * @param number to convert to percentage
  10329. * @param min min range
  10330. * @param max max range
  10331. * @returns the percentage
  10332. */
  10333. Scalar.RangeToPercent = function (number, min, max) {
  10334. return ((number - min) / (max - min));
  10335. };
  10336. /**
  10337. * This function returns number that corresponds to the percentage in a given range.
  10338. *
  10339. * PercentToRange(0.34,0,100) will return 34.
  10340. * @param percent to convert to number
  10341. * @param min min range
  10342. * @param max max range
  10343. * @returns the number
  10344. */
  10345. Scalar.PercentToRange = function (percent, min, max) {
  10346. return ((max - min) * percent + min);
  10347. };
  10348. /**
  10349. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  10350. * @param angle The angle to normalize in radian.
  10351. * @return The converted angle.
  10352. */
  10353. Scalar.NormalizeRadians = function (angle) {
  10354. // More precise but slower version kept for reference.
  10355. // angle = angle % Tools.TwoPi;
  10356. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  10357. //if (angle > Math.PI) {
  10358. // angle -= Tools.TwoPi;
  10359. //}
  10360. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  10361. return angle;
  10362. };
  10363. /**
  10364. * Two pi constants convenient for computation.
  10365. */
  10366. Scalar.TwoPi = Math.PI * 2;
  10367. return Scalar;
  10368. }());
  10369. BABYLON.Scalar = Scalar;
  10370. })(BABYLON || (BABYLON = {}));
  10371. //# sourceMappingURL=babylon.math.scalar.js.map
  10372. var XRFrameOfReferenceType;
  10373. (function (XRFrameOfReferenceType) {
  10374. XRFrameOfReferenceType[XRFrameOfReferenceType["head-model"] = 0] = "head-model";
  10375. XRFrameOfReferenceType[XRFrameOfReferenceType["eye-level"] = 1] = "eye-level";
  10376. XRFrameOfReferenceType[XRFrameOfReferenceType["stage"] = 2] = "stage";
  10377. })(XRFrameOfReferenceType || (XRFrameOfReferenceType = {}));
  10378. //# sourceMappingURL=babylon.mixins.js.map
  10379. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  10380. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  10381. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  10382. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10383. //# sourceMappingURL=babylon.webgl2.js.map
  10384. var BABYLON;
  10385. (function (BABYLON) {
  10386. var __decoratorInitialStore = {};
  10387. var __mergedStore = {};
  10388. var _copySource = function (creationFunction, source, instanciate) {
  10389. var destination = creationFunction();
  10390. // Tags
  10391. if (BABYLON.Tags) {
  10392. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10393. }
  10394. var classStore = getMergedStore(destination);
  10395. // Properties
  10396. for (var property in classStore) {
  10397. var propertyDescriptor = classStore[property];
  10398. var sourceProperty = source[property];
  10399. var propertyType = propertyDescriptor.type;
  10400. if (sourceProperty !== undefined && sourceProperty !== null) {
  10401. switch (propertyType) {
  10402. case 0: // Value
  10403. case 6: // Mesh reference
  10404. case 11: // Camera reference
  10405. destination[property] = sourceProperty;
  10406. break;
  10407. case 1: // Texture
  10408. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  10409. break;
  10410. case 2: // Color3
  10411. case 3: // FresnelParameters
  10412. case 4: // Vector2
  10413. case 5: // Vector3
  10414. case 7: // Color Curves
  10415. case 10: // Quaternion
  10416. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  10417. break;
  10418. }
  10419. }
  10420. }
  10421. return destination;
  10422. };
  10423. function getDirectStore(target) {
  10424. var classKey = target.getClassName();
  10425. if (!__decoratorInitialStore[classKey]) {
  10426. __decoratorInitialStore[classKey] = {};
  10427. }
  10428. return __decoratorInitialStore[classKey];
  10429. }
  10430. /**
  10431. * Return the list of properties flagged as serializable
  10432. * @param target: host object
  10433. */
  10434. function getMergedStore(target) {
  10435. var classKey = target.getClassName();
  10436. if (__mergedStore[classKey]) {
  10437. return __mergedStore[classKey];
  10438. }
  10439. __mergedStore[classKey] = {};
  10440. var store = __mergedStore[classKey];
  10441. var currentTarget = target;
  10442. var currentKey = classKey;
  10443. while (currentKey) {
  10444. var initialStore = __decoratorInitialStore[currentKey];
  10445. for (var property in initialStore) {
  10446. store[property] = initialStore[property];
  10447. }
  10448. var parent_1 = void 0;
  10449. var done = false;
  10450. do {
  10451. parent_1 = Object.getPrototypeOf(currentTarget);
  10452. if (!parent_1.getClassName) {
  10453. done = true;
  10454. break;
  10455. }
  10456. if (parent_1.getClassName() !== currentKey) {
  10457. break;
  10458. }
  10459. currentTarget = parent_1;
  10460. } while (parent_1);
  10461. if (done) {
  10462. break;
  10463. }
  10464. currentKey = parent_1.getClassName();
  10465. currentTarget = parent_1;
  10466. }
  10467. return store;
  10468. }
  10469. function generateSerializableMember(type, sourceName) {
  10470. return function (target, propertyKey) {
  10471. var classStore = getDirectStore(target);
  10472. if (!classStore[propertyKey]) {
  10473. classStore[propertyKey] = { type: type, sourceName: sourceName };
  10474. }
  10475. };
  10476. }
  10477. function generateExpandMember(setCallback, targetKey) {
  10478. if (targetKey === void 0) { targetKey = null; }
  10479. return function (target, propertyKey) {
  10480. var key = targetKey || ("_" + propertyKey);
  10481. Object.defineProperty(target, propertyKey, {
  10482. get: function () {
  10483. return this[key];
  10484. },
  10485. set: function (value) {
  10486. if (this[key] === value) {
  10487. return;
  10488. }
  10489. this[key] = value;
  10490. target[setCallback].apply(this);
  10491. },
  10492. enumerable: true,
  10493. configurable: true
  10494. });
  10495. };
  10496. }
  10497. function expandToProperty(callback, targetKey) {
  10498. if (targetKey === void 0) { targetKey = null; }
  10499. return generateExpandMember(callback, targetKey);
  10500. }
  10501. BABYLON.expandToProperty = expandToProperty;
  10502. function serialize(sourceName) {
  10503. return generateSerializableMember(0, sourceName); // value member
  10504. }
  10505. BABYLON.serialize = serialize;
  10506. function serializeAsTexture(sourceName) {
  10507. return generateSerializableMember(1, sourceName); // texture member
  10508. }
  10509. BABYLON.serializeAsTexture = serializeAsTexture;
  10510. function serializeAsColor3(sourceName) {
  10511. return generateSerializableMember(2, sourceName); // color3 member
  10512. }
  10513. BABYLON.serializeAsColor3 = serializeAsColor3;
  10514. function serializeAsFresnelParameters(sourceName) {
  10515. return generateSerializableMember(3, sourceName); // fresnel parameters member
  10516. }
  10517. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  10518. function serializeAsVector2(sourceName) {
  10519. return generateSerializableMember(4, sourceName); // vector2 member
  10520. }
  10521. BABYLON.serializeAsVector2 = serializeAsVector2;
  10522. function serializeAsVector3(sourceName) {
  10523. return generateSerializableMember(5, sourceName); // vector3 member
  10524. }
  10525. BABYLON.serializeAsVector3 = serializeAsVector3;
  10526. function serializeAsMeshReference(sourceName) {
  10527. return generateSerializableMember(6, sourceName); // mesh reference member
  10528. }
  10529. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  10530. function serializeAsColorCurves(sourceName) {
  10531. return generateSerializableMember(7, sourceName); // color curves
  10532. }
  10533. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  10534. function serializeAsColor4(sourceName) {
  10535. return generateSerializableMember(8, sourceName); // color 4
  10536. }
  10537. BABYLON.serializeAsColor4 = serializeAsColor4;
  10538. function serializeAsImageProcessingConfiguration(sourceName) {
  10539. return generateSerializableMember(9, sourceName); // image processing
  10540. }
  10541. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  10542. function serializeAsQuaternion(sourceName) {
  10543. return generateSerializableMember(10, sourceName); // quaternion member
  10544. }
  10545. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  10546. /**
  10547. * Decorator used to define property that can be serialized as reference to a camera
  10548. * @param sourceName defines the name of the property to decorate
  10549. */
  10550. function serializeAsCameraReference(sourceName) {
  10551. return generateSerializableMember(11, sourceName); // camera reference member
  10552. }
  10553. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  10554. /**
  10555. * Class used to help serialization objects
  10556. */
  10557. var SerializationHelper = /** @class */ (function () {
  10558. function SerializationHelper() {
  10559. }
  10560. /**
  10561. * Static function used to serialized a specific entity
  10562. * @param entity defines the entity to serialize
  10563. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  10564. * @returns a JSON compatible object representing the serialization of the entity
  10565. */
  10566. SerializationHelper.Serialize = function (entity, serializationObject) {
  10567. if (!serializationObject) {
  10568. serializationObject = {};
  10569. }
  10570. // Tags
  10571. if (BABYLON.Tags) {
  10572. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  10573. }
  10574. var serializedProperties = getMergedStore(entity);
  10575. // Properties
  10576. for (var property in serializedProperties) {
  10577. var propertyDescriptor = serializedProperties[property];
  10578. var targetPropertyName = propertyDescriptor.sourceName || property;
  10579. var propertyType = propertyDescriptor.type;
  10580. var sourceProperty = entity[property];
  10581. if (sourceProperty !== undefined && sourceProperty !== null) {
  10582. switch (propertyType) {
  10583. case 0: // Value
  10584. serializationObject[targetPropertyName] = sourceProperty;
  10585. break;
  10586. case 1: // Texture
  10587. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10588. break;
  10589. case 2: // Color3
  10590. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10591. break;
  10592. case 3: // FresnelParameters
  10593. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10594. break;
  10595. case 4: // Vector2
  10596. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10597. break;
  10598. case 5: // Vector3
  10599. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10600. break;
  10601. case 6: // Mesh reference
  10602. serializationObject[targetPropertyName] = sourceProperty.id;
  10603. break;
  10604. case 7: // Color Curves
  10605. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10606. break;
  10607. case 8: // Color 4
  10608. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10609. break;
  10610. case 9: // Image Processing
  10611. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10612. break;
  10613. case 10: // Quaternion
  10614. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10615. break;
  10616. case 11: // Camera reference
  10617. serializationObject[targetPropertyName] = sourceProperty.id;
  10618. break;
  10619. }
  10620. }
  10621. }
  10622. return serializationObject;
  10623. };
  10624. /**
  10625. * Creates a new entity from a serialization data object
  10626. * @param creationFunction defines a function used to instanciated the new entity
  10627. * @param source defines the source serialization data
  10628. * @param scene defines the hosting scene
  10629. * @param rootUrl defines the root url for resources
  10630. * @returns a new entity
  10631. */
  10632. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  10633. if (rootUrl === void 0) { rootUrl = null; }
  10634. var destination = creationFunction();
  10635. if (!rootUrl) {
  10636. rootUrl = "";
  10637. }
  10638. // Tags
  10639. if (BABYLON.Tags) {
  10640. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10641. }
  10642. var classStore = getMergedStore(destination);
  10643. // Properties
  10644. for (var property in classStore) {
  10645. var propertyDescriptor = classStore[property];
  10646. var sourceProperty = source[propertyDescriptor.sourceName || property];
  10647. var propertyType = propertyDescriptor.type;
  10648. if (sourceProperty !== undefined && sourceProperty !== null) {
  10649. var dest = destination;
  10650. switch (propertyType) {
  10651. case 0: // Value
  10652. dest[property] = sourceProperty;
  10653. break;
  10654. case 1: // Texture
  10655. if (scene) {
  10656. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  10657. }
  10658. break;
  10659. case 2: // Color3
  10660. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  10661. break;
  10662. case 3: // FresnelParameters
  10663. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  10664. break;
  10665. case 4: // Vector2
  10666. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  10667. break;
  10668. case 5: // Vector3
  10669. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  10670. break;
  10671. case 6: // Mesh reference
  10672. if (scene) {
  10673. dest[property] = scene.getLastMeshByID(sourceProperty);
  10674. }
  10675. break;
  10676. case 7: // Color Curves
  10677. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  10678. break;
  10679. case 8: // Color 4
  10680. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  10681. break;
  10682. case 9: // Image Processing
  10683. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  10684. break;
  10685. case 10: // Quaternion
  10686. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  10687. break;
  10688. case 11: // Camera reference
  10689. if (scene) {
  10690. dest[property] = scene.getCameraByID(sourceProperty);
  10691. }
  10692. break;
  10693. }
  10694. }
  10695. }
  10696. return destination;
  10697. };
  10698. /**
  10699. * Clones an object
  10700. * @param creationFunction defines the function used to instanciate the new object
  10701. * @param source defines the source object
  10702. * @returns the cloned object
  10703. */
  10704. SerializationHelper.Clone = function (creationFunction, source) {
  10705. return _copySource(creationFunction, source, false);
  10706. };
  10707. /**
  10708. * Instanciates a new object based on a source one (some data will be shared between both object)
  10709. * @param creationFunction defines the function used to instanciate the new object
  10710. * @param source defines the source object
  10711. * @returns the new object
  10712. */
  10713. SerializationHelper.Instanciate = function (creationFunction, source) {
  10714. return _copySource(creationFunction, source, true);
  10715. };
  10716. return SerializationHelper;
  10717. }());
  10718. BABYLON.SerializationHelper = SerializationHelper;
  10719. })(BABYLON || (BABYLON = {}));
  10720. //# sourceMappingURL=babylon.decorators.js.map
  10721. var BABYLON;
  10722. (function (BABYLON) {
  10723. /**
  10724. * Wrapper class for promise with external resolve and reject.
  10725. */
  10726. var Deferred = /** @class */ (function () {
  10727. /**
  10728. * Constructor for this deferred object.
  10729. */
  10730. function Deferred() {
  10731. var _this = this;
  10732. this.promise = new Promise(function (resolve, reject) {
  10733. _this._resolve = resolve;
  10734. _this._reject = reject;
  10735. });
  10736. }
  10737. Object.defineProperty(Deferred.prototype, "resolve", {
  10738. /**
  10739. * The resolve method of the promise associated with this deferred object.
  10740. */
  10741. get: function () {
  10742. return this._resolve;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(Deferred.prototype, "reject", {
  10748. /**
  10749. * The reject method of the promise associated with this deferred object.
  10750. */
  10751. get: function () {
  10752. return this._reject;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. return Deferred;
  10758. }());
  10759. BABYLON.Deferred = Deferred;
  10760. })(BABYLON || (BABYLON = {}));
  10761. //# sourceMappingURL=babylon.deferred.js.map
  10762. var BABYLON;
  10763. (function (BABYLON) {
  10764. /**
  10765. * A class serves as a medium between the observable and its observers
  10766. */
  10767. var EventState = /** @class */ (function () {
  10768. /**
  10769. * Create a new EventState
  10770. * @param mask defines the mask associated with this state
  10771. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10772. * @param target defines the original target of the state
  10773. * @param currentTarget defines the current target of the state
  10774. */
  10775. function EventState(mask, skipNextObservers, target, currentTarget) {
  10776. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10777. this.initalize(mask, skipNextObservers, target, currentTarget);
  10778. }
  10779. /**
  10780. * Initialize the current event state
  10781. * @param mask defines the mask associated with this state
  10782. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10783. * @param target defines the original target of the state
  10784. * @param currentTarget defines the current target of the state
  10785. * @returns the current event state
  10786. */
  10787. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  10788. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10789. this.mask = mask;
  10790. this.skipNextObservers = skipNextObservers;
  10791. this.target = target;
  10792. this.currentTarget = currentTarget;
  10793. return this;
  10794. };
  10795. return EventState;
  10796. }());
  10797. BABYLON.EventState = EventState;
  10798. /**
  10799. * Represent an Observer registered to a given Observable object.
  10800. */
  10801. var Observer = /** @class */ (function () {
  10802. /**
  10803. * Creates a new observer
  10804. * @param callback defines the callback to call when the observer is notified
  10805. * @param mask defines the mask of the observer (used to filter notifications)
  10806. * @param scope defines the current scope used to restore the JS context
  10807. */
  10808. function Observer(
  10809. /**
  10810. * Defines the callback to call when the observer is notified
  10811. */
  10812. callback,
  10813. /**
  10814. * Defines the mask of the observer (used to filter notifications)
  10815. */
  10816. mask,
  10817. /**
  10818. * Defines the current scope used to restore the JS context
  10819. */
  10820. scope) {
  10821. if (scope === void 0) { scope = null; }
  10822. this.callback = callback;
  10823. this.mask = mask;
  10824. this.scope = scope;
  10825. /** @hidden */
  10826. this._willBeUnregistered = false;
  10827. /**
  10828. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  10829. */
  10830. this.unregisterOnNextCall = false;
  10831. }
  10832. return Observer;
  10833. }());
  10834. BABYLON.Observer = Observer;
  10835. /**
  10836. * Represent a list of observers registered to multiple Observables object.
  10837. */
  10838. var MultiObserver = /** @class */ (function () {
  10839. function MultiObserver() {
  10840. }
  10841. /**
  10842. * Release associated resources
  10843. */
  10844. MultiObserver.prototype.dispose = function () {
  10845. if (this._observers && this._observables) {
  10846. for (var index = 0; index < this._observers.length; index++) {
  10847. this._observables[index].remove(this._observers[index]);
  10848. }
  10849. }
  10850. this._observers = null;
  10851. this._observables = null;
  10852. };
  10853. /**
  10854. * Raise a callback when one of the observable will notify
  10855. * @param observables defines a list of observables to watch
  10856. * @param callback defines the callback to call on notification
  10857. * @param mask defines the mask used to filter notifications
  10858. * @param scope defines the current scope used to restore the JS context
  10859. * @returns the new MultiObserver
  10860. */
  10861. MultiObserver.Watch = function (observables, callback, mask, scope) {
  10862. if (mask === void 0) { mask = -1; }
  10863. if (scope === void 0) { scope = null; }
  10864. var result = new MultiObserver();
  10865. result._observers = new Array();
  10866. result._observables = observables;
  10867. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  10868. var observable = observables_1[_i];
  10869. var observer = observable.add(callback, mask, false, scope);
  10870. if (observer) {
  10871. result._observers.push(observer);
  10872. }
  10873. }
  10874. return result;
  10875. };
  10876. return MultiObserver;
  10877. }());
  10878. BABYLON.MultiObserver = MultiObserver;
  10879. /**
  10880. * The Observable class is a simple implementation of the Observable pattern.
  10881. *
  10882. * 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.
  10883. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  10884. * 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).
  10885. * 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.
  10886. */
  10887. var Observable = /** @class */ (function () {
  10888. /**
  10889. * Creates a new observable
  10890. * @param onObserverAdded defines a callback to call when a new observer is added
  10891. */
  10892. function Observable(onObserverAdded) {
  10893. this._observers = new Array();
  10894. this._eventState = new EventState(0);
  10895. if (onObserverAdded) {
  10896. this._onObserverAdded = onObserverAdded;
  10897. }
  10898. }
  10899. /**
  10900. * Create a new Observer with the specified callback
  10901. * @param callback the callback that will be executed for that Observer
  10902. * @param mask the mask used to filter observers
  10903. * @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.
  10904. * @param scope optional scope for the callback to be called from
  10905. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  10906. * @returns the new observer created for the callback
  10907. */
  10908. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  10909. if (mask === void 0) { mask = -1; }
  10910. if (insertFirst === void 0) { insertFirst = false; }
  10911. if (scope === void 0) { scope = null; }
  10912. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  10913. if (!callback) {
  10914. return null;
  10915. }
  10916. var observer = new Observer(callback, mask, scope);
  10917. observer.unregisterOnNextCall = unregisterOnFirstCall;
  10918. if (insertFirst) {
  10919. this._observers.unshift(observer);
  10920. }
  10921. else {
  10922. this._observers.push(observer);
  10923. }
  10924. if (this._onObserverAdded) {
  10925. this._onObserverAdded(observer);
  10926. }
  10927. return observer;
  10928. };
  10929. /**
  10930. * Create a new Observer with the specified callback and unregisters after the next notification
  10931. * @param callback the callback that will be executed for that Observer
  10932. * @returns the new observer created for the callback
  10933. */
  10934. Observable.prototype.addOnce = function (callback) {
  10935. return this.add(callback, undefined, undefined, undefined, true);
  10936. };
  10937. /**
  10938. * Remove an Observer from the Observable object
  10939. * @param observer the instance of the Observer to remove
  10940. * @returns false if it doesn't belong to this Observable
  10941. */
  10942. Observable.prototype.remove = function (observer) {
  10943. if (!observer) {
  10944. return false;
  10945. }
  10946. var index = this._observers.indexOf(observer);
  10947. if (index !== -1) {
  10948. this._deferUnregister(observer);
  10949. return true;
  10950. }
  10951. return false;
  10952. };
  10953. /**
  10954. * Remove a callback from the Observable object
  10955. * @param callback the callback to remove
  10956. * @param scope optional scope. If used only the callbacks with this scope will be removed
  10957. * @returns false if it doesn't belong to this Observable
  10958. */
  10959. Observable.prototype.removeCallback = function (callback, scope) {
  10960. for (var index = 0; index < this._observers.length; index++) {
  10961. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  10962. this._deferUnregister(this._observers[index]);
  10963. return true;
  10964. }
  10965. }
  10966. return false;
  10967. };
  10968. Observable.prototype._deferUnregister = function (observer) {
  10969. var _this = this;
  10970. observer.unregisterOnNextCall = false;
  10971. observer._willBeUnregistered = true;
  10972. BABYLON.Tools.SetImmediate(function () {
  10973. _this._remove(observer);
  10974. });
  10975. };
  10976. // This should only be called when not iterating over _observers to avoid callback skipping.
  10977. // Removes an observer from the _observer Array.
  10978. Observable.prototype._remove = function (observer) {
  10979. if (!observer) {
  10980. return false;
  10981. }
  10982. var index = this._observers.indexOf(observer);
  10983. if (index !== -1) {
  10984. this._observers.splice(index, 1);
  10985. return true;
  10986. }
  10987. return false;
  10988. };
  10989. /**
  10990. * Notify all Observers by calling their respective callback with the given data
  10991. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  10992. * @param eventData defines the data to send to all observers
  10993. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  10994. * @param target defines the original target of the state
  10995. * @param currentTarget defines the current target of the state
  10996. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  10997. */
  10998. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  10999. if (mask === void 0) { mask = -1; }
  11000. if (!this._observers.length) {
  11001. return true;
  11002. }
  11003. var state = this._eventState;
  11004. state.mask = mask;
  11005. state.target = target;
  11006. state.currentTarget = currentTarget;
  11007. state.skipNextObservers = false;
  11008. state.lastReturnValue = eventData;
  11009. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11010. var obs = _a[_i];
  11011. if (obs._willBeUnregistered) {
  11012. continue;
  11013. }
  11014. if (obs.mask & mask) {
  11015. if (obs.scope) {
  11016. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  11017. }
  11018. else {
  11019. state.lastReturnValue = obs.callback(eventData, state);
  11020. }
  11021. if (obs.unregisterOnNextCall) {
  11022. this._deferUnregister(obs);
  11023. }
  11024. }
  11025. if (state.skipNextObservers) {
  11026. return false;
  11027. }
  11028. }
  11029. return true;
  11030. };
  11031. /**
  11032. * Calling this will execute each callback, expecting it to be a promise or return a value.
  11033. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  11034. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  11035. * and it is crucial that all callbacks will be executed.
  11036. * The order of the callbacks is kept, callbacks are not executed parallel.
  11037. *
  11038. * @param eventData The data to be sent to each callback
  11039. * @param mask is used to filter observers defaults to -1
  11040. * @param target defines the callback target (see EventState)
  11041. * @param currentTarget defines he current object in the bubbling phase
  11042. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  11043. */
  11044. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  11045. var _this = this;
  11046. if (mask === void 0) { mask = -1; }
  11047. // create an empty promise
  11048. var p = Promise.resolve(eventData);
  11049. // no observers? return this promise.
  11050. if (!this._observers.length) {
  11051. return p;
  11052. }
  11053. var state = this._eventState;
  11054. state.mask = mask;
  11055. state.target = target;
  11056. state.currentTarget = currentTarget;
  11057. state.skipNextObservers = false;
  11058. // execute one callback after another (not using Promise.all, the order is important)
  11059. this._observers.forEach(function (obs) {
  11060. if (state.skipNextObservers) {
  11061. return;
  11062. }
  11063. if (obs._willBeUnregistered) {
  11064. return;
  11065. }
  11066. if (obs.mask & mask) {
  11067. if (obs.scope) {
  11068. p = p.then(function (lastReturnedValue) {
  11069. state.lastReturnValue = lastReturnedValue;
  11070. return obs.callback.apply(obs.scope, [eventData, state]);
  11071. });
  11072. }
  11073. else {
  11074. p = p.then(function (lastReturnedValue) {
  11075. state.lastReturnValue = lastReturnedValue;
  11076. return obs.callback(eventData, state);
  11077. });
  11078. }
  11079. if (obs.unregisterOnNextCall) {
  11080. _this._deferUnregister(obs);
  11081. }
  11082. }
  11083. });
  11084. // return the eventData
  11085. return p.then(function () { return eventData; });
  11086. };
  11087. /**
  11088. * Notify a specific observer
  11089. * @param observer defines the observer to notify
  11090. * @param eventData defines the data to be sent to each callback
  11091. * @param mask is used to filter observers defaults to -1
  11092. */
  11093. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  11094. if (mask === void 0) { mask = -1; }
  11095. var state = this._eventState;
  11096. state.mask = mask;
  11097. state.skipNextObservers = false;
  11098. observer.callback(eventData, state);
  11099. };
  11100. /**
  11101. * Gets a boolean indicating if the observable has at least one observer
  11102. * @returns true is the Observable has at least one Observer registered
  11103. */
  11104. Observable.prototype.hasObservers = function () {
  11105. return this._observers.length > 0;
  11106. };
  11107. /**
  11108. * Clear the list of observers
  11109. */
  11110. Observable.prototype.clear = function () {
  11111. this._observers = new Array();
  11112. this._onObserverAdded = null;
  11113. };
  11114. /**
  11115. * Clone the current observable
  11116. * @returns a new observable
  11117. */
  11118. Observable.prototype.clone = function () {
  11119. var result = new Observable();
  11120. result._observers = this._observers.slice(0);
  11121. return result;
  11122. };
  11123. /**
  11124. * Does this observable handles observer registered with a given mask
  11125. * @param mask defines the mask to be tested
  11126. * @return whether or not one observer registered with the given mask is handeled
  11127. **/
  11128. Observable.prototype.hasSpecificMask = function (mask) {
  11129. if (mask === void 0) { mask = -1; }
  11130. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11131. var obs = _a[_i];
  11132. if (obs.mask & mask || obs.mask === mask) {
  11133. return true;
  11134. }
  11135. }
  11136. return false;
  11137. };
  11138. return Observable;
  11139. }());
  11140. BABYLON.Observable = Observable;
  11141. })(BABYLON || (BABYLON = {}));
  11142. //# sourceMappingURL=babylon.observable.js.map
  11143. var BABYLON;
  11144. (function (BABYLON) {
  11145. /**
  11146. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11147. */
  11148. var SmartArray = /** @class */ (function () {
  11149. /**
  11150. * Instantiates a Smart Array.
  11151. * @param capacity defines the default capacity of the array.
  11152. */
  11153. function SmartArray(capacity) {
  11154. /**
  11155. * The active length of the array.
  11156. */
  11157. this.length = 0;
  11158. this.data = new Array(capacity);
  11159. this._id = SmartArray._GlobalId++;
  11160. }
  11161. /**
  11162. * Pushes a value at the end of the active data.
  11163. * @param value defines the object to push in the array.
  11164. */
  11165. SmartArray.prototype.push = function (value) {
  11166. this.data[this.length++] = value;
  11167. if (this.length > this.data.length) {
  11168. this.data.length *= 2;
  11169. }
  11170. };
  11171. /**
  11172. * Iterates over the active data and apply the lambda to them.
  11173. * @param func defines the action to apply on each value.
  11174. */
  11175. SmartArray.prototype.forEach = function (func) {
  11176. for (var index = 0; index < this.length; index++) {
  11177. func(this.data[index]);
  11178. }
  11179. };
  11180. /**
  11181. * Sorts the full sets of data.
  11182. * @param compareFn defines the comparison function to apply.
  11183. */
  11184. SmartArray.prototype.sort = function (compareFn) {
  11185. this.data.sort(compareFn);
  11186. };
  11187. /**
  11188. * Resets the active data to an empty array.
  11189. */
  11190. SmartArray.prototype.reset = function () {
  11191. this.length = 0;
  11192. };
  11193. /**
  11194. * Releases all the data from the array as well as the array.
  11195. */
  11196. SmartArray.prototype.dispose = function () {
  11197. this.reset();
  11198. if (this.data) {
  11199. this.data.length = 0;
  11200. this.data = [];
  11201. }
  11202. };
  11203. /**
  11204. * Concats the active data with a given array.
  11205. * @param array defines the data to concatenate with.
  11206. */
  11207. SmartArray.prototype.concat = function (array) {
  11208. if (array.length === 0) {
  11209. return;
  11210. }
  11211. if (this.length + array.length > this.data.length) {
  11212. this.data.length = (this.length + array.length) * 2;
  11213. }
  11214. for (var index = 0; index < array.length; index++) {
  11215. this.data[this.length++] = (array.data || array)[index];
  11216. }
  11217. };
  11218. /**
  11219. * Returns the position of a value in the active data.
  11220. * @param value defines the value to find the index for
  11221. * @returns the index if found in the active data otherwise -1
  11222. */
  11223. SmartArray.prototype.indexOf = function (value) {
  11224. var position = this.data.indexOf(value);
  11225. if (position >= this.length) {
  11226. return -1;
  11227. }
  11228. return position;
  11229. };
  11230. /**
  11231. * Returns whether an element is part of the active data.
  11232. * @param value defines the value to look for
  11233. * @returns true if found in the active data otherwise false
  11234. */
  11235. SmartArray.prototype.contains = function (value) {
  11236. return this.indexOf(value) !== -1;
  11237. };
  11238. // Statics
  11239. SmartArray._GlobalId = 0;
  11240. return SmartArray;
  11241. }());
  11242. BABYLON.SmartArray = SmartArray;
  11243. /**
  11244. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11245. * The data in this array can only be present once
  11246. */
  11247. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  11248. __extends(SmartArrayNoDuplicate, _super);
  11249. function SmartArrayNoDuplicate() {
  11250. var _this = _super !== null && _super.apply(this, arguments) || this;
  11251. _this._duplicateId = 0;
  11252. return _this;
  11253. }
  11254. /**
  11255. * Pushes a value at the end of the active data.
  11256. * THIS DOES NOT PREVENT DUPPLICATE DATA
  11257. * @param value defines the object to push in the array.
  11258. */
  11259. SmartArrayNoDuplicate.prototype.push = function (value) {
  11260. _super.prototype.push.call(this, value);
  11261. if (!value.__smartArrayFlags) {
  11262. value.__smartArrayFlags = {};
  11263. }
  11264. value.__smartArrayFlags[this._id] = this._duplicateId;
  11265. };
  11266. /**
  11267. * Pushes a value at the end of the active data.
  11268. * If the data is already present, it won t be added again
  11269. * @param value defines the object to push in the array.
  11270. * @returns true if added false if it was already present
  11271. */
  11272. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  11273. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  11274. return false;
  11275. }
  11276. this.push(value);
  11277. return true;
  11278. };
  11279. /**
  11280. * Resets the active data to an empty array.
  11281. */
  11282. SmartArrayNoDuplicate.prototype.reset = function () {
  11283. _super.prototype.reset.call(this);
  11284. this._duplicateId++;
  11285. };
  11286. /**
  11287. * Concats the active data with a given array.
  11288. * This ensures no dupplicate will be present in the result.
  11289. * @param array defines the data to concatenate with.
  11290. */
  11291. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  11292. if (array.length === 0) {
  11293. return;
  11294. }
  11295. if (this.length + array.length > this.data.length) {
  11296. this.data.length = (this.length + array.length) * 2;
  11297. }
  11298. for (var index = 0; index < array.length; index++) {
  11299. var item = (array.data || array)[index];
  11300. this.pushNoDuplicate(item);
  11301. }
  11302. };
  11303. return SmartArrayNoDuplicate;
  11304. }(SmartArray));
  11305. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  11306. })(BABYLON || (BABYLON = {}));
  11307. //# sourceMappingURL=babylon.smartArray.js.map
  11308. var BABYLON;
  11309. (function (BABYLON) {
  11310. var PromiseStates;
  11311. (function (PromiseStates) {
  11312. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11313. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11314. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11315. })(PromiseStates || (PromiseStates = {}));
  11316. var FulFillmentAgregator = /** @class */ (function () {
  11317. function FulFillmentAgregator() {
  11318. this.count = 0;
  11319. this.target = 0;
  11320. this.results = [];
  11321. }
  11322. return FulFillmentAgregator;
  11323. }());
  11324. var InternalPromise = /** @class */ (function () {
  11325. function InternalPromise(resolver) {
  11326. var _this = this;
  11327. this._state = PromiseStates.Pending;
  11328. this._children = new Array();
  11329. this._rejectWasConsumed = false;
  11330. if (!resolver) {
  11331. return;
  11332. }
  11333. try {
  11334. resolver(function (value) {
  11335. _this._resolve(value);
  11336. }, function (reason) {
  11337. _this._reject(reason);
  11338. });
  11339. }
  11340. catch (e) {
  11341. this._reject(e);
  11342. }
  11343. }
  11344. Object.defineProperty(InternalPromise.prototype, "_result", {
  11345. get: function () {
  11346. return this._resultValue;
  11347. },
  11348. set: function (value) {
  11349. this._resultValue = value;
  11350. if (this._parent && this._parent._result === undefined) {
  11351. this._parent._result = value;
  11352. }
  11353. },
  11354. enumerable: true,
  11355. configurable: true
  11356. });
  11357. InternalPromise.prototype.catch = function (onRejected) {
  11358. return this.then(undefined, onRejected);
  11359. };
  11360. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11361. var _this = this;
  11362. var newPromise = new InternalPromise();
  11363. newPromise._onFulfilled = onFulfilled;
  11364. newPromise._onRejected = onRejected;
  11365. // Composition
  11366. this._children.push(newPromise);
  11367. newPromise._parent = this;
  11368. if (this._state !== PromiseStates.Pending) {
  11369. BABYLON.Tools.SetImmediate(function () {
  11370. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11371. var returnedValue = newPromise._resolve(_this._result);
  11372. if (returnedValue !== undefined && returnedValue !== null) {
  11373. if (returnedValue._state !== undefined) {
  11374. var returnedPromise = returnedValue;
  11375. newPromise._children.push(returnedPromise);
  11376. returnedPromise._parent = newPromise;
  11377. newPromise = returnedPromise;
  11378. }
  11379. else {
  11380. newPromise._result = returnedValue;
  11381. }
  11382. }
  11383. }
  11384. else {
  11385. newPromise._reject(_this._reason);
  11386. }
  11387. });
  11388. }
  11389. return newPromise;
  11390. };
  11391. InternalPromise.prototype._moveChildren = function (children) {
  11392. var _this = this;
  11393. var _a;
  11394. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11395. this._children.forEach(function (child) {
  11396. child._parent = _this;
  11397. });
  11398. if (this._state === PromiseStates.Fulfilled) {
  11399. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11400. var child = _b[_i];
  11401. child._resolve(this._result);
  11402. }
  11403. }
  11404. else if (this._state === PromiseStates.Rejected) {
  11405. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11406. var child = _d[_c];
  11407. child._reject(this._reason);
  11408. }
  11409. }
  11410. };
  11411. InternalPromise.prototype._resolve = function (value) {
  11412. try {
  11413. this._state = PromiseStates.Fulfilled;
  11414. var returnedValue = null;
  11415. if (this._onFulfilled) {
  11416. returnedValue = this._onFulfilled(value);
  11417. }
  11418. if (returnedValue !== undefined && returnedValue !== null) {
  11419. if (returnedValue._state !== undefined) {
  11420. // Transmit children
  11421. var returnedPromise = returnedValue;
  11422. returnedPromise._parent = this;
  11423. returnedPromise._moveChildren(this._children);
  11424. value = returnedPromise._result;
  11425. }
  11426. else {
  11427. value = returnedValue;
  11428. }
  11429. }
  11430. this._result = value;
  11431. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11432. var child = _a[_i];
  11433. child._resolve(value);
  11434. }
  11435. this._children.length = 0;
  11436. delete this._onFulfilled;
  11437. delete this._onRejected;
  11438. }
  11439. catch (e) {
  11440. this._reject(e, true);
  11441. }
  11442. };
  11443. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11444. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11445. this._state = PromiseStates.Rejected;
  11446. this._reason = reason;
  11447. if (this._onRejected && !onLocalThrow) {
  11448. try {
  11449. this._onRejected(reason);
  11450. this._rejectWasConsumed = true;
  11451. }
  11452. catch (e) {
  11453. reason = e;
  11454. }
  11455. }
  11456. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11457. var child = _a[_i];
  11458. if (this._rejectWasConsumed) {
  11459. child._resolve(null);
  11460. }
  11461. else {
  11462. child._reject(reason);
  11463. }
  11464. }
  11465. this._children.length = 0;
  11466. delete this._onFulfilled;
  11467. delete this._onRejected;
  11468. };
  11469. InternalPromise.resolve = function (value) {
  11470. var newPromise = new InternalPromise();
  11471. newPromise._resolve(value);
  11472. return newPromise;
  11473. };
  11474. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11475. promise.then(function (value) {
  11476. agregator.results[index] = value;
  11477. agregator.count++;
  11478. if (agregator.count === agregator.target) {
  11479. agregator.rootPromise._resolve(agregator.results);
  11480. }
  11481. return null;
  11482. }, function (reason) {
  11483. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11484. agregator.rootPromise._reject(reason);
  11485. }
  11486. });
  11487. };
  11488. InternalPromise.all = function (promises) {
  11489. var newPromise = new InternalPromise();
  11490. var agregator = new FulFillmentAgregator();
  11491. agregator.target = promises.length;
  11492. agregator.rootPromise = newPromise;
  11493. if (promises.length) {
  11494. for (var index = 0; index < promises.length; index++) {
  11495. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11496. }
  11497. }
  11498. else {
  11499. newPromise._resolve([]);
  11500. }
  11501. return newPromise;
  11502. };
  11503. InternalPromise.race = function (promises) {
  11504. var newPromise = new InternalPromise();
  11505. if (promises.length) {
  11506. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11507. var promise = promises_1[_i];
  11508. promise.then(function (value) {
  11509. if (newPromise) {
  11510. newPromise._resolve(value);
  11511. newPromise = null;
  11512. }
  11513. return null;
  11514. }, function (reason) {
  11515. if (newPromise) {
  11516. newPromise._reject(reason);
  11517. newPromise = null;
  11518. }
  11519. });
  11520. }
  11521. }
  11522. return newPromise;
  11523. };
  11524. return InternalPromise;
  11525. }());
  11526. /**
  11527. * Helper class that provides a small promise polyfill
  11528. */
  11529. var PromisePolyfill = /** @class */ (function () {
  11530. function PromisePolyfill() {
  11531. }
  11532. /**
  11533. * Static function used to check if the polyfill is required
  11534. * If this is the case then the function will inject the polyfill to window.Promise
  11535. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11536. */
  11537. PromisePolyfill.Apply = function (force) {
  11538. if (force === void 0) { force = false; }
  11539. if (force || typeof Promise === 'undefined') {
  11540. var root = window;
  11541. root.Promise = InternalPromise;
  11542. }
  11543. };
  11544. return PromisePolyfill;
  11545. }());
  11546. BABYLON.PromisePolyfill = PromisePolyfill;
  11547. })(BABYLON || (BABYLON = {}));
  11548. //# sourceMappingURL=babylon.promise.js.map
  11549. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11550. var BABYLON;
  11551. (function (BABYLON) {
  11552. /**
  11553. * Helper class to push actions to a pool of workers.
  11554. */
  11555. var WorkerPool = /** @class */ (function () {
  11556. /**
  11557. * Constructor
  11558. * @param workers Array of workers to use for actions
  11559. */
  11560. function WorkerPool(workers) {
  11561. this._pendingActions = new Array();
  11562. this._workerInfos = workers.map(function (worker) { return ({
  11563. worker: worker,
  11564. active: false
  11565. }); });
  11566. }
  11567. /**
  11568. * Terminates all workers and clears any pending actions.
  11569. */
  11570. WorkerPool.prototype.dispose = function () {
  11571. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11572. var workerInfo = _a[_i];
  11573. workerInfo.worker.terminate();
  11574. }
  11575. delete this._workerInfos;
  11576. delete this._pendingActions;
  11577. };
  11578. /**
  11579. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11580. * pended until a worker has completed its action.
  11581. * @param action The action to perform. Call onComplete when the action is complete.
  11582. */
  11583. WorkerPool.prototype.push = function (action) {
  11584. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11585. var workerInfo = _a[_i];
  11586. if (!workerInfo.active) {
  11587. this._execute(workerInfo, action);
  11588. return;
  11589. }
  11590. }
  11591. this._pendingActions.push(action);
  11592. };
  11593. WorkerPool.prototype._execute = function (workerInfo, action) {
  11594. var _this = this;
  11595. workerInfo.active = true;
  11596. action(workerInfo.worker, function () {
  11597. workerInfo.active = false;
  11598. var nextAction = _this._pendingActions.shift();
  11599. if (nextAction) {
  11600. _this._execute(workerInfo, nextAction);
  11601. }
  11602. });
  11603. };
  11604. return WorkerPool;
  11605. }());
  11606. BABYLON.WorkerPool = WorkerPool;
  11607. })(BABYLON || (BABYLON = {}));
  11608. //# sourceMappingURL=babylon.workerPool.js.map
  11609. var BABYLON;
  11610. (function (BABYLON) {
  11611. /**
  11612. * @hidden
  11613. **/
  11614. var _AlphaState = /** @class */ (function () {
  11615. /**
  11616. * Initializes the state.
  11617. */
  11618. function _AlphaState() {
  11619. this._isAlphaBlendDirty = false;
  11620. this._isBlendFunctionParametersDirty = false;
  11621. this._isBlendEquationParametersDirty = false;
  11622. this._isBlendConstantsDirty = false;
  11623. this._alphaBlend = false;
  11624. this._blendFunctionParameters = new Array(4);
  11625. this._blendEquationParameters = new Array(2);
  11626. this._blendConstants = new Array(4);
  11627. this.reset();
  11628. }
  11629. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11630. get: function () {
  11631. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11637. get: function () {
  11638. return this._alphaBlend;
  11639. },
  11640. set: function (value) {
  11641. if (this._alphaBlend === value) {
  11642. return;
  11643. }
  11644. this._alphaBlend = value;
  11645. this._isAlphaBlendDirty = true;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11651. if (this._blendConstants[0] === r &&
  11652. this._blendConstants[1] === g &&
  11653. this._blendConstants[2] === b &&
  11654. this._blendConstants[3] === a) {
  11655. return;
  11656. }
  11657. this._blendConstants[0] = r;
  11658. this._blendConstants[1] = g;
  11659. this._blendConstants[2] = b;
  11660. this._blendConstants[3] = a;
  11661. this._isBlendConstantsDirty = true;
  11662. };
  11663. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11664. if (this._blendFunctionParameters[0] === value0 &&
  11665. this._blendFunctionParameters[1] === value1 &&
  11666. this._blendFunctionParameters[2] === value2 &&
  11667. this._blendFunctionParameters[3] === value3) {
  11668. return;
  11669. }
  11670. this._blendFunctionParameters[0] = value0;
  11671. this._blendFunctionParameters[1] = value1;
  11672. this._blendFunctionParameters[2] = value2;
  11673. this._blendFunctionParameters[3] = value3;
  11674. this._isBlendFunctionParametersDirty = true;
  11675. };
  11676. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11677. if (this._blendEquationParameters[0] === rgb &&
  11678. this._blendEquationParameters[1] === alpha) {
  11679. return;
  11680. }
  11681. this._blendEquationParameters[0] = rgb;
  11682. this._blendEquationParameters[1] = alpha;
  11683. this._isBlendEquationParametersDirty = true;
  11684. };
  11685. _AlphaState.prototype.reset = function () {
  11686. this._alphaBlend = false;
  11687. this._blendFunctionParameters[0] = null;
  11688. this._blendFunctionParameters[1] = null;
  11689. this._blendFunctionParameters[2] = null;
  11690. this._blendFunctionParameters[3] = null;
  11691. this._blendEquationParameters[0] = null;
  11692. this._blendEquationParameters[1] = null;
  11693. this._blendConstants[0] = null;
  11694. this._blendConstants[1] = null;
  11695. this._blendConstants[2] = null;
  11696. this._blendConstants[3] = null;
  11697. this._isAlphaBlendDirty = true;
  11698. this._isBlendFunctionParametersDirty = false;
  11699. this._isBlendEquationParametersDirty = false;
  11700. this._isBlendConstantsDirty = false;
  11701. };
  11702. _AlphaState.prototype.apply = function (gl) {
  11703. if (!this.isDirty) {
  11704. return;
  11705. }
  11706. // Alpha blend
  11707. if (this._isAlphaBlendDirty) {
  11708. if (this._alphaBlend) {
  11709. gl.enable(gl.BLEND);
  11710. }
  11711. else {
  11712. gl.disable(gl.BLEND);
  11713. }
  11714. this._isAlphaBlendDirty = false;
  11715. }
  11716. // Alpha function
  11717. if (this._isBlendFunctionParametersDirty) {
  11718. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11719. this._isBlendFunctionParametersDirty = false;
  11720. }
  11721. // Alpha equation
  11722. if (this._isBlendEquationParametersDirty) {
  11723. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11724. this._isBlendEquationParametersDirty = false;
  11725. }
  11726. // Constants
  11727. if (this._isBlendConstantsDirty) {
  11728. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11729. this._isBlendConstantsDirty = false;
  11730. }
  11731. };
  11732. return _AlphaState;
  11733. }());
  11734. BABYLON._AlphaState = _AlphaState;
  11735. })(BABYLON || (BABYLON = {}));
  11736. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11737. var BABYLON;
  11738. (function (BABYLON) {
  11739. /**
  11740. * @hidden
  11741. **/
  11742. var _DepthCullingState = /** @class */ (function () {
  11743. /**
  11744. * Initializes the state.
  11745. */
  11746. function _DepthCullingState() {
  11747. this._isDepthTestDirty = false;
  11748. this._isDepthMaskDirty = false;
  11749. this._isDepthFuncDirty = false;
  11750. this._isCullFaceDirty = false;
  11751. this._isCullDirty = false;
  11752. this._isZOffsetDirty = false;
  11753. this._isFrontFaceDirty = false;
  11754. this.reset();
  11755. }
  11756. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11757. get: function () {
  11758. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11764. get: function () {
  11765. return this._zOffset;
  11766. },
  11767. set: function (value) {
  11768. if (this._zOffset === value) {
  11769. return;
  11770. }
  11771. this._zOffset = value;
  11772. this._isZOffsetDirty = true;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11778. get: function () {
  11779. return this._cullFace;
  11780. },
  11781. set: function (value) {
  11782. if (this._cullFace === value) {
  11783. return;
  11784. }
  11785. this._cullFace = value;
  11786. this._isCullFaceDirty = true;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11792. get: function () {
  11793. return this._cull;
  11794. },
  11795. set: function (value) {
  11796. if (this._cull === value) {
  11797. return;
  11798. }
  11799. this._cull = value;
  11800. this._isCullDirty = true;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11806. get: function () {
  11807. return this._depthFunc;
  11808. },
  11809. set: function (value) {
  11810. if (this._depthFunc === value) {
  11811. return;
  11812. }
  11813. this._depthFunc = value;
  11814. this._isDepthFuncDirty = true;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11820. get: function () {
  11821. return this._depthMask;
  11822. },
  11823. set: function (value) {
  11824. if (this._depthMask === value) {
  11825. return;
  11826. }
  11827. this._depthMask = value;
  11828. this._isDepthMaskDirty = true;
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11834. get: function () {
  11835. return this._depthTest;
  11836. },
  11837. set: function (value) {
  11838. if (this._depthTest === value) {
  11839. return;
  11840. }
  11841. this._depthTest = value;
  11842. this._isDepthTestDirty = true;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11848. get: function () {
  11849. return this._frontFace;
  11850. },
  11851. set: function (value) {
  11852. if (this._frontFace === value) {
  11853. return;
  11854. }
  11855. this._frontFace = value;
  11856. this._isFrontFaceDirty = true;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. _DepthCullingState.prototype.reset = function () {
  11862. this._depthMask = true;
  11863. this._depthTest = true;
  11864. this._depthFunc = null;
  11865. this._cullFace = null;
  11866. this._cull = null;
  11867. this._zOffset = 0;
  11868. this._frontFace = null;
  11869. this._isDepthTestDirty = true;
  11870. this._isDepthMaskDirty = true;
  11871. this._isDepthFuncDirty = false;
  11872. this._isCullFaceDirty = false;
  11873. this._isCullDirty = false;
  11874. this._isZOffsetDirty = false;
  11875. this._isFrontFaceDirty = false;
  11876. };
  11877. _DepthCullingState.prototype.apply = function (gl) {
  11878. if (!this.isDirty) {
  11879. return;
  11880. }
  11881. // Cull
  11882. if (this._isCullDirty) {
  11883. if (this.cull) {
  11884. gl.enable(gl.CULL_FACE);
  11885. }
  11886. else {
  11887. gl.disable(gl.CULL_FACE);
  11888. }
  11889. this._isCullDirty = false;
  11890. }
  11891. // Cull face
  11892. if (this._isCullFaceDirty) {
  11893. gl.cullFace(this.cullFace);
  11894. this._isCullFaceDirty = false;
  11895. }
  11896. // Depth mask
  11897. if (this._isDepthMaskDirty) {
  11898. gl.depthMask(this.depthMask);
  11899. this._isDepthMaskDirty = false;
  11900. }
  11901. // Depth test
  11902. if (this._isDepthTestDirty) {
  11903. if (this.depthTest) {
  11904. gl.enable(gl.DEPTH_TEST);
  11905. }
  11906. else {
  11907. gl.disable(gl.DEPTH_TEST);
  11908. }
  11909. this._isDepthTestDirty = false;
  11910. }
  11911. // Depth func
  11912. if (this._isDepthFuncDirty) {
  11913. gl.depthFunc(this.depthFunc);
  11914. this._isDepthFuncDirty = false;
  11915. }
  11916. // zOffset
  11917. if (this._isZOffsetDirty) {
  11918. if (this.zOffset) {
  11919. gl.enable(gl.POLYGON_OFFSET_FILL);
  11920. gl.polygonOffset(this.zOffset, 0);
  11921. }
  11922. else {
  11923. gl.disable(gl.POLYGON_OFFSET_FILL);
  11924. }
  11925. this._isZOffsetDirty = false;
  11926. }
  11927. // Front face
  11928. if (this._isFrontFaceDirty) {
  11929. gl.frontFace(this.frontFace);
  11930. this._isFrontFaceDirty = false;
  11931. }
  11932. };
  11933. return _DepthCullingState;
  11934. }());
  11935. BABYLON._DepthCullingState = _DepthCullingState;
  11936. })(BABYLON || (BABYLON = {}));
  11937. //# sourceMappingURL=babylon.depthCullingState.js.map
  11938. var BABYLON;
  11939. (function (BABYLON) {
  11940. /**
  11941. * @hidden
  11942. **/
  11943. var _StencilState = /** @class */ (function () {
  11944. function _StencilState() {
  11945. this._isStencilTestDirty = false;
  11946. this._isStencilMaskDirty = false;
  11947. this._isStencilFuncDirty = false;
  11948. this._isStencilOpDirty = false;
  11949. this.reset();
  11950. }
  11951. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11952. get: function () {
  11953. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11954. },
  11955. enumerable: true,
  11956. configurable: true
  11957. });
  11958. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11959. get: function () {
  11960. return this._stencilFunc;
  11961. },
  11962. set: function (value) {
  11963. if (this._stencilFunc === value) {
  11964. return;
  11965. }
  11966. this._stencilFunc = value;
  11967. this._isStencilFuncDirty = true;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11973. get: function () {
  11974. return this._stencilFuncRef;
  11975. },
  11976. set: function (value) {
  11977. if (this._stencilFuncRef === value) {
  11978. return;
  11979. }
  11980. this._stencilFuncRef = value;
  11981. this._isStencilFuncDirty = true;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11987. get: function () {
  11988. return this._stencilFuncMask;
  11989. },
  11990. set: function (value) {
  11991. if (this._stencilFuncMask === value) {
  11992. return;
  11993. }
  11994. this._stencilFuncMask = value;
  11995. this._isStencilFuncDirty = true;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  12001. get: function () {
  12002. return this._stencilOpStencilFail;
  12003. },
  12004. set: function (value) {
  12005. if (this._stencilOpStencilFail === value) {
  12006. return;
  12007. }
  12008. this._stencilOpStencilFail = value;
  12009. this._isStencilOpDirty = true;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  12015. get: function () {
  12016. return this._stencilOpDepthFail;
  12017. },
  12018. set: function (value) {
  12019. if (this._stencilOpDepthFail === value) {
  12020. return;
  12021. }
  12022. this._stencilOpDepthFail = value;
  12023. this._isStencilOpDirty = true;
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  12029. get: function () {
  12030. return this._stencilOpStencilDepthPass;
  12031. },
  12032. set: function (value) {
  12033. if (this._stencilOpStencilDepthPass === value) {
  12034. return;
  12035. }
  12036. this._stencilOpStencilDepthPass = value;
  12037. this._isStencilOpDirty = true;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  12043. get: function () {
  12044. return this._stencilMask;
  12045. },
  12046. set: function (value) {
  12047. if (this._stencilMask === value) {
  12048. return;
  12049. }
  12050. this._stencilMask = value;
  12051. this._isStencilMaskDirty = true;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  12057. get: function () {
  12058. return this._stencilTest;
  12059. },
  12060. set: function (value) {
  12061. if (this._stencilTest === value) {
  12062. return;
  12063. }
  12064. this._stencilTest = value;
  12065. this._isStencilTestDirty = true;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. _StencilState.prototype.reset = function () {
  12071. this._stencilTest = false;
  12072. this._stencilMask = 0xFF;
  12073. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12074. this._stencilFuncRef = 1;
  12075. this._stencilFuncMask = 0xFF;
  12076. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12077. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12078. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12079. this._isStencilTestDirty = true;
  12080. this._isStencilMaskDirty = true;
  12081. this._isStencilFuncDirty = true;
  12082. this._isStencilOpDirty = true;
  12083. };
  12084. _StencilState.prototype.apply = function (gl) {
  12085. if (!this.isDirty) {
  12086. return;
  12087. }
  12088. // Stencil test
  12089. if (this._isStencilTestDirty) {
  12090. if (this.stencilTest) {
  12091. gl.enable(gl.STENCIL_TEST);
  12092. }
  12093. else {
  12094. gl.disable(gl.STENCIL_TEST);
  12095. }
  12096. this._isStencilTestDirty = false;
  12097. }
  12098. // Stencil mask
  12099. if (this._isStencilMaskDirty) {
  12100. gl.stencilMask(this.stencilMask);
  12101. this._isStencilMaskDirty = false;
  12102. }
  12103. // Stencil func
  12104. if (this._isStencilFuncDirty) {
  12105. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12106. this._isStencilFuncDirty = false;
  12107. }
  12108. // Stencil op
  12109. if (this._isStencilOpDirty) {
  12110. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12111. this._isStencilOpDirty = false;
  12112. }
  12113. };
  12114. return _StencilState;
  12115. }());
  12116. BABYLON._StencilState = _StencilState;
  12117. })(BABYLON || (BABYLON = {}));
  12118. //# sourceMappingURL=babylon.stencilState.js.map
  12119. var __assign = (this && this.__assign) || function () {
  12120. __assign = Object.assign || function(t) {
  12121. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12122. s = arguments[i];
  12123. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12124. t[p] = s[p];
  12125. }
  12126. return t;
  12127. };
  12128. return __assign.apply(this, arguments);
  12129. };
  12130. var BABYLON;
  12131. (function (BABYLON) {
  12132. /**
  12133. * Keeps track of all the buffer info used in engine.
  12134. */
  12135. var BufferPointer = /** @class */ (function () {
  12136. function BufferPointer() {
  12137. }
  12138. return BufferPointer;
  12139. }());
  12140. /**
  12141. * Interface for attribute information associated with buffer instanciation
  12142. */
  12143. var InstancingAttributeInfo = /** @class */ (function () {
  12144. function InstancingAttributeInfo() {
  12145. }
  12146. return InstancingAttributeInfo;
  12147. }());
  12148. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12149. /**
  12150. * Define options used to create a render target texture
  12151. */
  12152. var RenderTargetCreationOptions = /** @class */ (function () {
  12153. function RenderTargetCreationOptions() {
  12154. }
  12155. return RenderTargetCreationOptions;
  12156. }());
  12157. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12158. /**
  12159. * Define options used to create a depth texture
  12160. */
  12161. var DepthTextureCreationOptions = /** @class */ (function () {
  12162. function DepthTextureCreationOptions() {
  12163. }
  12164. return DepthTextureCreationOptions;
  12165. }());
  12166. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12167. /**
  12168. * Class used to describe the capabilities of the engine relatively to the current browser
  12169. */
  12170. var EngineCapabilities = /** @class */ (function () {
  12171. function EngineCapabilities() {
  12172. }
  12173. return EngineCapabilities;
  12174. }());
  12175. BABYLON.EngineCapabilities = EngineCapabilities;
  12176. /**
  12177. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12178. */
  12179. var Engine = /** @class */ (function () {
  12180. /**
  12181. * Creates a new engine
  12182. * @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
  12183. * @param antialias defines enable antialiasing (default: false)
  12184. * @param options defines further options to be sent to the getContext() function
  12185. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12186. */
  12187. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12188. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12189. var _this = this;
  12190. // Public members
  12191. /**
  12192. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12193. */
  12194. this.forcePOTTextures = false;
  12195. /**
  12196. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12197. */
  12198. this.isFullscreen = false;
  12199. /**
  12200. * Gets a boolean indicating if the pointer is currently locked
  12201. */
  12202. this.isPointerLock = false;
  12203. /**
  12204. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12205. */
  12206. this.cullBackFaces = true;
  12207. /**
  12208. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12209. */
  12210. this.renderEvenInBackground = true;
  12211. /**
  12212. * Gets or sets a boolean indicating that cache can be kept between frames
  12213. */
  12214. this.preventCacheWipeBetweenFrames = false;
  12215. /**
  12216. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12217. **/
  12218. this.enableOfflineSupport = false;
  12219. /**
  12220. * 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)
  12221. **/
  12222. this.disableManifestCheck = false;
  12223. /**
  12224. * Gets the list of created scenes
  12225. */
  12226. this.scenes = new Array();
  12227. /**
  12228. * Gets the list of created postprocesses
  12229. */
  12230. this.postProcesses = new Array();
  12231. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12232. this.validateShaderPrograms = false;
  12233. // Observables
  12234. /**
  12235. * Observable event triggered each time the rendering canvas is resized
  12236. */
  12237. this.onResizeObservable = new BABYLON.Observable();
  12238. /**
  12239. * Observable event triggered each time the canvas loses focus
  12240. */
  12241. this.onCanvasBlurObservable = new BABYLON.Observable();
  12242. /**
  12243. * Observable event triggered each time the canvas gains focus
  12244. */
  12245. this.onCanvasFocusObservable = new BABYLON.Observable();
  12246. /**
  12247. * Observable event triggered each time the canvas receives pointerout event
  12248. */
  12249. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12250. /**
  12251. * Observable event triggered before each texture is initialized
  12252. */
  12253. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12254. //WebVR
  12255. this._vrDisplay = undefined;
  12256. this._vrSupported = false;
  12257. this._vrExclusivePointerMode = false;
  12258. // Uniform buffers list
  12259. /**
  12260. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12261. */
  12262. this.disableUniformBuffers = false;
  12263. /** @hidden */
  12264. this._uniformBuffers = new Array();
  12265. // Observables
  12266. /**
  12267. * Observable raised when the engine begins a new frame
  12268. */
  12269. this.onBeginFrameObservable = new BABYLON.Observable();
  12270. /**
  12271. * If set, will be used to request the next animation frame for the render loop
  12272. */
  12273. this.customAnimationFrameRequester = null;
  12274. /**
  12275. * Observable raised when the engine ends the current frame
  12276. */
  12277. this.onEndFrameObservable = new BABYLON.Observable();
  12278. /**
  12279. * Observable raised when the engine is about to compile a shader
  12280. */
  12281. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12282. /**
  12283. * Observable raised when the engine has jsut compiled a shader
  12284. */
  12285. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12286. this._windowIsBackground = false;
  12287. this._webGLVersion = 1.0;
  12288. /** @hidden */
  12289. this._badOS = false;
  12290. /** @hidden */
  12291. this._badDesktopOS = false;
  12292. /**
  12293. * Gets or sets a value indicating if we want to disable texture binding optimization.
  12294. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12295. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12296. */
  12297. this.disableTextureBindingOptimization = false;
  12298. /**
  12299. * Observable signaled when VR display mode changes
  12300. */
  12301. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12302. /**
  12303. * Observable signaled when VR request present is complete
  12304. */
  12305. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12306. /**
  12307. * Observable signaled when VR request present starts
  12308. */
  12309. this.onVRRequestPresentStart = new BABYLON.Observable();
  12310. this._colorWrite = true;
  12311. /** @hidden */
  12312. this._drawCalls = new BABYLON.PerfCounter();
  12313. /** @hidden */
  12314. this._textureCollisions = new BABYLON.PerfCounter();
  12315. this._renderingQueueLaunched = false;
  12316. this._activeRenderLoops = new Array();
  12317. // Deterministic lockstepMaxSteps
  12318. this._deterministicLockstep = false;
  12319. this._lockstepMaxSteps = 4;
  12320. // Lost context
  12321. /**
  12322. * Observable signaled when a context lost event is raised
  12323. */
  12324. this.onContextLostObservable = new BABYLON.Observable();
  12325. /**
  12326. * Observable signaled when a context restored event is raised
  12327. */
  12328. this.onContextRestoredObservable = new BABYLON.Observable();
  12329. this._contextWasLost = false;
  12330. this._doNotHandleContextLost = false;
  12331. // FPS
  12332. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12333. this._fps = 60;
  12334. this._deltaTime = 0;
  12335. /**
  12336. * Turn this value on if you want to pause FPS computation when in background
  12337. */
  12338. this.disablePerformanceMonitorInBackground = false;
  12339. // States
  12340. /** @hidden */
  12341. this._depthCullingState = new BABYLON._DepthCullingState();
  12342. /** @hidden */
  12343. this._stencilState = new BABYLON._StencilState();
  12344. /** @hidden */
  12345. this._alphaState = new BABYLON._AlphaState();
  12346. /** @hidden */
  12347. this._alphaMode = Engine.ALPHA_DISABLE;
  12348. // Cache
  12349. this._internalTexturesCache = new Array();
  12350. /** @hidden */
  12351. this._activeChannel = 0;
  12352. this._currentTextureChannel = -1;
  12353. /** @hidden */
  12354. this._boundTexturesCache = {};
  12355. this._compiledEffects = {};
  12356. this._vertexAttribArraysEnabled = [];
  12357. this._uintIndicesCurrentlySet = false;
  12358. this._currentBoundBuffer = new Array();
  12359. /** @hidden */
  12360. this._currentFramebuffer = null;
  12361. this._currentBufferPointers = new Array();
  12362. this._currentInstanceLocations = new Array();
  12363. this._currentInstanceBuffers = new Array();
  12364. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12365. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12366. this._vaoRecordInProgress = false;
  12367. this._mustWipeVertexAttributes = false;
  12368. this._nextFreeTextureSlots = new Array();
  12369. this._maxSimultaneousTextures = 0;
  12370. this._activeRequests = new Array();
  12371. // Hardware supported Compressed Textures
  12372. this._texturesSupported = new Array();
  12373. /**
  12374. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12375. */
  12376. this.premultipliedAlpha = true;
  12377. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12378. this._onVRFullScreenTriggered = function () {
  12379. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12380. //get the old size before we change
  12381. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12382. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12383. //get the width and height, change the render size
  12384. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12385. _this.setHardwareScalingLevel(1);
  12386. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12387. }
  12388. else {
  12389. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12390. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12391. }
  12392. };
  12393. this._unpackFlipYCached = null;
  12394. /**
  12395. * In case you are sharing the context with other applications, it might
  12396. * be interested to not cache the unpack flip y state to ensure a consistent
  12397. * value would be set.
  12398. */
  12399. this.enableUnpackFlipYCached = true;
  12400. this._boundUniforms = {};
  12401. // Register promises
  12402. BABYLON.PromisePolyfill.Apply();
  12403. var canvas = null;
  12404. Engine.Instances.push(this);
  12405. if (!canvasOrContext) {
  12406. return;
  12407. }
  12408. options = options || {};
  12409. if (canvasOrContext.getContext) {
  12410. canvas = canvasOrContext;
  12411. this._renderingCanvas = canvas;
  12412. if (antialias != null) {
  12413. options.antialias = antialias;
  12414. }
  12415. if (options.deterministicLockstep === undefined) {
  12416. options.deterministicLockstep = false;
  12417. }
  12418. if (options.lockstepMaxSteps === undefined) {
  12419. options.lockstepMaxSteps = 4;
  12420. }
  12421. if (options.preserveDrawingBuffer === undefined) {
  12422. options.preserveDrawingBuffer = false;
  12423. }
  12424. if (options.audioEngine === undefined) {
  12425. options.audioEngine = true;
  12426. }
  12427. if (options.stencil === undefined) {
  12428. options.stencil = true;
  12429. }
  12430. if (options.premultipliedAlpha === false) {
  12431. this.premultipliedAlpha = false;
  12432. }
  12433. this._deterministicLockstep = options.deterministicLockstep;
  12434. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12435. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12436. // Exceptions
  12437. if (navigator && navigator.userAgent) {
  12438. var ua = navigator.userAgent;
  12439. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12440. var exception = _a[_i];
  12441. var key = exception.key;
  12442. var targets = exception.targets;
  12443. if (ua.indexOf(key) > -1) {
  12444. if (exception.capture && exception.captureConstraint) {
  12445. var capture = exception.capture;
  12446. var constraint = exception.captureConstraint;
  12447. var regex = new RegExp(capture);
  12448. var matches = regex.exec(ua);
  12449. if (matches && matches.length > 0) {
  12450. var capturedValue = parseInt(matches[matches.length - 1]);
  12451. if (capturedValue >= constraint) {
  12452. continue;
  12453. }
  12454. }
  12455. }
  12456. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12457. var target = targets_1[_b];
  12458. switch (target) {
  12459. case "uniformBuffer":
  12460. this.disableUniformBuffers = true;
  12461. break;
  12462. case "textureBindingOptimization":
  12463. this.disableTextureBindingOptimization = true;
  12464. break;
  12465. }
  12466. }
  12467. }
  12468. }
  12469. }
  12470. // GL
  12471. if (!options.disableWebGL2Support) {
  12472. try {
  12473. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12474. if (this._gl) {
  12475. this._webGLVersion = 2.0;
  12476. // Prevent weird browsers to lie :-)
  12477. if (!this._gl.deleteQuery) {
  12478. this._webGLVersion = 1.0;
  12479. }
  12480. }
  12481. }
  12482. catch (e) {
  12483. // Do nothing
  12484. }
  12485. }
  12486. if (!this._gl) {
  12487. if (!canvas) {
  12488. throw new Error("The provided canvas is null or undefined.");
  12489. }
  12490. try {
  12491. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12492. }
  12493. catch (e) {
  12494. throw new Error("WebGL not supported");
  12495. }
  12496. }
  12497. if (!this._gl) {
  12498. throw new Error("WebGL not supported");
  12499. }
  12500. this._onCanvasFocus = function () {
  12501. _this.onCanvasFocusObservable.notifyObservers(_this);
  12502. };
  12503. this._onCanvasBlur = function () {
  12504. _this.onCanvasBlurObservable.notifyObservers(_this);
  12505. };
  12506. canvas.addEventListener("focus", this._onCanvasFocus);
  12507. canvas.addEventListener("blur", this._onCanvasBlur);
  12508. this._onBlur = function () {
  12509. if (_this.disablePerformanceMonitorInBackground) {
  12510. _this._performanceMonitor.disable();
  12511. }
  12512. _this._windowIsBackground = true;
  12513. };
  12514. this._onFocus = function () {
  12515. if (_this.disablePerformanceMonitorInBackground) {
  12516. _this._performanceMonitor.enable();
  12517. }
  12518. _this._windowIsBackground = false;
  12519. };
  12520. this._onCanvasPointerOut = function (ev) {
  12521. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12522. };
  12523. window.addEventListener("blur", this._onBlur);
  12524. window.addEventListener("focus", this._onFocus);
  12525. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12526. // Context lost
  12527. if (!this._doNotHandleContextLost) {
  12528. this._onContextLost = function (evt) {
  12529. evt.preventDefault();
  12530. _this._contextWasLost = true;
  12531. BABYLON.Tools.Warn("WebGL context lost.");
  12532. _this.onContextLostObservable.notifyObservers(_this);
  12533. };
  12534. this._onContextRestored = function (evt) {
  12535. // Adding a timeout to avoid race condition at browser level
  12536. setTimeout(function () {
  12537. // Rebuild gl context
  12538. _this._initGLContext();
  12539. // Rebuild effects
  12540. _this._rebuildEffects();
  12541. // Rebuild textures
  12542. _this._rebuildInternalTextures();
  12543. // Rebuild buffers
  12544. _this._rebuildBuffers();
  12545. // Cache
  12546. _this.wipeCaches(true);
  12547. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12548. _this.onContextRestoredObservable.notifyObservers(_this);
  12549. _this._contextWasLost = false;
  12550. }, 0);
  12551. };
  12552. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12553. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12554. }
  12555. }
  12556. else {
  12557. this._gl = canvasOrContext;
  12558. this._renderingCanvas = this._gl.canvas;
  12559. if (this._gl.renderbufferStorageMultisample) {
  12560. this._webGLVersion = 2.0;
  12561. }
  12562. var attributes = this._gl.getContextAttributes();
  12563. if (attributes) {
  12564. options.stencil = attributes.stencil;
  12565. }
  12566. }
  12567. // Viewport
  12568. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12569. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12570. this.resize();
  12571. this._isStencilEnable = options.stencil ? true : false;
  12572. this._initGLContext();
  12573. if (canvas) {
  12574. // Fullscreen
  12575. this._onFullscreenChange = function () {
  12576. if (document.fullscreen !== undefined) {
  12577. _this.isFullscreen = document.fullscreen;
  12578. }
  12579. else if (document.mozFullScreen !== undefined) {
  12580. _this.isFullscreen = document.mozFullScreen;
  12581. }
  12582. else if (document.webkitIsFullScreen !== undefined) {
  12583. _this.isFullscreen = document.webkitIsFullScreen;
  12584. }
  12585. else if (document.msIsFullScreen !== undefined) {
  12586. _this.isFullscreen = document.msIsFullScreen;
  12587. }
  12588. // Pointer lock
  12589. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12590. canvas.requestPointerLock = canvas.requestPointerLock ||
  12591. canvas.msRequestPointerLock ||
  12592. canvas.mozRequestPointerLock ||
  12593. canvas.webkitRequestPointerLock;
  12594. if (canvas.requestPointerLock) {
  12595. canvas.requestPointerLock();
  12596. }
  12597. }
  12598. };
  12599. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12600. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12601. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12602. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12603. // Pointer lock
  12604. this._onPointerLockChange = function () {
  12605. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12606. document.webkitPointerLockElement === canvas ||
  12607. document.msPointerLockElement === canvas ||
  12608. document.pointerLockElement === canvas);
  12609. };
  12610. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12611. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12612. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12613. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12614. this._onVRDisplayPointerRestricted = function () {
  12615. if (canvas) {
  12616. canvas.requestPointerLock();
  12617. }
  12618. };
  12619. this._onVRDisplayPointerUnrestricted = function () {
  12620. document.exitPointerLock();
  12621. };
  12622. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12623. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12624. }
  12625. // Create Audio Engine if needed.
  12626. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12627. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12628. }
  12629. // Prepare buffer pointers
  12630. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12631. this._currentBufferPointers[i] = new BufferPointer();
  12632. }
  12633. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12634. // Load WebVR Devices
  12635. if (options.autoEnableWebVR) {
  12636. this.initWebVR();
  12637. }
  12638. // Detect if we are running on a faulty buggy OS.
  12639. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12640. // Detect if we are running on a faulty buggy desktop OS.
  12641. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12642. console.log("Babylon.js v" + Engine.Version + " - " + this.description);
  12643. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  12644. }
  12645. Object.defineProperty(Engine, "LastCreatedEngine", {
  12646. /**
  12647. * Gets the latest created engine
  12648. */
  12649. get: function () {
  12650. if (Engine.Instances.length === 0) {
  12651. return null;
  12652. }
  12653. return Engine.Instances[Engine.Instances.length - 1];
  12654. },
  12655. enumerable: true,
  12656. configurable: true
  12657. });
  12658. Object.defineProperty(Engine, "LastCreatedScene", {
  12659. /**
  12660. * Gets the latest created scene
  12661. */
  12662. get: function () {
  12663. var lastCreatedEngine = Engine.LastCreatedEngine;
  12664. if (!lastCreatedEngine) {
  12665. return null;
  12666. }
  12667. if (lastCreatedEngine.scenes.length === 0) {
  12668. return null;
  12669. }
  12670. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12671. },
  12672. enumerable: true,
  12673. configurable: true
  12674. });
  12675. /**
  12676. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12677. * @param flag defines which part of the materials must be marked as dirty
  12678. * @param predicate defines a predicate used to filter which materials should be affected
  12679. */
  12680. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12681. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12682. var engine = Engine.Instances[engineIndex];
  12683. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12684. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12685. }
  12686. }
  12687. };
  12688. Object.defineProperty(Engine, "Version", {
  12689. /**
  12690. * Returns the current version of the framework
  12691. */
  12692. get: function () {
  12693. return "4.0.0-alpha.2";
  12694. },
  12695. enumerable: true,
  12696. configurable: true
  12697. });
  12698. Object.defineProperty(Engine.prototype, "description", {
  12699. /**
  12700. * Returns a string describing the current engine
  12701. */
  12702. get: function () {
  12703. var description = "WebGL" + this.webGLVersion;
  12704. if (this._caps.parallelShaderCompile) {
  12705. description += " - Parallel shader compilation";
  12706. }
  12707. return description;
  12708. },
  12709. enumerable: true,
  12710. configurable: true
  12711. });
  12712. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12713. /**
  12714. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12715. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12716. */
  12717. get: function () {
  12718. return this._vrExclusivePointerMode;
  12719. },
  12720. enumerable: true,
  12721. configurable: true
  12722. });
  12723. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12724. /**
  12725. * Gets a boolean indicating that the engine supports uniform buffers
  12726. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12727. */
  12728. get: function () {
  12729. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12730. },
  12731. enumerable: true,
  12732. configurable: true
  12733. });
  12734. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12735. /**
  12736. * Gets a boolean indicating that only power of 2 textures are supported
  12737. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12738. */
  12739. get: function () {
  12740. return this._webGLVersion < 2 || this.forcePOTTextures;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12746. /**
  12747. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12748. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12749. */
  12750. get: function () {
  12751. return this._doNotHandleContextLost;
  12752. },
  12753. set: function (value) {
  12754. this._doNotHandleContextLost = value;
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12760. /**
  12761. * Gets the performance monitor attached to this engine
  12762. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12763. */
  12764. get: function () {
  12765. return this._performanceMonitor;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12771. /**
  12772. * Gets the list of texture formats supported
  12773. */
  12774. get: function () {
  12775. return this._texturesSupported;
  12776. },
  12777. enumerable: true,
  12778. configurable: true
  12779. });
  12780. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12781. /**
  12782. * Gets the list of texture formats in use
  12783. */
  12784. get: function () {
  12785. return this._textureFormatInUse;
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. Object.defineProperty(Engine.prototype, "currentViewport", {
  12791. /**
  12792. * Gets the current viewport
  12793. */
  12794. get: function () {
  12795. return this._cachedViewport;
  12796. },
  12797. enumerable: true,
  12798. configurable: true
  12799. });
  12800. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12801. /**
  12802. * Gets the default empty texture
  12803. */
  12804. get: function () {
  12805. if (!this._emptyTexture) {
  12806. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12807. }
  12808. return this._emptyTexture;
  12809. },
  12810. enumerable: true,
  12811. configurable: true
  12812. });
  12813. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12814. /**
  12815. * Gets the default empty 3D texture
  12816. */
  12817. get: function () {
  12818. if (!this._emptyTexture3D) {
  12819. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12820. }
  12821. return this._emptyTexture3D;
  12822. },
  12823. enumerable: true,
  12824. configurable: true
  12825. });
  12826. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12827. /**
  12828. * Gets the default empty cube texture
  12829. */
  12830. get: function () {
  12831. if (!this._emptyCubeTexture) {
  12832. var faceData = new Uint8Array(4);
  12833. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12834. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12835. }
  12836. return this._emptyCubeTexture;
  12837. },
  12838. enumerable: true,
  12839. configurable: true
  12840. });
  12841. Engine.prototype._rebuildInternalTextures = function () {
  12842. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12843. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12844. var internalTexture = currentState_1[_i];
  12845. internalTexture._rebuild();
  12846. }
  12847. };
  12848. Engine.prototype._rebuildEffects = function () {
  12849. for (var key in this._compiledEffects) {
  12850. var effect = this._compiledEffects[key];
  12851. effect._prepareEffect();
  12852. }
  12853. BABYLON.Effect.ResetCache();
  12854. };
  12855. /**
  12856. * Gets a boolean indicating if all created effects are ready
  12857. * @returns true if all effects are ready
  12858. */
  12859. Engine.prototype.areAllEffectsReady = function () {
  12860. for (var key in this._compiledEffects) {
  12861. var effect = this._compiledEffects[key];
  12862. if (!effect.isReady()) {
  12863. return false;
  12864. }
  12865. }
  12866. return true;
  12867. };
  12868. Engine.prototype._rebuildBuffers = function () {
  12869. // Index / Vertex
  12870. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12871. var scene = _a[_i];
  12872. scene.resetCachedMaterial();
  12873. scene._rebuildGeometries();
  12874. scene._rebuildTextures();
  12875. }
  12876. // Uniforms
  12877. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12878. var uniformBuffer = _c[_b];
  12879. uniformBuffer._rebuild();
  12880. }
  12881. };
  12882. Engine.prototype._initGLContext = function () {
  12883. // Caps
  12884. this._caps = new EngineCapabilities();
  12885. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12886. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12887. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12888. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12889. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12890. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12891. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12892. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12893. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12894. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12895. // Infos
  12896. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12897. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12898. if (rendererInfo != null) {
  12899. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12900. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12901. }
  12902. if (!this._glVendor) {
  12903. this._glVendor = "Unknown vendor";
  12904. }
  12905. if (!this._glRenderer) {
  12906. this._glRenderer = "Unknown renderer";
  12907. }
  12908. // Constants
  12909. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12910. if (this._gl.RGBA16F !== 0x881A) {
  12911. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12912. }
  12913. if (this._gl.RGBA32F !== 0x8814) {
  12914. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12915. }
  12916. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12917. this._gl.DEPTH24_STENCIL8 = 35056;
  12918. }
  12919. // Extensions
  12920. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12921. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12922. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12923. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12924. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12925. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12926. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12927. 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');
  12928. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12929. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12930. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12931. this._caps.highPrecisionShaderSupported = true;
  12932. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12933. if (this._caps.timerQuery) {
  12934. if (this._webGLVersion === 1) {
  12935. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12936. }
  12937. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12938. }
  12939. // Checks if some of the format renders first to allow the use of webgl inspector.
  12940. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12941. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12942. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12943. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12944. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12945. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12946. if (this._webGLVersion > 1) {
  12947. this._gl.HALF_FLOAT_OES = 0x140B;
  12948. }
  12949. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12950. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12951. // Draw buffers
  12952. if (this._webGLVersion > 1) {
  12953. this._caps.drawBuffersExtension = true;
  12954. }
  12955. else {
  12956. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12957. if (drawBuffersExtension !== null) {
  12958. this._caps.drawBuffersExtension = true;
  12959. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12960. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12961. for (var i = 0; i < 16; i++) {
  12962. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12963. }
  12964. }
  12965. else {
  12966. this._caps.drawBuffersExtension = false;
  12967. }
  12968. }
  12969. // Shader compiler threads
  12970. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  12971. if (this._caps.parallelShaderCompile) {
  12972. var threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  12973. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  12974. }
  12975. // Depth Texture
  12976. if (this._webGLVersion > 1) {
  12977. this._caps.depthTextureExtension = true;
  12978. }
  12979. else {
  12980. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12981. if (depthTextureExtension != null) {
  12982. this._caps.depthTextureExtension = true;
  12983. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12984. }
  12985. }
  12986. // Vertex array object
  12987. if (this._webGLVersion > 1) {
  12988. this._caps.vertexArrayObject = true;
  12989. }
  12990. else {
  12991. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12992. if (vertexArrayObjectExtension != null) {
  12993. this._caps.vertexArrayObject = true;
  12994. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12995. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12996. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12997. }
  12998. else {
  12999. this._caps.vertexArrayObject = false;
  13000. }
  13001. }
  13002. // Instances count
  13003. if (this._webGLVersion > 1) {
  13004. this._caps.instancedArrays = true;
  13005. }
  13006. else {
  13007. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  13008. if (instanceExtension != null) {
  13009. this._caps.instancedArrays = true;
  13010. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  13011. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  13012. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  13013. }
  13014. else {
  13015. this._caps.instancedArrays = false;
  13016. }
  13017. }
  13018. // Intelligently add supported compressed formats in order to check for.
  13019. // Check for ASTC support first as it is most powerful and to be very cross platform.
  13020. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  13021. // Likely no hardware which supports both PVR & DXT, so order matters little.
  13022. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  13023. if (this._caps.astc) {
  13024. this.texturesSupported.push('-astc.ktx');
  13025. }
  13026. if (this._caps.s3tc) {
  13027. this.texturesSupported.push('-dxt.ktx');
  13028. }
  13029. if (this._caps.pvrtc) {
  13030. this.texturesSupported.push('-pvrtc.ktx');
  13031. }
  13032. if (this._caps.etc2) {
  13033. this.texturesSupported.push('-etc2.ktx');
  13034. }
  13035. if (this._caps.etc1) {
  13036. this.texturesSupported.push('-etc1.ktx');
  13037. }
  13038. if (this._gl.getShaderPrecisionFormat) {
  13039. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  13040. if (highp) {
  13041. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  13042. }
  13043. }
  13044. // Depth buffer
  13045. this.setDepthBuffer(true);
  13046. this.setDepthFunctionToLessOrEqual();
  13047. this.setDepthWrite(true);
  13048. // Texture maps
  13049. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  13050. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13051. this._nextFreeTextureSlots.push(slot);
  13052. }
  13053. };
  13054. Object.defineProperty(Engine.prototype, "webGLVersion", {
  13055. /**
  13056. * Gets version of the current webGL context
  13057. */
  13058. get: function () {
  13059. return this._webGLVersion;
  13060. },
  13061. enumerable: true,
  13062. configurable: true
  13063. });
  13064. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  13065. /**
  13066. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  13067. */
  13068. get: function () {
  13069. return this._isStencilEnable;
  13070. },
  13071. enumerable: true,
  13072. configurable: true
  13073. });
  13074. Engine.prototype._prepareWorkingCanvas = function () {
  13075. if (this._workingCanvas) {
  13076. return;
  13077. }
  13078. this._workingCanvas = document.createElement("canvas");
  13079. var context = this._workingCanvas.getContext("2d");
  13080. if (context) {
  13081. this._workingContext = context;
  13082. }
  13083. };
  13084. /**
  13085. * Reset the texture cache to empty state
  13086. */
  13087. Engine.prototype.resetTextureCache = function () {
  13088. for (var key in this._boundTexturesCache) {
  13089. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13090. continue;
  13091. }
  13092. var boundTexture = this._boundTexturesCache[key];
  13093. if (boundTexture) {
  13094. this._removeDesignatedSlot(boundTexture);
  13095. }
  13096. this._boundTexturesCache[key] = null;
  13097. }
  13098. if (!this.disableTextureBindingOptimization) {
  13099. this._nextFreeTextureSlots = [];
  13100. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13101. this._nextFreeTextureSlots.push(slot);
  13102. }
  13103. }
  13104. this._currentTextureChannel = -1;
  13105. };
  13106. /**
  13107. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13108. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13109. * @returns true if engine is in deterministic lock step mode
  13110. */
  13111. Engine.prototype.isDeterministicLockStep = function () {
  13112. return this._deterministicLockstep;
  13113. };
  13114. /**
  13115. * Gets the max steps when engine is running in deterministic lock step
  13116. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13117. * @returns the max steps
  13118. */
  13119. Engine.prototype.getLockstepMaxSteps = function () {
  13120. return this._lockstepMaxSteps;
  13121. };
  13122. /**
  13123. * Gets an object containing information about the current webGL context
  13124. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13125. */
  13126. Engine.prototype.getGlInfo = function () {
  13127. return {
  13128. vendor: this._glVendor,
  13129. renderer: this._glRenderer,
  13130. version: this._glVersion
  13131. };
  13132. };
  13133. /**
  13134. * Gets current aspect ratio
  13135. * @param camera defines the camera to use to get the aspect ratio
  13136. * @param useScreen defines if screen size must be used (or the current render target if any)
  13137. * @returns a number defining the aspect ratio
  13138. */
  13139. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13140. if (useScreen === void 0) { useScreen = false; }
  13141. var viewport = camera.viewport;
  13142. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13143. };
  13144. /**
  13145. * Gets current screen aspect ratio
  13146. * @returns a number defining the aspect ratio
  13147. */
  13148. Engine.prototype.getScreenAspectRatio = function () {
  13149. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13150. };
  13151. /**
  13152. * Gets the current render width
  13153. * @param useScreen defines if screen size must be used (or the current render target if any)
  13154. * @returns a number defining the current render width
  13155. */
  13156. Engine.prototype.getRenderWidth = function (useScreen) {
  13157. if (useScreen === void 0) { useScreen = false; }
  13158. if (!useScreen && this._currentRenderTarget) {
  13159. return this._currentRenderTarget.width;
  13160. }
  13161. return this._gl.drawingBufferWidth;
  13162. };
  13163. /**
  13164. * Gets the current render height
  13165. * @param useScreen defines if screen size must be used (or the current render target if any)
  13166. * @returns a number defining the current render height
  13167. */
  13168. Engine.prototype.getRenderHeight = function (useScreen) {
  13169. if (useScreen === void 0) { useScreen = false; }
  13170. if (!useScreen && this._currentRenderTarget) {
  13171. return this._currentRenderTarget.height;
  13172. }
  13173. return this._gl.drawingBufferHeight;
  13174. };
  13175. /**
  13176. * Gets the HTML canvas attached with the current webGL context
  13177. * @returns a HTML canvas
  13178. */
  13179. Engine.prototype.getRenderingCanvas = function () {
  13180. return this._renderingCanvas;
  13181. };
  13182. /**
  13183. * Gets the client rect of the HTML canvas attached with the current webGL context
  13184. * @returns a client rectanglee
  13185. */
  13186. Engine.prototype.getRenderingCanvasClientRect = function () {
  13187. if (!this._renderingCanvas) {
  13188. return null;
  13189. }
  13190. return this._renderingCanvas.getBoundingClientRect();
  13191. };
  13192. /**
  13193. * Defines the hardware scaling level.
  13194. * By default the hardware scaling level is computed from the window device ratio.
  13195. * 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.
  13196. * @param level defines the level to use
  13197. */
  13198. Engine.prototype.setHardwareScalingLevel = function (level) {
  13199. this._hardwareScalingLevel = level;
  13200. this.resize();
  13201. };
  13202. /**
  13203. * Gets the current hardware scaling level.
  13204. * By default the hardware scaling level is computed from the window device ratio.
  13205. * 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.
  13206. * @returns a number indicating the current hardware scaling level
  13207. */
  13208. Engine.prototype.getHardwareScalingLevel = function () {
  13209. return this._hardwareScalingLevel;
  13210. };
  13211. /**
  13212. * Gets the list of loaded textures
  13213. * @returns an array containing all loaded textures
  13214. */
  13215. Engine.prototype.getLoadedTexturesCache = function () {
  13216. return this._internalTexturesCache;
  13217. };
  13218. /**
  13219. * Gets the object containing all engine capabilities
  13220. * @returns the EngineCapabilities object
  13221. */
  13222. Engine.prototype.getCaps = function () {
  13223. return this._caps;
  13224. };
  13225. Object.defineProperty(Engine.prototype, "drawCalls", {
  13226. /** @hidden */
  13227. get: function () {
  13228. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13229. return 0;
  13230. },
  13231. enumerable: true,
  13232. configurable: true
  13233. });
  13234. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13235. /** @hidden */
  13236. get: function () {
  13237. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13238. return null;
  13239. },
  13240. enumerable: true,
  13241. configurable: true
  13242. });
  13243. /**
  13244. * Gets the current depth function
  13245. * @returns a number defining the depth function
  13246. */
  13247. Engine.prototype.getDepthFunction = function () {
  13248. return this._depthCullingState.depthFunc;
  13249. };
  13250. /**
  13251. * Sets the current depth function
  13252. * @param depthFunc defines the function to use
  13253. */
  13254. Engine.prototype.setDepthFunction = function (depthFunc) {
  13255. this._depthCullingState.depthFunc = depthFunc;
  13256. };
  13257. /**
  13258. * Sets the current depth function to GREATER
  13259. */
  13260. Engine.prototype.setDepthFunctionToGreater = function () {
  13261. this._depthCullingState.depthFunc = this._gl.GREATER;
  13262. };
  13263. /**
  13264. * Sets the current depth function to GEQUAL
  13265. */
  13266. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13267. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13268. };
  13269. /**
  13270. * Sets the current depth function to LESS
  13271. */
  13272. Engine.prototype.setDepthFunctionToLess = function () {
  13273. this._depthCullingState.depthFunc = this._gl.LESS;
  13274. };
  13275. /**
  13276. * Sets the current depth function to LEQUAL
  13277. */
  13278. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13279. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13280. };
  13281. /**
  13282. * Gets a boolean indicating if stencil buffer is enabled
  13283. * @returns the current stencil buffer state
  13284. */
  13285. Engine.prototype.getStencilBuffer = function () {
  13286. return this._stencilState.stencilTest;
  13287. };
  13288. /**
  13289. * Enable or disable the stencil buffer
  13290. * @param enable defines if the stencil buffer must be enabled or disabled
  13291. */
  13292. Engine.prototype.setStencilBuffer = function (enable) {
  13293. this._stencilState.stencilTest = enable;
  13294. };
  13295. /**
  13296. * Gets the current stencil mask
  13297. * @returns a number defining the new stencil mask to use
  13298. */
  13299. Engine.prototype.getStencilMask = function () {
  13300. return this._stencilState.stencilMask;
  13301. };
  13302. /**
  13303. * Sets the current stencil mask
  13304. * @param mask defines the new stencil mask to use
  13305. */
  13306. Engine.prototype.setStencilMask = function (mask) {
  13307. this._stencilState.stencilMask = mask;
  13308. };
  13309. /**
  13310. * Gets the current stencil function
  13311. * @returns a number defining the stencil function to use
  13312. */
  13313. Engine.prototype.getStencilFunction = function () {
  13314. return this._stencilState.stencilFunc;
  13315. };
  13316. /**
  13317. * Gets the current stencil reference value
  13318. * @returns a number defining the stencil reference value to use
  13319. */
  13320. Engine.prototype.getStencilFunctionReference = function () {
  13321. return this._stencilState.stencilFuncRef;
  13322. };
  13323. /**
  13324. * Gets the current stencil mask
  13325. * @returns a number defining the stencil mask to use
  13326. */
  13327. Engine.prototype.getStencilFunctionMask = function () {
  13328. return this._stencilState.stencilFuncMask;
  13329. };
  13330. /**
  13331. * Sets the current stencil function
  13332. * @param stencilFunc defines the new stencil function to use
  13333. */
  13334. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13335. this._stencilState.stencilFunc = stencilFunc;
  13336. };
  13337. /**
  13338. * Sets the current stencil reference
  13339. * @param reference defines the new stencil reference to use
  13340. */
  13341. Engine.prototype.setStencilFunctionReference = function (reference) {
  13342. this._stencilState.stencilFuncRef = reference;
  13343. };
  13344. /**
  13345. * Sets the current stencil mask
  13346. * @param mask defines the new stencil mask to use
  13347. */
  13348. Engine.prototype.setStencilFunctionMask = function (mask) {
  13349. this._stencilState.stencilFuncMask = mask;
  13350. };
  13351. /**
  13352. * Gets the current stencil operation when stencil fails
  13353. * @returns a number defining stencil operation to use when stencil fails
  13354. */
  13355. Engine.prototype.getStencilOperationFail = function () {
  13356. return this._stencilState.stencilOpStencilFail;
  13357. };
  13358. /**
  13359. * Gets the current stencil operation when depth fails
  13360. * @returns a number defining stencil operation to use when depth fails
  13361. */
  13362. Engine.prototype.getStencilOperationDepthFail = function () {
  13363. return this._stencilState.stencilOpDepthFail;
  13364. };
  13365. /**
  13366. * Gets the current stencil operation when stencil passes
  13367. * @returns a number defining stencil operation to use when stencil passes
  13368. */
  13369. Engine.prototype.getStencilOperationPass = function () {
  13370. return this._stencilState.stencilOpStencilDepthPass;
  13371. };
  13372. /**
  13373. * Sets the stencil operation to use when stencil fails
  13374. * @param operation defines the stencil operation to use when stencil fails
  13375. */
  13376. Engine.prototype.setStencilOperationFail = function (operation) {
  13377. this._stencilState.stencilOpStencilFail = operation;
  13378. };
  13379. /**
  13380. * Sets the stencil operation to use when depth fails
  13381. * @param operation defines the stencil operation to use when depth fails
  13382. */
  13383. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13384. this._stencilState.stencilOpDepthFail = operation;
  13385. };
  13386. /**
  13387. * Sets the stencil operation to use when stencil passes
  13388. * @param operation defines the stencil operation to use when stencil passes
  13389. */
  13390. Engine.prototype.setStencilOperationPass = function (operation) {
  13391. this._stencilState.stencilOpStencilDepthPass = operation;
  13392. };
  13393. /**
  13394. * Sets a boolean indicating if the dithering state is enabled or disabled
  13395. * @param value defines the dithering state
  13396. */
  13397. Engine.prototype.setDitheringState = function (value) {
  13398. if (value) {
  13399. this._gl.enable(this._gl.DITHER);
  13400. }
  13401. else {
  13402. this._gl.disable(this._gl.DITHER);
  13403. }
  13404. };
  13405. /**
  13406. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13407. * @param value defines the rasterizer state
  13408. */
  13409. Engine.prototype.setRasterizerState = function (value) {
  13410. if (value) {
  13411. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13412. }
  13413. else {
  13414. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13415. }
  13416. };
  13417. /**
  13418. * stop executing a render loop function and remove it from the execution array
  13419. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13420. */
  13421. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13422. if (!renderFunction) {
  13423. this._activeRenderLoops = [];
  13424. return;
  13425. }
  13426. var index = this._activeRenderLoops.indexOf(renderFunction);
  13427. if (index >= 0) {
  13428. this._activeRenderLoops.splice(index, 1);
  13429. }
  13430. };
  13431. /** @hidden */
  13432. Engine.prototype._renderLoop = function () {
  13433. if (!this._contextWasLost) {
  13434. var shouldRender = true;
  13435. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13436. shouldRender = false;
  13437. }
  13438. if (shouldRender) {
  13439. // Start new frame
  13440. this.beginFrame();
  13441. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13442. var renderFunction = this._activeRenderLoops[index];
  13443. renderFunction();
  13444. }
  13445. // Present
  13446. this.endFrame();
  13447. }
  13448. }
  13449. if (this._activeRenderLoops.length > 0) {
  13450. // Register new frame
  13451. if (this.customAnimationFrameRequester) {
  13452. this.customAnimationFrameRequester.requestID = BABYLON.Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  13453. this._frameHandler = this.customAnimationFrameRequester.requestID;
  13454. }
  13455. else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13456. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  13457. }
  13458. else {
  13459. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13460. }
  13461. }
  13462. else {
  13463. this._renderingQueueLaunched = false;
  13464. }
  13465. };
  13466. /**
  13467. * Register and execute a render loop. The engine can have more than one render function
  13468. * @param renderFunction defines the function to continuously execute
  13469. */
  13470. Engine.prototype.runRenderLoop = function (renderFunction) {
  13471. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13472. return;
  13473. }
  13474. this._activeRenderLoops.push(renderFunction);
  13475. if (!this._renderingQueueLaunched) {
  13476. this._renderingQueueLaunched = true;
  13477. this._bindedRenderFunction = this._renderLoop.bind(this);
  13478. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13479. }
  13480. };
  13481. /**
  13482. * Toggle full screen mode
  13483. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13484. */
  13485. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13486. if (this.isFullscreen) {
  13487. BABYLON.Tools.ExitFullscreen();
  13488. }
  13489. else {
  13490. this._pointerLockRequested = requestPointerLock;
  13491. if (this._renderingCanvas) {
  13492. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13493. }
  13494. }
  13495. };
  13496. /**
  13497. * Clear the current render buffer or the current render target (if any is set up)
  13498. * @param color defines the color to use
  13499. * @param backBuffer defines if the back buffer must be cleared
  13500. * @param depth defines if the depth buffer must be cleared
  13501. * @param stencil defines if the stencil buffer must be cleared
  13502. */
  13503. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13504. if (stencil === void 0) { stencil = false; }
  13505. this.applyStates();
  13506. var mode = 0;
  13507. if (backBuffer && color) {
  13508. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13509. mode |= this._gl.COLOR_BUFFER_BIT;
  13510. }
  13511. if (depth) {
  13512. this._gl.clearDepth(1.0);
  13513. mode |= this._gl.DEPTH_BUFFER_BIT;
  13514. }
  13515. if (stencil) {
  13516. this._gl.clearStencil(0);
  13517. mode |= this._gl.STENCIL_BUFFER_BIT;
  13518. }
  13519. this._gl.clear(mode);
  13520. };
  13521. /**
  13522. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13523. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13524. * @param y defines the y-coordinate of the corner of the clear rectangle
  13525. * @param width defines the width of the clear rectangle
  13526. * @param height defines the height of the clear rectangle
  13527. * @param clearColor defines the clear color
  13528. */
  13529. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13530. var gl = this._gl;
  13531. // Save state
  13532. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13533. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13534. // Change state
  13535. gl.enable(gl.SCISSOR_TEST);
  13536. gl.scissor(x, y, width, height);
  13537. // Clear
  13538. this.clear(clearColor, true, true, true);
  13539. // Restore state
  13540. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13541. if (curScissor === true) {
  13542. gl.enable(gl.SCISSOR_TEST);
  13543. }
  13544. else {
  13545. gl.disable(gl.SCISSOR_TEST);
  13546. }
  13547. };
  13548. /** @hidden */
  13549. Engine.prototype._viewport = function (x, y, width, height) {
  13550. if (x !== this._viewportCached.x ||
  13551. y !== this._viewportCached.y ||
  13552. width !== this._viewportCached.z ||
  13553. height !== this._viewportCached.w) {
  13554. this._viewportCached.x = x;
  13555. this._viewportCached.y = y;
  13556. this._viewportCached.z = width;
  13557. this._viewportCached.w = height;
  13558. this._gl.viewport(x, y, width, height);
  13559. }
  13560. };
  13561. /**
  13562. * Set the WebGL's viewport
  13563. * @param viewport defines the viewport element to be used
  13564. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13565. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13566. */
  13567. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13568. var width = requiredWidth || this.getRenderWidth();
  13569. var height = requiredHeight || this.getRenderHeight();
  13570. var x = viewport.x || 0;
  13571. var y = viewport.y || 0;
  13572. this._cachedViewport = viewport;
  13573. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13574. };
  13575. /**
  13576. * Directly set the WebGL Viewport
  13577. * @param x defines the x coordinate of the viewport (in screen space)
  13578. * @param y defines the y coordinate of the viewport (in screen space)
  13579. * @param width defines the width of the viewport (in screen space)
  13580. * @param height defines the height of the viewport (in screen space)
  13581. * @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
  13582. */
  13583. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13584. var currentViewport = this._cachedViewport;
  13585. this._cachedViewport = null;
  13586. this._viewport(x, y, width, height);
  13587. return currentViewport;
  13588. };
  13589. /**
  13590. * Begin a new frame
  13591. */
  13592. Engine.prototype.beginFrame = function () {
  13593. this.onBeginFrameObservable.notifyObservers(this);
  13594. this._measureFps();
  13595. };
  13596. /**
  13597. * Enf the current frame
  13598. */
  13599. Engine.prototype.endFrame = function () {
  13600. // Force a flush in case we are using a bad OS.
  13601. if (this._badOS) {
  13602. this.flushFramebuffer();
  13603. }
  13604. // Submit frame to the vr device, if enabled
  13605. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13606. // TODO: We should only submit the frame if we read frameData successfully.
  13607. this._vrDisplay.submitFrame();
  13608. }
  13609. this.onEndFrameObservable.notifyObservers(this);
  13610. };
  13611. /**
  13612. * Resize the view according to the canvas' size
  13613. */
  13614. Engine.prototype.resize = function () {
  13615. // We're not resizing the size of the canvas while in VR mode & presenting
  13616. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13617. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13618. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13619. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13620. }
  13621. };
  13622. /**
  13623. * Force a specific size of the canvas
  13624. * @param width defines the new canvas' width
  13625. * @param height defines the new canvas' height
  13626. */
  13627. Engine.prototype.setSize = function (width, height) {
  13628. if (!this._renderingCanvas) {
  13629. return;
  13630. }
  13631. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13632. return;
  13633. }
  13634. this._renderingCanvas.width = width;
  13635. this._renderingCanvas.height = height;
  13636. for (var index = 0; index < this.scenes.length; index++) {
  13637. var scene = this.scenes[index];
  13638. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13639. var cam = scene.cameras[camIndex];
  13640. cam._currentRenderId = 0;
  13641. }
  13642. }
  13643. if (this.onResizeObservable.hasObservers) {
  13644. this.onResizeObservable.notifyObservers(this);
  13645. }
  13646. };
  13647. // WebVR functions
  13648. /**
  13649. * Gets a boolean indicating if a webVR device was detected
  13650. * @returns true if a webVR device was detected
  13651. */
  13652. Engine.prototype.isVRDevicePresent = function () {
  13653. return !!this._vrDisplay;
  13654. };
  13655. /**
  13656. * Gets the current webVR device
  13657. * @returns the current webVR device (or null)
  13658. */
  13659. Engine.prototype.getVRDevice = function () {
  13660. return this._vrDisplay;
  13661. };
  13662. /**
  13663. * Initializes a webVR display and starts listening to display change events
  13664. * The onVRDisplayChangedObservable will be notified upon these changes
  13665. * @returns The onVRDisplayChangedObservable
  13666. */
  13667. Engine.prototype.initWebVR = function () {
  13668. this.initWebVRAsync();
  13669. return this.onVRDisplayChangedObservable;
  13670. };
  13671. /**
  13672. * Initializes a webVR display and starts listening to display change events
  13673. * The onVRDisplayChangedObservable will be notified upon these changes
  13674. * @returns A promise containing a VRDisplay and if vr is supported
  13675. */
  13676. Engine.prototype.initWebVRAsync = function () {
  13677. var _this = this;
  13678. var notifyObservers = function () {
  13679. var eventArgs = {
  13680. vrDisplay: _this._vrDisplay,
  13681. vrSupported: _this._vrSupported
  13682. };
  13683. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13684. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13685. };
  13686. if (!this._onVrDisplayConnect) {
  13687. this._onVrDisplayConnect = function (event) {
  13688. _this._vrDisplay = event.display;
  13689. notifyObservers();
  13690. };
  13691. this._onVrDisplayDisconnect = function () {
  13692. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13693. _this._vrDisplay = undefined;
  13694. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13695. notifyObservers();
  13696. };
  13697. this._onVrDisplayPresentChange = function () {
  13698. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13699. };
  13700. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13701. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13702. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13703. }
  13704. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13705. this._webVRInitPromise.then(notifyObservers);
  13706. return this._webVRInitPromise;
  13707. };
  13708. /**
  13709. * Call this function to switch to webVR mode
  13710. * Will do nothing if webVR is not supported or if there is no webVR device
  13711. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13712. */
  13713. Engine.prototype.enableVR = function () {
  13714. var _this = this;
  13715. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13716. var onResolved = function () {
  13717. _this.onVRRequestPresentComplete.notifyObservers(true);
  13718. _this._onVRFullScreenTriggered();
  13719. };
  13720. var onRejected = function () {
  13721. _this.onVRRequestPresentComplete.notifyObservers(false);
  13722. };
  13723. this.onVRRequestPresentStart.notifyObservers(this);
  13724. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13725. }
  13726. };
  13727. /**
  13728. * Call this function to leave webVR mode
  13729. * Will do nothing if webVR is not supported or if there is no webVR device
  13730. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13731. */
  13732. Engine.prototype.disableVR = function () {
  13733. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13734. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13735. }
  13736. };
  13737. Engine.prototype._getVRDisplaysAsync = function () {
  13738. var _this = this;
  13739. return new Promise(function (res, rej) {
  13740. if (navigator.getVRDisplays) {
  13741. navigator.getVRDisplays().then(function (devices) {
  13742. _this._vrSupported = true;
  13743. // note that devices may actually be an empty array. This is fine;
  13744. // we expect this._vrDisplay to be undefined in this case.
  13745. _this._vrDisplay = devices[0];
  13746. res({
  13747. vrDisplay: _this._vrDisplay,
  13748. vrSupported: _this._vrSupported
  13749. });
  13750. });
  13751. }
  13752. else {
  13753. _this._vrDisplay = undefined;
  13754. _this._vrSupported = false;
  13755. res({
  13756. vrDisplay: _this._vrDisplay,
  13757. vrSupported: _this._vrSupported
  13758. });
  13759. }
  13760. });
  13761. };
  13762. /**
  13763. * Binds the frame buffer to the specified texture.
  13764. * @param texture The texture to render to or null for the default canvas
  13765. * @param faceIndex The face of the texture to render to in case of cube texture
  13766. * @param requiredWidth The width of the target to render to
  13767. * @param requiredHeight The height of the target to render to
  13768. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13769. * @param depthStencilTexture The depth stencil texture to use to render
  13770. * @param lodLevel defines le lod level to bind to the frame buffer
  13771. */
  13772. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13773. if (lodLevel === void 0) { lodLevel = 0; }
  13774. if (this._currentRenderTarget) {
  13775. this.unBindFramebuffer(this._currentRenderTarget);
  13776. }
  13777. this._currentRenderTarget = texture;
  13778. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13779. var gl = this._gl;
  13780. if (texture.isCube) {
  13781. if (faceIndex === undefined) {
  13782. faceIndex = 0;
  13783. }
  13784. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13785. if (depthStencilTexture) {
  13786. if (depthStencilTexture._generateStencilBuffer) {
  13787. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13788. }
  13789. else {
  13790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13791. }
  13792. }
  13793. }
  13794. if (this._cachedViewport && !forceFullscreenViewport) {
  13795. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13796. }
  13797. else {
  13798. if (!requiredWidth) {
  13799. requiredWidth = texture.width;
  13800. if (lodLevel) {
  13801. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13802. }
  13803. }
  13804. if (!requiredHeight) {
  13805. requiredHeight = texture.height;
  13806. if (lodLevel) {
  13807. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13808. }
  13809. }
  13810. this._viewport(0, 0, requiredWidth, requiredHeight);
  13811. }
  13812. this.wipeCaches();
  13813. };
  13814. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13815. if (this._currentFramebuffer !== framebuffer) {
  13816. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13817. this._currentFramebuffer = framebuffer;
  13818. }
  13819. };
  13820. /**
  13821. * Unbind the current render target texture from the webGL context
  13822. * @param texture defines the render target texture to unbind
  13823. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13824. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13825. */
  13826. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13827. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13828. this._currentRenderTarget = null;
  13829. // If MSAA, we need to bitblt back to main texture
  13830. var gl = this._gl;
  13831. if (texture._MSAAFramebuffer) {
  13832. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13833. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13834. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13835. }
  13836. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13837. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13838. gl.generateMipmap(gl.TEXTURE_2D);
  13839. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13840. }
  13841. if (onBeforeUnbind) {
  13842. if (texture._MSAAFramebuffer) {
  13843. // Bind the correct framebuffer
  13844. this.bindUnboundFramebuffer(texture._framebuffer);
  13845. }
  13846. onBeforeUnbind();
  13847. }
  13848. this.bindUnboundFramebuffer(null);
  13849. };
  13850. /**
  13851. * Unbind a list of render target textures from the webGL context
  13852. * This is used only when drawBuffer extension or webGL2 are active
  13853. * @param textures defines the render target textures to unbind
  13854. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13855. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13856. */
  13857. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13858. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13859. this._currentRenderTarget = null;
  13860. // If MSAA, we need to bitblt back to main texture
  13861. var gl = this._gl;
  13862. if (textures[0]._MSAAFramebuffer) {
  13863. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13864. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13865. var attachments = textures[0]._attachments;
  13866. if (!attachments) {
  13867. attachments = new Array(textures.length);
  13868. textures[0]._attachments = attachments;
  13869. }
  13870. for (var i = 0; i < textures.length; i++) {
  13871. var texture = textures[i];
  13872. for (var j = 0; j < attachments.length; j++) {
  13873. attachments[j] = gl.NONE;
  13874. }
  13875. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13876. gl.readBuffer(attachments[i]);
  13877. gl.drawBuffers(attachments);
  13878. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13879. }
  13880. for (var i = 0; i < attachments.length; i++) {
  13881. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13882. }
  13883. gl.drawBuffers(attachments);
  13884. }
  13885. for (var i = 0; i < textures.length; i++) {
  13886. var texture = textures[i];
  13887. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13888. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13889. gl.generateMipmap(gl.TEXTURE_2D);
  13890. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13891. }
  13892. }
  13893. if (onBeforeUnbind) {
  13894. if (textures[0]._MSAAFramebuffer) {
  13895. // Bind the correct framebuffer
  13896. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13897. }
  13898. onBeforeUnbind();
  13899. }
  13900. this.bindUnboundFramebuffer(null);
  13901. };
  13902. /**
  13903. * Force the mipmap generation for the given render target texture
  13904. * @param texture defines the render target texture to use
  13905. */
  13906. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13907. if (texture.generateMipMaps) {
  13908. var gl = this._gl;
  13909. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13910. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13911. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13912. }
  13913. };
  13914. /**
  13915. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13916. */
  13917. Engine.prototype.flushFramebuffer = function () {
  13918. this._gl.flush();
  13919. };
  13920. /**
  13921. * Unbind the current render target and bind the default framebuffer
  13922. */
  13923. Engine.prototype.restoreDefaultFramebuffer = function () {
  13924. if (this._currentRenderTarget) {
  13925. this.unBindFramebuffer(this._currentRenderTarget);
  13926. }
  13927. else {
  13928. this.bindUnboundFramebuffer(null);
  13929. }
  13930. if (this._cachedViewport) {
  13931. this.setViewport(this._cachedViewport);
  13932. }
  13933. this.wipeCaches();
  13934. };
  13935. // UBOs
  13936. /**
  13937. * Create an uniform buffer
  13938. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13939. * @param elements defines the content of the uniform buffer
  13940. * @returns the webGL uniform buffer
  13941. */
  13942. Engine.prototype.createUniformBuffer = function (elements) {
  13943. var ubo = this._gl.createBuffer();
  13944. if (!ubo) {
  13945. throw new Error("Unable to create uniform buffer");
  13946. }
  13947. this.bindUniformBuffer(ubo);
  13948. if (elements instanceof Float32Array) {
  13949. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13950. }
  13951. else {
  13952. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13953. }
  13954. this.bindUniformBuffer(null);
  13955. ubo.references = 1;
  13956. return ubo;
  13957. };
  13958. /**
  13959. * Create a dynamic uniform buffer
  13960. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13961. * @param elements defines the content of the uniform buffer
  13962. * @returns the webGL uniform buffer
  13963. */
  13964. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13965. var ubo = this._gl.createBuffer();
  13966. if (!ubo) {
  13967. throw new Error("Unable to create dynamic uniform buffer");
  13968. }
  13969. this.bindUniformBuffer(ubo);
  13970. if (elements instanceof Float32Array) {
  13971. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13972. }
  13973. else {
  13974. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13975. }
  13976. this.bindUniformBuffer(null);
  13977. ubo.references = 1;
  13978. return ubo;
  13979. };
  13980. /**
  13981. * Update an existing uniform buffer
  13982. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13983. * @param uniformBuffer defines the target uniform buffer
  13984. * @param elements defines the content to update
  13985. * @param offset defines the offset in the uniform buffer where update should start
  13986. * @param count defines the size of the data to update
  13987. */
  13988. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13989. this.bindUniformBuffer(uniformBuffer);
  13990. if (offset === undefined) {
  13991. offset = 0;
  13992. }
  13993. if (count === undefined) {
  13994. if (elements instanceof Float32Array) {
  13995. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13996. }
  13997. else {
  13998. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13999. }
  14000. }
  14001. else {
  14002. if (elements instanceof Float32Array) {
  14003. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  14004. }
  14005. else {
  14006. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  14007. }
  14008. }
  14009. this.bindUniformBuffer(null);
  14010. };
  14011. // VBOs
  14012. Engine.prototype._resetVertexBufferBinding = function () {
  14013. this.bindArrayBuffer(null);
  14014. this._cachedVertexBuffers = null;
  14015. };
  14016. /**
  14017. * Creates a vertex buffer
  14018. * @param data the data for the vertex buffer
  14019. * @returns the new WebGL static buffer
  14020. */
  14021. Engine.prototype.createVertexBuffer = function (data) {
  14022. var vbo = this._gl.createBuffer();
  14023. if (!vbo) {
  14024. throw new Error("Unable to create vertex buffer");
  14025. }
  14026. this.bindArrayBuffer(vbo);
  14027. if (data instanceof Array) {
  14028. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  14029. }
  14030. else {
  14031. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  14032. }
  14033. this._resetVertexBufferBinding();
  14034. vbo.references = 1;
  14035. return vbo;
  14036. };
  14037. /**
  14038. * Creates a dynamic vertex buffer
  14039. * @param data the data for the dynamic vertex buffer
  14040. * @returns the new WebGL dynamic buffer
  14041. */
  14042. Engine.prototype.createDynamicVertexBuffer = function (data) {
  14043. var vbo = this._gl.createBuffer();
  14044. if (!vbo) {
  14045. throw new Error("Unable to create dynamic vertex buffer");
  14046. }
  14047. this.bindArrayBuffer(vbo);
  14048. if (data instanceof Array) {
  14049. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  14050. }
  14051. else {
  14052. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  14053. }
  14054. this._resetVertexBufferBinding();
  14055. vbo.references = 1;
  14056. return vbo;
  14057. };
  14058. /**
  14059. * Update a dynamic index buffer
  14060. * @param indexBuffer defines the target index buffer
  14061. * @param indices defines the data to update
  14062. * @param offset defines the offset in the target index buffer where update should start
  14063. */
  14064. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  14065. if (offset === void 0) { offset = 0; }
  14066. // Force cache update
  14067. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  14068. this.bindIndexBuffer(indexBuffer);
  14069. var arrayBuffer;
  14070. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  14071. arrayBuffer = indices;
  14072. }
  14073. else {
  14074. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14075. }
  14076. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  14077. this._resetIndexBufferBinding();
  14078. };
  14079. /**
  14080. * Updates a dynamic vertex buffer.
  14081. * @param vertexBuffer the vertex buffer to update
  14082. * @param data the data used to update the vertex buffer
  14083. * @param byteOffset the byte offset of the data
  14084. * @param byteLength the byte length of the data
  14085. */
  14086. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  14087. this.bindArrayBuffer(vertexBuffer);
  14088. if (byteOffset === undefined) {
  14089. byteOffset = 0;
  14090. }
  14091. if (byteLength === undefined) {
  14092. if (data instanceof Array) {
  14093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14094. }
  14095. else {
  14096. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14097. }
  14098. }
  14099. else {
  14100. if (data instanceof Array) {
  14101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14102. }
  14103. else {
  14104. if (data instanceof ArrayBuffer) {
  14105. data = new Uint8Array(data, byteOffset, byteLength);
  14106. }
  14107. else {
  14108. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14109. }
  14110. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14111. }
  14112. }
  14113. this._resetVertexBufferBinding();
  14114. };
  14115. Engine.prototype._resetIndexBufferBinding = function () {
  14116. this.bindIndexBuffer(null);
  14117. this._cachedIndexBuffer = null;
  14118. };
  14119. /**
  14120. * Creates a new index buffer
  14121. * @param indices defines the content of the index buffer
  14122. * @param updatable defines if the index buffer must be updatable
  14123. * @returns a new webGL buffer
  14124. */
  14125. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14126. var vbo = this._gl.createBuffer();
  14127. if (!vbo) {
  14128. throw new Error("Unable to create index buffer");
  14129. }
  14130. this.bindIndexBuffer(vbo);
  14131. // Check for 32 bits indices
  14132. var arrayBuffer;
  14133. var need32Bits = false;
  14134. if (indices instanceof Uint16Array) {
  14135. arrayBuffer = indices;
  14136. }
  14137. else {
  14138. //check 32 bit support
  14139. if (this._caps.uintIndices) {
  14140. if (indices instanceof Uint32Array) {
  14141. arrayBuffer = indices;
  14142. need32Bits = true;
  14143. }
  14144. else {
  14145. //number[] or Int32Array, check if 32 bit is necessary
  14146. for (var index = 0; index < indices.length; index++) {
  14147. if (indices[index] > 65535) {
  14148. need32Bits = true;
  14149. break;
  14150. }
  14151. }
  14152. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14153. }
  14154. }
  14155. else {
  14156. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14157. arrayBuffer = new Uint16Array(indices);
  14158. }
  14159. }
  14160. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14161. this._resetIndexBufferBinding();
  14162. vbo.references = 1;
  14163. vbo.is32Bits = need32Bits;
  14164. return vbo;
  14165. };
  14166. /**
  14167. * Bind a webGL buffer to the webGL context
  14168. * @param buffer defines the buffer to bind
  14169. */
  14170. Engine.prototype.bindArrayBuffer = function (buffer) {
  14171. if (!this._vaoRecordInProgress) {
  14172. this._unbindVertexArrayObject();
  14173. }
  14174. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14175. };
  14176. /**
  14177. * Bind an uniform buffer to the current webGL context
  14178. * @param buffer defines the buffer to bind
  14179. */
  14180. Engine.prototype.bindUniformBuffer = function (buffer) {
  14181. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14182. };
  14183. /**
  14184. * Bind a buffer to the current webGL context at a given location
  14185. * @param buffer defines the buffer to bind
  14186. * @param location defines the index where to bind the buffer
  14187. */
  14188. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14189. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14190. };
  14191. /**
  14192. * Bind a specific block at a given index in a specific shader program
  14193. * @param shaderProgram defines the shader program
  14194. * @param blockName defines the block name
  14195. * @param index defines the index where to bind the block
  14196. */
  14197. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14198. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14199. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14200. };
  14201. Engine.prototype.bindIndexBuffer = function (buffer) {
  14202. if (!this._vaoRecordInProgress) {
  14203. this._unbindVertexArrayObject();
  14204. }
  14205. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14206. };
  14207. Engine.prototype.bindBuffer = function (buffer, target) {
  14208. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14209. this._gl.bindBuffer(target, buffer);
  14210. this._currentBoundBuffer[target] = buffer;
  14211. }
  14212. };
  14213. /**
  14214. * update the bound buffer with the given data
  14215. * @param data defines the data to update
  14216. */
  14217. Engine.prototype.updateArrayBuffer = function (data) {
  14218. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14219. };
  14220. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14221. var pointer = this._currentBufferPointers[indx];
  14222. var changed = false;
  14223. if (!pointer.active) {
  14224. changed = true;
  14225. pointer.active = true;
  14226. pointer.index = indx;
  14227. pointer.size = size;
  14228. pointer.type = type;
  14229. pointer.normalized = normalized;
  14230. pointer.stride = stride;
  14231. pointer.offset = offset;
  14232. pointer.buffer = buffer;
  14233. }
  14234. else {
  14235. if (pointer.buffer !== buffer) {
  14236. pointer.buffer = buffer;
  14237. changed = true;
  14238. }
  14239. if (pointer.size !== size) {
  14240. pointer.size = size;
  14241. changed = true;
  14242. }
  14243. if (pointer.type !== type) {
  14244. pointer.type = type;
  14245. changed = true;
  14246. }
  14247. if (pointer.normalized !== normalized) {
  14248. pointer.normalized = normalized;
  14249. changed = true;
  14250. }
  14251. if (pointer.stride !== stride) {
  14252. pointer.stride = stride;
  14253. changed = true;
  14254. }
  14255. if (pointer.offset !== offset) {
  14256. pointer.offset = offset;
  14257. changed = true;
  14258. }
  14259. }
  14260. if (changed || this._vaoRecordInProgress) {
  14261. this.bindArrayBuffer(buffer);
  14262. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14263. }
  14264. };
  14265. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14266. if (indexBuffer == null) {
  14267. return;
  14268. }
  14269. if (this._cachedIndexBuffer !== indexBuffer) {
  14270. this._cachedIndexBuffer = indexBuffer;
  14271. this.bindIndexBuffer(indexBuffer);
  14272. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14273. }
  14274. };
  14275. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14276. var attributes = effect.getAttributesNames();
  14277. if (!this._vaoRecordInProgress) {
  14278. this._unbindVertexArrayObject();
  14279. }
  14280. this.unbindAllAttributes();
  14281. for (var index = 0; index < attributes.length; index++) {
  14282. var order = effect.getAttributeLocation(index);
  14283. if (order >= 0) {
  14284. var vertexBuffer = vertexBuffers[attributes[index]];
  14285. if (!vertexBuffer) {
  14286. continue;
  14287. }
  14288. this._gl.enableVertexAttribArray(order);
  14289. if (!this._vaoRecordInProgress) {
  14290. this._vertexAttribArraysEnabled[order] = true;
  14291. }
  14292. var buffer = vertexBuffer.getBuffer();
  14293. if (buffer) {
  14294. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14295. if (vertexBuffer.getIsInstanced()) {
  14296. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14297. if (!this._vaoRecordInProgress) {
  14298. this._currentInstanceLocations.push(order);
  14299. this._currentInstanceBuffers.push(buffer);
  14300. }
  14301. }
  14302. }
  14303. }
  14304. }
  14305. };
  14306. /**
  14307. * Records a vertex array object
  14308. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14309. * @param vertexBuffers defines the list of vertex buffers to store
  14310. * @param indexBuffer defines the index buffer to store
  14311. * @param effect defines the effect to store
  14312. * @returns the new vertex array object
  14313. */
  14314. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14315. var vao = this._gl.createVertexArray();
  14316. this._vaoRecordInProgress = true;
  14317. this._gl.bindVertexArray(vao);
  14318. this._mustWipeVertexAttributes = true;
  14319. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14320. this.bindIndexBuffer(indexBuffer);
  14321. this._vaoRecordInProgress = false;
  14322. this._gl.bindVertexArray(null);
  14323. return vao;
  14324. };
  14325. /**
  14326. * Bind a specific vertex array object
  14327. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14328. * @param vertexArrayObject defines the vertex array object to bind
  14329. * @param indexBuffer defines the index buffer to bind
  14330. */
  14331. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14332. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14333. this._cachedVertexArrayObject = vertexArrayObject;
  14334. this._gl.bindVertexArray(vertexArrayObject);
  14335. this._cachedVertexBuffers = null;
  14336. this._cachedIndexBuffer = null;
  14337. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14338. this._mustWipeVertexAttributes = true;
  14339. }
  14340. };
  14341. /**
  14342. * Bind webGl buffers directly to the webGL context
  14343. * @param vertexBuffer defines the vertex buffer to bind
  14344. * @param indexBuffer defines the index buffer to bind
  14345. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14346. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14347. * @param effect defines the effect associated with the vertex buffer
  14348. */
  14349. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14350. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14351. this._cachedVertexBuffers = vertexBuffer;
  14352. this._cachedEffectForVertexBuffers = effect;
  14353. var attributesCount = effect.getAttributesCount();
  14354. this._unbindVertexArrayObject();
  14355. this.unbindAllAttributes();
  14356. var offset = 0;
  14357. for (var index = 0; index < attributesCount; index++) {
  14358. if (index < vertexDeclaration.length) {
  14359. var order = effect.getAttributeLocation(index);
  14360. if (order >= 0) {
  14361. this._gl.enableVertexAttribArray(order);
  14362. this._vertexAttribArraysEnabled[order] = true;
  14363. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14364. }
  14365. offset += vertexDeclaration[index] * 4;
  14366. }
  14367. }
  14368. }
  14369. this._bindIndexBufferWithCache(indexBuffer);
  14370. };
  14371. Engine.prototype._unbindVertexArrayObject = function () {
  14372. if (!this._cachedVertexArrayObject) {
  14373. return;
  14374. }
  14375. this._cachedVertexArrayObject = null;
  14376. this._gl.bindVertexArray(null);
  14377. };
  14378. /**
  14379. * Bind a list of vertex buffers to the webGL context
  14380. * @param vertexBuffers defines the list of vertex buffers to bind
  14381. * @param indexBuffer defines the index buffer to bind
  14382. * @param effect defines the effect associated with the vertex buffers
  14383. */
  14384. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14385. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14386. this._cachedVertexBuffers = vertexBuffers;
  14387. this._cachedEffectForVertexBuffers = effect;
  14388. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14389. }
  14390. this._bindIndexBufferWithCache(indexBuffer);
  14391. };
  14392. /**
  14393. * Unbind all instance attributes
  14394. */
  14395. Engine.prototype.unbindInstanceAttributes = function () {
  14396. var boundBuffer;
  14397. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14398. var instancesBuffer = this._currentInstanceBuffers[i];
  14399. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14400. boundBuffer = instancesBuffer;
  14401. this.bindArrayBuffer(instancesBuffer);
  14402. }
  14403. var offsetLocation = this._currentInstanceLocations[i];
  14404. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14405. }
  14406. this._currentInstanceBuffers.length = 0;
  14407. this._currentInstanceLocations.length = 0;
  14408. };
  14409. /**
  14410. * Release and free the memory of a vertex array object
  14411. * @param vao defines the vertex array object to delete
  14412. */
  14413. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14414. this._gl.deleteVertexArray(vao);
  14415. };
  14416. /** @hidden */
  14417. Engine.prototype._releaseBuffer = function (buffer) {
  14418. buffer.references--;
  14419. if (buffer.references === 0) {
  14420. this._gl.deleteBuffer(buffer);
  14421. return true;
  14422. }
  14423. return false;
  14424. };
  14425. /**
  14426. * Creates a webGL buffer to use with instanciation
  14427. * @param capacity defines the size of the buffer
  14428. * @returns the webGL buffer
  14429. */
  14430. Engine.prototype.createInstancesBuffer = function (capacity) {
  14431. var buffer = this._gl.createBuffer();
  14432. if (!buffer) {
  14433. throw new Error("Unable to create instance buffer");
  14434. }
  14435. buffer.capacity = capacity;
  14436. this.bindArrayBuffer(buffer);
  14437. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14438. return buffer;
  14439. };
  14440. /**
  14441. * Delete a webGL buffer used with instanciation
  14442. * @param buffer defines the webGL buffer to delete
  14443. */
  14444. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14445. this._gl.deleteBuffer(buffer);
  14446. };
  14447. /**
  14448. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14449. * @param instancesBuffer defines the webGL buffer to update and bind
  14450. * @param data defines the data to store in the buffer
  14451. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14452. */
  14453. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14454. this.bindArrayBuffer(instancesBuffer);
  14455. if (data) {
  14456. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14457. }
  14458. if (offsetLocations[0].index !== undefined) {
  14459. var stride = 0;
  14460. for (var i = 0; i < offsetLocations.length; i++) {
  14461. var ai = offsetLocations[i];
  14462. stride += ai.attributeSize * 4;
  14463. }
  14464. for (var i = 0; i < offsetLocations.length; i++) {
  14465. var ai = offsetLocations[i];
  14466. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14467. this._gl.enableVertexAttribArray(ai.index);
  14468. this._vertexAttribArraysEnabled[ai.index] = true;
  14469. }
  14470. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14471. this._gl.vertexAttribDivisor(ai.index, 1);
  14472. this._currentInstanceLocations.push(ai.index);
  14473. this._currentInstanceBuffers.push(instancesBuffer);
  14474. }
  14475. }
  14476. else {
  14477. for (var index = 0; index < 4; index++) {
  14478. var offsetLocation = offsetLocations[index];
  14479. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14480. this._gl.enableVertexAttribArray(offsetLocation);
  14481. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14482. }
  14483. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14484. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14485. this._currentInstanceLocations.push(offsetLocation);
  14486. this._currentInstanceBuffers.push(instancesBuffer);
  14487. }
  14488. }
  14489. };
  14490. /**
  14491. * Apply all cached states (depth, culling, stencil and alpha)
  14492. */
  14493. Engine.prototype.applyStates = function () {
  14494. this._depthCullingState.apply(this._gl);
  14495. this._stencilState.apply(this._gl);
  14496. this._alphaState.apply(this._gl);
  14497. };
  14498. /**
  14499. * Send a draw order
  14500. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14501. * @param indexStart defines the starting index
  14502. * @param indexCount defines the number of index to draw
  14503. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14504. */
  14505. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14506. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14507. };
  14508. /**
  14509. * Draw a list of points
  14510. * @param verticesStart defines the index of first vertex to draw
  14511. * @param verticesCount defines the count of vertices to draw
  14512. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14513. */
  14514. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14515. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14516. };
  14517. /**
  14518. * Draw a list of unindexed primitives
  14519. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14520. * @param verticesStart defines the index of first vertex to draw
  14521. * @param verticesCount defines the count of vertices to draw
  14522. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14523. */
  14524. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14525. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14526. };
  14527. /**
  14528. * Draw a list of indexed primitives
  14529. * @param fillMode defines the primitive to use
  14530. * @param indexStart defines the starting index
  14531. * @param indexCount defines the number of index to draw
  14532. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14533. */
  14534. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14535. // Apply states
  14536. this.applyStates();
  14537. this._drawCalls.addCount(1, false);
  14538. // Render
  14539. var drawMode = this._drawMode(fillMode);
  14540. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14541. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14542. if (instancesCount) {
  14543. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14544. }
  14545. else {
  14546. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14547. }
  14548. };
  14549. /**
  14550. * Draw a list of unindexed primitives
  14551. * @param fillMode defines the primitive to use
  14552. * @param verticesStart defines the index of first vertex to draw
  14553. * @param verticesCount defines the count of vertices to draw
  14554. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14555. */
  14556. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14557. // Apply states
  14558. this.applyStates();
  14559. this._drawCalls.addCount(1, false);
  14560. var drawMode = this._drawMode(fillMode);
  14561. if (instancesCount) {
  14562. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14563. }
  14564. else {
  14565. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14566. }
  14567. };
  14568. Engine.prototype._drawMode = function (fillMode) {
  14569. switch (fillMode) {
  14570. // Triangle views
  14571. case BABYLON.Material.TriangleFillMode:
  14572. return this._gl.TRIANGLES;
  14573. case BABYLON.Material.PointFillMode:
  14574. return this._gl.POINTS;
  14575. case BABYLON.Material.WireFrameFillMode:
  14576. return this._gl.LINES;
  14577. // Draw modes
  14578. case BABYLON.Material.PointListDrawMode:
  14579. return this._gl.POINTS;
  14580. case BABYLON.Material.LineListDrawMode:
  14581. return this._gl.LINES;
  14582. case BABYLON.Material.LineLoopDrawMode:
  14583. return this._gl.LINE_LOOP;
  14584. case BABYLON.Material.LineStripDrawMode:
  14585. return this._gl.LINE_STRIP;
  14586. case BABYLON.Material.TriangleStripDrawMode:
  14587. return this._gl.TRIANGLE_STRIP;
  14588. case BABYLON.Material.TriangleFanDrawMode:
  14589. return this._gl.TRIANGLE_FAN;
  14590. default:
  14591. return this._gl.TRIANGLES;
  14592. }
  14593. };
  14594. // Shaders
  14595. /** @hidden */
  14596. Engine.prototype._releaseEffect = function (effect) {
  14597. if (this._compiledEffects[effect._key]) {
  14598. delete this._compiledEffects[effect._key];
  14599. this._deleteProgram(effect.getProgram());
  14600. }
  14601. };
  14602. /** @hidden */
  14603. Engine.prototype._deleteProgram = function (program) {
  14604. if (program) {
  14605. program.__SPECTOR_rebuildProgram = null;
  14606. if (program.transformFeedback) {
  14607. this.deleteTransformFeedback(program.transformFeedback);
  14608. program.transformFeedback = null;
  14609. }
  14610. this._gl.deleteProgram(program);
  14611. }
  14612. };
  14613. /**
  14614. * Create a new effect (used to store vertex/fragment shaders)
  14615. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14616. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14617. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14618. * @param samplers defines an array of string used to represent textures
  14619. * @param defines defines the string containing the defines to use to compile the shaders
  14620. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14621. * @param onCompiled defines a function to call when the effect creation is successful
  14622. * @param onError defines a function to call when the effect creation has failed
  14623. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14624. * @returns the new Effect
  14625. */
  14626. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14627. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14628. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14629. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14630. if (this._compiledEffects[name]) {
  14631. var compiledEffect = this._compiledEffects[name];
  14632. if (onCompiled && compiledEffect.isReady()) {
  14633. onCompiled(compiledEffect);
  14634. }
  14635. return compiledEffect;
  14636. }
  14637. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14638. effect._key = name;
  14639. this._compiledEffects[name] = effect;
  14640. return effect;
  14641. };
  14642. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14643. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14644. };
  14645. Engine.prototype._compileRawShader = function (source, type) {
  14646. var gl = this._gl;
  14647. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14648. if (!shader) {
  14649. throw new Error("Something went wrong while compile the shader.");
  14650. }
  14651. gl.shaderSource(shader, source);
  14652. gl.compileShader(shader);
  14653. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14654. var log = gl.getShaderInfoLog(shader);
  14655. if (log) {
  14656. throw new Error(log);
  14657. }
  14658. }
  14659. return shader;
  14660. };
  14661. /**
  14662. * Directly creates a webGL program
  14663. * @param vertexCode defines the vertex shader code to use
  14664. * @param fragmentCode defines the fragment shader code to use
  14665. * @param context defines the webGL context to use (if not set, the current one will be used)
  14666. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14667. * @returns the new webGL program
  14668. */
  14669. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14670. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14671. context = context || this._gl;
  14672. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14673. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14674. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14675. };
  14676. /**
  14677. * Creates a webGL program
  14678. * @param vertexCode defines the vertex shader code to use
  14679. * @param fragmentCode defines the fragment shader code to use
  14680. * @param defines defines the string containing the defines to use to compile the shaders
  14681. * @param context defines the webGL context to use (if not set, the current one will be used)
  14682. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14683. * @returns the new webGL program
  14684. */
  14685. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14686. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14687. context = context || this._gl;
  14688. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14689. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14690. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14691. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14692. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14693. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14694. return program;
  14695. };
  14696. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14697. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14698. var shaderProgram = context.createProgram();
  14699. if (!shaderProgram) {
  14700. throw new Error("Unable to create program");
  14701. }
  14702. context.attachShader(shaderProgram, vertexShader);
  14703. context.attachShader(shaderProgram, fragmentShader);
  14704. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14705. var transformFeedback = this.createTransformFeedback();
  14706. this.bindTransformFeedback(transformFeedback);
  14707. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14708. shaderProgram.transformFeedback = transformFeedback;
  14709. }
  14710. context.linkProgram(shaderProgram);
  14711. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14712. this.bindTransformFeedback(null);
  14713. }
  14714. shaderProgram.context = context;
  14715. shaderProgram.vertexShader = vertexShader;
  14716. shaderProgram.fragmentShader = fragmentShader;
  14717. if (!this._caps.parallelShaderCompile) {
  14718. this._finalizeProgram(shaderProgram);
  14719. }
  14720. else {
  14721. shaderProgram.isParallelCompiled = true;
  14722. }
  14723. return shaderProgram;
  14724. };
  14725. Engine.prototype._finalizeProgram = function (shaderProgram) {
  14726. var context = shaderProgram.context;
  14727. var vertexShader = shaderProgram.vertexShader;
  14728. var fragmentShader = shaderProgram.fragmentShader;
  14729. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14730. if (!linked) {
  14731. var error = context.getProgramInfoLog(shaderProgram);
  14732. if (error) {
  14733. throw new Error(error);
  14734. }
  14735. }
  14736. if (this.validateShaderPrograms) {
  14737. context.validateProgram(shaderProgram);
  14738. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14739. if (!validated) {
  14740. var error = context.getProgramInfoLog(shaderProgram);
  14741. if (error) {
  14742. throw new Error(error);
  14743. }
  14744. }
  14745. }
  14746. context.deleteShader(vertexShader);
  14747. context.deleteShader(fragmentShader);
  14748. shaderProgram.context = undefined;
  14749. shaderProgram.vertexShader = undefined;
  14750. shaderProgram.fragmentShader = undefined;
  14751. if (shaderProgram.onCompiled) {
  14752. shaderProgram.onCompiled();
  14753. shaderProgram.onCompiled = undefined;
  14754. }
  14755. };
  14756. /** @hidden */
  14757. Engine.prototype._isProgramCompiled = function (shaderProgram) {
  14758. if (!shaderProgram.isParallelCompiled) {
  14759. return true;
  14760. }
  14761. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  14762. this._finalizeProgram(shaderProgram);
  14763. return true;
  14764. }
  14765. return false;
  14766. };
  14767. /** @hidden */
  14768. Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) {
  14769. if (!shaderProgram.isParallelCompiled) {
  14770. action();
  14771. return;
  14772. }
  14773. shaderProgram.onCompiled = action;
  14774. };
  14775. /**
  14776. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14777. * @param shaderProgram defines the webGL program to use
  14778. * @param uniformsNames defines the list of uniform names
  14779. * @returns an array of webGL uniform locations
  14780. */
  14781. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14782. var results = new Array();
  14783. for (var index = 0; index < uniformsNames.length; index++) {
  14784. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14785. }
  14786. return results;
  14787. };
  14788. /**
  14789. * Gets the lsit of active attributes for a given webGL program
  14790. * @param shaderProgram defines the webGL program to use
  14791. * @param attributesNames defines the list of attribute names to get
  14792. * @returns an array of indices indicating the offset of each attribute
  14793. */
  14794. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14795. var results = [];
  14796. for (var index = 0; index < attributesNames.length; index++) {
  14797. try {
  14798. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14799. }
  14800. catch (e) {
  14801. results.push(-1);
  14802. }
  14803. }
  14804. return results;
  14805. };
  14806. /**
  14807. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14808. * @param effect defines the effect to activate
  14809. */
  14810. Engine.prototype.enableEffect = function (effect) {
  14811. if (!effect || effect === this._currentEffect) {
  14812. return;
  14813. }
  14814. // Use program
  14815. this.bindSamplers(effect);
  14816. this._currentEffect = effect;
  14817. if (effect.onBind) {
  14818. effect.onBind(effect);
  14819. }
  14820. if (effect._onBindObservable) {
  14821. effect._onBindObservable.notifyObservers(effect);
  14822. }
  14823. };
  14824. /**
  14825. * Set the value of an uniform to an array of int32
  14826. * @param uniform defines the webGL uniform location where to store the value
  14827. * @param array defines the array of int32 to store
  14828. */
  14829. Engine.prototype.setIntArray = function (uniform, array) {
  14830. if (!uniform) {
  14831. return;
  14832. }
  14833. this._gl.uniform1iv(uniform, array);
  14834. };
  14835. /**
  14836. * Set the value of an uniform to an array of int32 (stored as vec2)
  14837. * @param uniform defines the webGL uniform location where to store the value
  14838. * @param array defines the array of int32 to store
  14839. */
  14840. Engine.prototype.setIntArray2 = function (uniform, array) {
  14841. if (!uniform || array.length % 2 !== 0) {
  14842. return;
  14843. }
  14844. this._gl.uniform2iv(uniform, array);
  14845. };
  14846. /**
  14847. * Set the value of an uniform to an array of int32 (stored as vec3)
  14848. * @param uniform defines the webGL uniform location where to store the value
  14849. * @param array defines the array of int32 to store
  14850. */
  14851. Engine.prototype.setIntArray3 = function (uniform, array) {
  14852. if (!uniform || array.length % 3 !== 0) {
  14853. return;
  14854. }
  14855. this._gl.uniform3iv(uniform, array);
  14856. };
  14857. /**
  14858. * Set the value of an uniform to an array of int32 (stored as vec4)
  14859. * @param uniform defines the webGL uniform location where to store the value
  14860. * @param array defines the array of int32 to store
  14861. */
  14862. Engine.prototype.setIntArray4 = function (uniform, array) {
  14863. if (!uniform || array.length % 4 !== 0) {
  14864. return;
  14865. }
  14866. this._gl.uniform4iv(uniform, array);
  14867. };
  14868. /**
  14869. * Set the value of an uniform to an array of float32
  14870. * @param uniform defines the webGL uniform location where to store the value
  14871. * @param array defines the array of float32 to store
  14872. */
  14873. Engine.prototype.setFloatArray = function (uniform, array) {
  14874. if (!uniform) {
  14875. return;
  14876. }
  14877. this._gl.uniform1fv(uniform, array);
  14878. };
  14879. /**
  14880. * Set the value of an uniform to an array of float32 (stored as vec2)
  14881. * @param uniform defines the webGL uniform location where to store the value
  14882. * @param array defines the array of float32 to store
  14883. */
  14884. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14885. if (!uniform || array.length % 2 !== 0) {
  14886. return;
  14887. }
  14888. this._gl.uniform2fv(uniform, array);
  14889. };
  14890. /**
  14891. * Set the value of an uniform to an array of float32 (stored as vec3)
  14892. * @param uniform defines the webGL uniform location where to store the value
  14893. * @param array defines the array of float32 to store
  14894. */
  14895. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14896. if (!uniform || array.length % 3 !== 0) {
  14897. return;
  14898. }
  14899. this._gl.uniform3fv(uniform, array);
  14900. };
  14901. /**
  14902. * Set the value of an uniform to an array of float32 (stored as vec4)
  14903. * @param uniform defines the webGL uniform location where to store the value
  14904. * @param array defines the array of float32 to store
  14905. */
  14906. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14907. if (!uniform || array.length % 4 !== 0) {
  14908. return;
  14909. }
  14910. this._gl.uniform4fv(uniform, array);
  14911. };
  14912. /**
  14913. * Set the value of an uniform to an array of number
  14914. * @param uniform defines the webGL uniform location where to store the value
  14915. * @param array defines the array of number to store
  14916. */
  14917. Engine.prototype.setArray = function (uniform, array) {
  14918. if (!uniform) {
  14919. return;
  14920. }
  14921. this._gl.uniform1fv(uniform, array);
  14922. };
  14923. /**
  14924. * Set the value of an uniform to an array of number (stored as vec2)
  14925. * @param uniform defines the webGL uniform location where to store the value
  14926. * @param array defines the array of number to store
  14927. */
  14928. Engine.prototype.setArray2 = function (uniform, array) {
  14929. if (!uniform || array.length % 2 !== 0) {
  14930. return;
  14931. }
  14932. this._gl.uniform2fv(uniform, array);
  14933. };
  14934. /**
  14935. * Set the value of an uniform to an array of number (stored as vec3)
  14936. * @param uniform defines the webGL uniform location where to store the value
  14937. * @param array defines the array of number to store
  14938. */
  14939. Engine.prototype.setArray3 = function (uniform, array) {
  14940. if (!uniform || array.length % 3 !== 0) {
  14941. return;
  14942. }
  14943. this._gl.uniform3fv(uniform, array);
  14944. };
  14945. /**
  14946. * Set the value of an uniform to an array of number (stored as vec4)
  14947. * @param uniform defines the webGL uniform location where to store the value
  14948. * @param array defines the array of number to store
  14949. */
  14950. Engine.prototype.setArray4 = function (uniform, array) {
  14951. if (!uniform || array.length % 4 !== 0) {
  14952. return;
  14953. }
  14954. this._gl.uniform4fv(uniform, array);
  14955. };
  14956. /**
  14957. * Set the value of an uniform to an array of float32 (stored as matrices)
  14958. * @param uniform defines the webGL uniform location where to store the value
  14959. * @param matrices defines the array of float32 to store
  14960. */
  14961. Engine.prototype.setMatrices = function (uniform, matrices) {
  14962. if (!uniform) {
  14963. return;
  14964. }
  14965. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14966. };
  14967. /**
  14968. * Set the value of an uniform to a matrix
  14969. * @param uniform defines the webGL uniform location where to store the value
  14970. * @param matrix defines the matrix to store
  14971. */
  14972. Engine.prototype.setMatrix = function (uniform, matrix) {
  14973. if (!uniform) {
  14974. return;
  14975. }
  14976. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14977. };
  14978. /**
  14979. * Set the value of an uniform to a matrix (3x3)
  14980. * @param uniform defines the webGL uniform location where to store the value
  14981. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14982. */
  14983. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14984. if (!uniform) {
  14985. return;
  14986. }
  14987. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14988. };
  14989. /**
  14990. * Set the value of an uniform to a matrix (2x2)
  14991. * @param uniform defines the webGL uniform location where to store the value
  14992. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14993. */
  14994. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14995. if (!uniform) {
  14996. return;
  14997. }
  14998. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14999. };
  15000. /**
  15001. * Set the value of an uniform to a number (int)
  15002. * @param uniform defines the webGL uniform location where to store the value
  15003. * @param value defines the int number to store
  15004. */
  15005. Engine.prototype.setInt = function (uniform, value) {
  15006. if (!uniform) {
  15007. return;
  15008. }
  15009. this._gl.uniform1i(uniform, value);
  15010. };
  15011. /**
  15012. * Set the value of an uniform to a number (float)
  15013. * @param uniform defines the webGL uniform location where to store the value
  15014. * @param value defines the float number to store
  15015. */
  15016. Engine.prototype.setFloat = function (uniform, value) {
  15017. if (!uniform) {
  15018. return;
  15019. }
  15020. this._gl.uniform1f(uniform, value);
  15021. };
  15022. /**
  15023. * Set the value of an uniform to a vec2
  15024. * @param uniform defines the webGL uniform location where to store the value
  15025. * @param x defines the 1st component of the value
  15026. * @param y defines the 2nd component of the value
  15027. */
  15028. Engine.prototype.setFloat2 = function (uniform, x, y) {
  15029. if (!uniform) {
  15030. return;
  15031. }
  15032. this._gl.uniform2f(uniform, x, y);
  15033. };
  15034. /**
  15035. * Set the value of an uniform to a vec3
  15036. * @param uniform defines the webGL uniform location where to store the value
  15037. * @param x defines the 1st component of the value
  15038. * @param y defines the 2nd component of the value
  15039. * @param z defines the 3rd component of the value
  15040. */
  15041. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  15042. if (!uniform) {
  15043. return;
  15044. }
  15045. this._gl.uniform3f(uniform, x, y, z);
  15046. };
  15047. /**
  15048. * Set the value of an uniform to a boolean
  15049. * @param uniform defines the webGL uniform location where to store the value
  15050. * @param bool defines the boolean to store
  15051. */
  15052. Engine.prototype.setBool = function (uniform, bool) {
  15053. if (!uniform) {
  15054. return;
  15055. }
  15056. this._gl.uniform1i(uniform, bool);
  15057. };
  15058. /**
  15059. * Set the value of an uniform to a vec4
  15060. * @param uniform defines the webGL uniform location where to store the value
  15061. * @param x defines the 1st component of the value
  15062. * @param y defines the 2nd component of the value
  15063. * @param z defines the 3rd component of the value
  15064. * @param w defines the 4th component of the value
  15065. */
  15066. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  15067. if (!uniform) {
  15068. return;
  15069. }
  15070. this._gl.uniform4f(uniform, x, y, z, w);
  15071. };
  15072. /**
  15073. * Set the value of an uniform to a Color3
  15074. * @param uniform defines the webGL uniform location where to store the value
  15075. * @param color3 defines the color to store
  15076. */
  15077. Engine.prototype.setColor3 = function (uniform, color3) {
  15078. if (!uniform) {
  15079. return;
  15080. }
  15081. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  15082. };
  15083. /**
  15084. * Set the value of an uniform to a Color3 and an alpha value
  15085. * @param uniform defines the webGL uniform location where to store the value
  15086. * @param color3 defines the color to store
  15087. * @param alpha defines the alpha component to store
  15088. */
  15089. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  15090. if (!uniform) {
  15091. return;
  15092. }
  15093. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  15094. };
  15095. /**
  15096. * Sets a Color4 on a uniform variable
  15097. * @param uniform defines the uniform location
  15098. * @param color4 defines the value to be set
  15099. */
  15100. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  15101. if (!uniform) {
  15102. return;
  15103. }
  15104. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  15105. };
  15106. // States
  15107. /**
  15108. * Set various states to the webGL context
  15109. * @param culling defines backface culling state
  15110. * @param zOffset defines the value to apply to zOffset (0 by default)
  15111. * @param force defines if states must be applied even if cache is up to date
  15112. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  15113. */
  15114. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  15115. if (zOffset === void 0) { zOffset = 0; }
  15116. if (reverseSide === void 0) { reverseSide = false; }
  15117. // Culling
  15118. if (this._depthCullingState.cull !== culling || force) {
  15119. this._depthCullingState.cull = culling;
  15120. }
  15121. // Cull face
  15122. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  15123. if (this._depthCullingState.cullFace !== cullFace || force) {
  15124. this._depthCullingState.cullFace = cullFace;
  15125. }
  15126. // Z offset
  15127. this.setZOffset(zOffset);
  15128. // Front face
  15129. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  15130. if (this._depthCullingState.frontFace !== frontFace || force) {
  15131. this._depthCullingState.frontFace = frontFace;
  15132. }
  15133. };
  15134. /**
  15135. * Set the z offset to apply to current rendering
  15136. * @param value defines the offset to apply
  15137. */
  15138. Engine.prototype.setZOffset = function (value) {
  15139. this._depthCullingState.zOffset = value;
  15140. };
  15141. /**
  15142. * Gets the current value of the zOffset
  15143. * @returns the current zOffset state
  15144. */
  15145. Engine.prototype.getZOffset = function () {
  15146. return this._depthCullingState.zOffset;
  15147. };
  15148. /**
  15149. * Enable or disable depth buffering
  15150. * @param enable defines the state to set
  15151. */
  15152. Engine.prototype.setDepthBuffer = function (enable) {
  15153. this._depthCullingState.depthTest = enable;
  15154. };
  15155. /**
  15156. * Gets a boolean indicating if depth writing is enabled
  15157. * @returns the current depth writing state
  15158. */
  15159. Engine.prototype.getDepthWrite = function () {
  15160. return this._depthCullingState.depthMask;
  15161. };
  15162. /**
  15163. * Enable or disable depth writing
  15164. * @param enable defines the state to set
  15165. */
  15166. Engine.prototype.setDepthWrite = function (enable) {
  15167. this._depthCullingState.depthMask = enable;
  15168. };
  15169. /**
  15170. * Enable or disable color writing
  15171. * @param enable defines the state to set
  15172. */
  15173. Engine.prototype.setColorWrite = function (enable) {
  15174. this._gl.colorMask(enable, enable, enable, enable);
  15175. this._colorWrite = enable;
  15176. };
  15177. /**
  15178. * Gets a boolean indicating if color writing is enabled
  15179. * @returns the current color writing state
  15180. */
  15181. Engine.prototype.getColorWrite = function () {
  15182. return this._colorWrite;
  15183. };
  15184. /**
  15185. * Sets alpha constants used by some alpha blending modes
  15186. * @param r defines the red component
  15187. * @param g defines the green component
  15188. * @param b defines the blue component
  15189. * @param a defines the alpha component
  15190. */
  15191. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15192. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15193. };
  15194. /**
  15195. * Sets the current alpha mode
  15196. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15197. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15198. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15199. */
  15200. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15201. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15202. if (this._alphaMode === mode) {
  15203. return;
  15204. }
  15205. switch (mode) {
  15206. case Engine.ALPHA_DISABLE:
  15207. this._alphaState.alphaBlend = false;
  15208. break;
  15209. case Engine.ALPHA_PREMULTIPLIED:
  15210. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15211. this._alphaState.alphaBlend = true;
  15212. break;
  15213. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15214. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15215. this._alphaState.alphaBlend = true;
  15216. break;
  15217. case Engine.ALPHA_COMBINE:
  15218. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15219. this._alphaState.alphaBlend = true;
  15220. break;
  15221. case Engine.ALPHA_ONEONE:
  15222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15223. this._alphaState.alphaBlend = true;
  15224. break;
  15225. case Engine.ALPHA_ADD:
  15226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15227. this._alphaState.alphaBlend = true;
  15228. break;
  15229. case Engine.ALPHA_SUBTRACT:
  15230. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15231. this._alphaState.alphaBlend = true;
  15232. break;
  15233. case Engine.ALPHA_MULTIPLY:
  15234. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15235. this._alphaState.alphaBlend = true;
  15236. break;
  15237. case Engine.ALPHA_MAXIMIZED:
  15238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15239. this._alphaState.alphaBlend = true;
  15240. break;
  15241. case Engine.ALPHA_INTERPOLATE:
  15242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15243. this._alphaState.alphaBlend = true;
  15244. break;
  15245. case Engine.ALPHA_SCREENMODE:
  15246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15247. this._alphaState.alphaBlend = true;
  15248. break;
  15249. }
  15250. if (!noDepthWriteChange) {
  15251. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15252. }
  15253. this._alphaMode = mode;
  15254. };
  15255. /**
  15256. * Gets the current alpha mode
  15257. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15258. * @returns the current alpha mode
  15259. */
  15260. Engine.prototype.getAlphaMode = function () {
  15261. return this._alphaMode;
  15262. };
  15263. // Textures
  15264. /**
  15265. * Clears the list of texture accessible through engine.
  15266. * This can help preventing texture load conflict due to name collision.
  15267. */
  15268. Engine.prototype.clearInternalTexturesCache = function () {
  15269. this._internalTexturesCache = [];
  15270. };
  15271. /**
  15272. * Force the entire cache to be cleared
  15273. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15274. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15275. */
  15276. Engine.prototype.wipeCaches = function (bruteForce) {
  15277. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15278. return;
  15279. }
  15280. this._currentEffect = null;
  15281. this._viewportCached.x = 0;
  15282. this._viewportCached.y = 0;
  15283. this._viewportCached.z = 0;
  15284. this._viewportCached.w = 0;
  15285. if (bruteForce) {
  15286. this.resetTextureCache();
  15287. this._currentProgram = null;
  15288. this._stencilState.reset();
  15289. this._depthCullingState.reset();
  15290. this.setDepthFunctionToLessOrEqual();
  15291. this._alphaState.reset();
  15292. this._unpackFlipYCached = null;
  15293. }
  15294. this._resetVertexBufferBinding();
  15295. this._cachedIndexBuffer = null;
  15296. this._cachedEffectForVertexBuffers = null;
  15297. this._unbindVertexArrayObject();
  15298. this.bindIndexBuffer(null);
  15299. };
  15300. /**
  15301. * Set the compressed texture format to use, based on the formats you have, and the formats
  15302. * supported by the hardware / browser.
  15303. *
  15304. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15305. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15306. * to API arguments needed to compressed textures. This puts the burden on the container
  15307. * generator to house the arcane code for determining these for current & future formats.
  15308. *
  15309. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15310. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15311. *
  15312. * Note: The result of this call is not taken into account when a texture is base64.
  15313. *
  15314. * @param formatsAvailable defines the list of those format families you have created
  15315. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15316. *
  15317. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15318. * @returns The extension selected.
  15319. */
  15320. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15321. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15322. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15323. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15324. return this._textureFormatInUse = this._texturesSupported[i];
  15325. }
  15326. }
  15327. }
  15328. // actively set format to nothing, to allow this to be called more than once
  15329. // and possibly fail the 2nd time
  15330. this._textureFormatInUse = null;
  15331. return null;
  15332. };
  15333. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15334. var gl = this._gl;
  15335. var magFilter = gl.NEAREST;
  15336. var minFilter = gl.NEAREST;
  15337. switch (samplingMode) {
  15338. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15339. magFilter = gl.LINEAR;
  15340. if (generateMipMaps) {
  15341. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15342. }
  15343. else {
  15344. minFilter = gl.LINEAR;
  15345. }
  15346. break;
  15347. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15348. magFilter = gl.LINEAR;
  15349. if (generateMipMaps) {
  15350. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15351. }
  15352. else {
  15353. minFilter = gl.LINEAR;
  15354. }
  15355. break;
  15356. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15357. magFilter = gl.NEAREST;
  15358. if (generateMipMaps) {
  15359. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15360. }
  15361. else {
  15362. minFilter = gl.NEAREST;
  15363. }
  15364. break;
  15365. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15366. magFilter = gl.NEAREST;
  15367. if (generateMipMaps) {
  15368. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15369. }
  15370. else {
  15371. minFilter = gl.NEAREST;
  15372. }
  15373. break;
  15374. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15375. magFilter = gl.NEAREST;
  15376. if (generateMipMaps) {
  15377. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15378. }
  15379. else {
  15380. minFilter = gl.LINEAR;
  15381. }
  15382. break;
  15383. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15384. magFilter = gl.NEAREST;
  15385. if (generateMipMaps) {
  15386. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15387. }
  15388. else {
  15389. minFilter = gl.LINEAR;
  15390. }
  15391. break;
  15392. case Engine.TEXTURE_NEAREST_LINEAR:
  15393. magFilter = gl.NEAREST;
  15394. minFilter = gl.LINEAR;
  15395. break;
  15396. case Engine.TEXTURE_NEAREST_NEAREST:
  15397. magFilter = gl.NEAREST;
  15398. minFilter = gl.NEAREST;
  15399. break;
  15400. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15401. magFilter = gl.LINEAR;
  15402. if (generateMipMaps) {
  15403. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15404. }
  15405. else {
  15406. minFilter = gl.NEAREST;
  15407. }
  15408. break;
  15409. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15410. magFilter = gl.LINEAR;
  15411. if (generateMipMaps) {
  15412. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15413. }
  15414. else {
  15415. minFilter = gl.NEAREST;
  15416. }
  15417. break;
  15418. case Engine.TEXTURE_LINEAR_LINEAR:
  15419. magFilter = gl.LINEAR;
  15420. minFilter = gl.LINEAR;
  15421. break;
  15422. case Engine.TEXTURE_LINEAR_NEAREST:
  15423. magFilter = gl.LINEAR;
  15424. minFilter = gl.NEAREST;
  15425. break;
  15426. }
  15427. return {
  15428. min: minFilter,
  15429. mag: magFilter
  15430. };
  15431. };
  15432. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15433. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15434. var img;
  15435. var onload = function () {
  15436. loadedImages[index] = img;
  15437. loadedImages._internalCount++;
  15438. if (scene) {
  15439. scene._removePendingData(img);
  15440. }
  15441. if (loadedImages._internalCount === 6) {
  15442. onfinish(loadedImages);
  15443. }
  15444. };
  15445. var onerror = function (message, exception) {
  15446. if (scene) {
  15447. scene._removePendingData(img);
  15448. }
  15449. if (onErrorCallBack) {
  15450. onErrorCallBack(message, exception);
  15451. }
  15452. };
  15453. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  15454. if (scene) {
  15455. scene._addPendingData(img);
  15456. }
  15457. };
  15458. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15459. if (onError === void 0) { onError = null; }
  15460. var loadedImages = [];
  15461. loadedImages._internalCount = 0;
  15462. for (var index = 0; index < 6; index++) {
  15463. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15464. }
  15465. };
  15466. /** @hidden */
  15467. Engine.prototype._createTexture = function () {
  15468. var texture = this._gl.createTexture();
  15469. if (!texture) {
  15470. throw new Error("Unable to create texture");
  15471. }
  15472. return texture;
  15473. };
  15474. /**
  15475. * Usually called from BABYLON.Texture.ts.
  15476. * Passed information to create a WebGLTexture
  15477. * @param urlArg defines a value which contains one of the following:
  15478. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15479. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15480. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15481. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15482. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15483. * @param scene needed for loading to the correct scene
  15484. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15485. * @param onLoad optional callback to be called upon successful completion
  15486. * @param onError optional callback to be called upon failure
  15487. * @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
  15488. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15489. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15490. * @param forcedExtension defines the extension to use to pick the right loader
  15491. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15492. */
  15493. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15494. var _this = this;
  15495. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15496. if (onLoad === void 0) { onLoad = null; }
  15497. if (onError === void 0) { onError = null; }
  15498. if (buffer === void 0) { buffer = null; }
  15499. if (fallback === void 0) { fallback = null; }
  15500. if (format === void 0) { format = null; }
  15501. if (forcedExtension === void 0) { forcedExtension = null; }
  15502. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15503. var fromData = url.substr(0, 5) === "data:";
  15504. var fromBlob = url.substr(0, 5) === "blob:";
  15505. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15506. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15507. // establish the file extension, if possible
  15508. var lastDot = url.lastIndexOf('.');
  15509. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15510. var loader = null;
  15511. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15512. var availableLoader = _a[_i];
  15513. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15514. loader = availableLoader;
  15515. break;
  15516. }
  15517. }
  15518. if (loader) {
  15519. url = loader.transformUrl(url, this._textureFormatInUse);
  15520. }
  15521. if (scene) {
  15522. scene._addPendingData(texture);
  15523. }
  15524. texture.url = url;
  15525. texture.generateMipMaps = !noMipmap;
  15526. texture.samplingMode = samplingMode;
  15527. texture.invertY = invertY;
  15528. if (!this._doNotHandleContextLost) {
  15529. // Keep a link to the buffer only if we plan to handle context lost
  15530. texture._buffer = buffer;
  15531. }
  15532. var onLoadObserver = null;
  15533. if (onLoad && !fallback) {
  15534. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15535. }
  15536. if (!fallback) {
  15537. this._internalTexturesCache.push(texture);
  15538. }
  15539. var onInternalError = function (message, exception) {
  15540. if (scene) {
  15541. scene._removePendingData(texture);
  15542. }
  15543. var customFallback = false;
  15544. if (loader) {
  15545. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15546. if (fallbackUrl) {
  15547. // Add Back
  15548. customFallback = true;
  15549. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15550. }
  15551. }
  15552. if (!customFallback) {
  15553. if (onLoadObserver) {
  15554. texture.onLoadedObservable.remove(onLoadObserver);
  15555. }
  15556. if (BABYLON.Tools.UseFallbackTexture) {
  15557. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15558. }
  15559. }
  15560. if (onError) {
  15561. onError(message || "Unknown error", exception);
  15562. }
  15563. };
  15564. // processing for non-image formats
  15565. if (loader) {
  15566. var callback = function (data) {
  15567. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15568. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15569. done();
  15570. return false;
  15571. }, samplingMode);
  15572. });
  15573. };
  15574. if (!buffer) {
  15575. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
  15576. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15577. });
  15578. }
  15579. else {
  15580. callback(buffer);
  15581. }
  15582. }
  15583. else {
  15584. var onload = function (img) {
  15585. if (fromBlob && !_this._doNotHandleContextLost) {
  15586. // We need to store the image if we need to rebuild the texture
  15587. // in case of a webgl context lost
  15588. texture._buffer = img;
  15589. }
  15590. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15591. var gl = _this._gl;
  15592. var isPot = (img.width === potWidth && img.height === potHeight);
  15593. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15594. if (isPot) {
  15595. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15596. return false;
  15597. }
  15598. var maxTextureSize = _this._caps.maxTextureSize;
  15599. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15600. _this._prepareWorkingCanvas();
  15601. if (!_this._workingCanvas || !_this._workingContext) {
  15602. return false;
  15603. }
  15604. _this._workingCanvas.width = potWidth;
  15605. _this._workingCanvas.height = potHeight;
  15606. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15607. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15608. texture.width = potWidth;
  15609. texture.height = potHeight;
  15610. return false;
  15611. }
  15612. else {
  15613. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15614. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15615. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15616. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15617. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15618. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15619. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15620. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15621. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15622. _this._releaseTexture(source_1);
  15623. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15624. continuationCallback();
  15625. });
  15626. }
  15627. return true;
  15628. }, samplingMode);
  15629. };
  15630. if (!fromData || isBase64) {
  15631. if (buffer instanceof HTMLImageElement) {
  15632. onload(buffer);
  15633. }
  15634. else {
  15635. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  15636. }
  15637. }
  15638. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15639. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  15640. }
  15641. else {
  15642. onload(buffer);
  15643. }
  15644. }
  15645. return texture;
  15646. };
  15647. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15648. var _this = this;
  15649. var rtt = this.createRenderTargetTexture({
  15650. width: destination.width,
  15651. height: destination.height,
  15652. }, {
  15653. generateMipMaps: false,
  15654. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15655. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15656. generateDepthBuffer: false,
  15657. generateStencilBuffer: false
  15658. });
  15659. if (!this._rescalePostProcess) {
  15660. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15661. }
  15662. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15663. _this._rescalePostProcess.onApply = function (effect) {
  15664. effect._bindTexture("textureSampler", source);
  15665. };
  15666. var hostingScene = scene;
  15667. if (!hostingScene) {
  15668. hostingScene = _this.scenes[_this.scenes.length - 1];
  15669. }
  15670. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15671. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15672. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15673. _this.unBindFramebuffer(rtt);
  15674. _this._releaseTexture(rtt);
  15675. if (onComplete) {
  15676. onComplete();
  15677. }
  15678. });
  15679. };
  15680. /**
  15681. * Update a raw texture
  15682. * @param texture defines the texture to update
  15683. * @param data defines the data to store in the texture
  15684. * @param format defines the format of the data
  15685. * @param invertY defines if data must be stored with Y axis inverted
  15686. * @param compression defines the compression used (null by default)
  15687. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15688. */
  15689. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15690. if (compression === void 0) { compression = null; }
  15691. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15692. if (!texture) {
  15693. return;
  15694. }
  15695. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15696. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15697. // babylon's internalFormat but gl's texImage2D format
  15698. var internalFormat = this._getInternalFormat(format);
  15699. var textureType = this._getWebGLTextureType(type);
  15700. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15701. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15702. if (!this._doNotHandleContextLost) {
  15703. texture._bufferView = data;
  15704. texture.format = format;
  15705. texture.type = type;
  15706. texture.invertY = invertY;
  15707. texture._compression = compression;
  15708. }
  15709. if (texture.width % 4 !== 0) {
  15710. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15711. }
  15712. if (compression && data) {
  15713. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15714. }
  15715. else {
  15716. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15717. }
  15718. if (texture.generateMipMaps) {
  15719. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15720. }
  15721. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15722. // this.resetTextureCache();
  15723. texture.isReady = true;
  15724. };
  15725. /**
  15726. * Creates a raw texture
  15727. * @param data defines the data to store in the texture
  15728. * @param width defines the width of the texture
  15729. * @param height defines the height of the texture
  15730. * @param format defines the format of the data
  15731. * @param generateMipMaps defines if the engine should generate the mip levels
  15732. * @param invertY defines if data must be stored with Y axis inverted
  15733. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15734. * @param compression defines the compression used (null by default)
  15735. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15736. * @returns the raw texture inside an InternalTexture
  15737. */
  15738. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15739. if (compression === void 0) { compression = null; }
  15740. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15742. texture.baseWidth = width;
  15743. texture.baseHeight = height;
  15744. texture.width = width;
  15745. texture.height = height;
  15746. texture.format = format;
  15747. texture.generateMipMaps = generateMipMaps;
  15748. texture.samplingMode = samplingMode;
  15749. texture.invertY = invertY;
  15750. texture._compression = compression;
  15751. texture.type = type;
  15752. if (!this._doNotHandleContextLost) {
  15753. texture._bufferView = data;
  15754. }
  15755. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15756. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15757. // Filters
  15758. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15759. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15760. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15761. if (generateMipMaps) {
  15762. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15763. }
  15764. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15765. this._internalTexturesCache.push(texture);
  15766. return texture;
  15767. };
  15768. /** @hidden */
  15769. Engine.prototype._unpackFlipY = function (value) {
  15770. if (this._unpackFlipYCached !== value) {
  15771. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15772. if (this.enableUnpackFlipYCached) {
  15773. this._unpackFlipYCached = value;
  15774. }
  15775. }
  15776. };
  15777. /** @hidden */
  15778. Engine.prototype._getUnpackAlignement = function () {
  15779. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15780. };
  15781. /**
  15782. * Creates a dynamic texture
  15783. * @param width defines the width of the texture
  15784. * @param height defines the height of the texture
  15785. * @param generateMipMaps defines if the engine should generate the mip levels
  15786. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15787. * @returns the dynamic texture inside an InternalTexture
  15788. */
  15789. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15790. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15791. texture.baseWidth = width;
  15792. texture.baseHeight = height;
  15793. if (generateMipMaps) {
  15794. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15795. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15796. }
  15797. // this.resetTextureCache();
  15798. texture.width = width;
  15799. texture.height = height;
  15800. texture.isReady = false;
  15801. texture.generateMipMaps = generateMipMaps;
  15802. texture.samplingMode = samplingMode;
  15803. this.updateTextureSamplingMode(samplingMode, texture);
  15804. this._internalTexturesCache.push(texture);
  15805. return texture;
  15806. };
  15807. /**
  15808. * Update the sampling mode of a given texture
  15809. * @param samplingMode defines the required sampling mode
  15810. * @param texture defines the texture to update
  15811. */
  15812. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15813. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15814. if (texture.isCube) {
  15815. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15816. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15817. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15818. }
  15819. else if (texture.is3D) {
  15820. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15821. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15822. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15823. }
  15824. else {
  15825. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15826. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15827. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15828. }
  15829. texture.samplingMode = samplingMode;
  15830. };
  15831. /**
  15832. * Update the content of a dynamic texture
  15833. * @param texture defines the texture to update
  15834. * @param canvas defines the canvas containing the source
  15835. * @param invertY defines if data must be stored with Y axis inverted
  15836. * @param premulAlpha defines if alpha is stored as premultiplied
  15837. * @param format defines the format of the data
  15838. */
  15839. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15840. if (premulAlpha === void 0) { premulAlpha = false; }
  15841. if (!texture) {
  15842. return;
  15843. }
  15844. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15845. this._unpackFlipY(invertY);
  15846. if (premulAlpha) {
  15847. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15848. }
  15849. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15850. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15851. if (texture.generateMipMaps) {
  15852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15853. }
  15854. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15855. if (premulAlpha) {
  15856. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15857. }
  15858. texture.isReady = true;
  15859. };
  15860. /**
  15861. * Update a video texture
  15862. * @param texture defines the texture to update
  15863. * @param video defines the video element to use
  15864. * @param invertY defines if data must be stored with Y axis inverted
  15865. */
  15866. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15867. if (!texture || texture._isDisabled) {
  15868. return;
  15869. }
  15870. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15871. this._unpackFlipY(!invertY); // Video are upside down by default
  15872. try {
  15873. // Testing video texture support
  15874. if (this._videoTextureSupported === undefined) {
  15875. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15876. if (this._gl.getError() !== 0) {
  15877. this._videoTextureSupported = false;
  15878. }
  15879. else {
  15880. this._videoTextureSupported = true;
  15881. }
  15882. }
  15883. // Copy video through the current working canvas if video texture is not supported
  15884. if (!this._videoTextureSupported) {
  15885. if (!texture._workingCanvas) {
  15886. texture._workingCanvas = document.createElement("canvas");
  15887. var context = texture._workingCanvas.getContext("2d");
  15888. if (!context) {
  15889. throw new Error("Unable to get 2d context");
  15890. }
  15891. texture._workingContext = context;
  15892. texture._workingCanvas.width = texture.width;
  15893. texture._workingCanvas.height = texture.height;
  15894. }
  15895. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15896. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15897. }
  15898. else {
  15899. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15900. }
  15901. if (texture.generateMipMaps) {
  15902. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15903. }
  15904. if (!wasPreviouslyBound) {
  15905. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15906. }
  15907. // this.resetTextureCache();
  15908. texture.isReady = true;
  15909. }
  15910. catch (ex) {
  15911. // Something unexpected
  15912. // Let's disable the texture
  15913. texture._isDisabled = true;
  15914. }
  15915. };
  15916. /**
  15917. * Updates a depth texture Comparison Mode and Function.
  15918. * If the comparison Function is equal to 0, the mode will be set to none.
  15919. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15920. * @param texture The texture to set the comparison function for
  15921. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15922. */
  15923. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15924. if (this.webGLVersion === 1) {
  15925. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15926. return;
  15927. }
  15928. var gl = this._gl;
  15929. if (texture.isCube) {
  15930. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15931. if (comparisonFunction === 0) {
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15934. }
  15935. else {
  15936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15938. }
  15939. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15940. }
  15941. else {
  15942. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15943. if (comparisonFunction === 0) {
  15944. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15945. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15946. }
  15947. else {
  15948. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15949. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15950. }
  15951. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15952. }
  15953. texture._comparisonFunction = comparisonFunction;
  15954. };
  15955. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15956. var width = size.width || size;
  15957. var height = size.height || size;
  15958. internalTexture.baseWidth = width;
  15959. internalTexture.baseHeight = height;
  15960. internalTexture.width = width;
  15961. internalTexture.height = height;
  15962. internalTexture.isReady = true;
  15963. internalTexture.samples = 1;
  15964. internalTexture.generateMipMaps = false;
  15965. internalTexture._generateDepthBuffer = true;
  15966. internalTexture._generateStencilBuffer = generateStencil;
  15967. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15968. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15969. internalTexture._comparisonFunction = comparisonFunction;
  15970. var gl = this._gl;
  15971. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15972. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15973. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15974. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15975. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15976. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15977. if (comparisonFunction === 0) {
  15978. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15979. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15980. }
  15981. else {
  15982. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15983. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15984. }
  15985. };
  15986. /**
  15987. * Creates a depth stencil texture.
  15988. * This is only available in WebGL 2 or with the depth texture extension available.
  15989. * @param size The size of face edge in the texture.
  15990. * @param options The options defining the texture.
  15991. * @returns The texture
  15992. */
  15993. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15994. if (options.isCube) {
  15995. var width = size.width || size;
  15996. return this._createDepthStencilCubeTexture(width, options);
  15997. }
  15998. else {
  15999. return this._createDepthStencilTexture(size, options);
  16000. }
  16001. };
  16002. /**
  16003. * Creates a depth stencil texture.
  16004. * This is only available in WebGL 2 or with the depth texture extension available.
  16005. * @param size The size of face edge in the texture.
  16006. * @param options The options defining the texture.
  16007. * @returns The texture
  16008. */
  16009. Engine.prototype._createDepthStencilTexture = function (size, options) {
  16010. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  16011. if (!this._caps.depthTextureExtension) {
  16012. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  16013. return internalTexture;
  16014. }
  16015. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16016. var gl = this._gl;
  16017. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  16018. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16019. if (this.webGLVersion > 1) {
  16020. if (internalOptions.generateStencil) {
  16021. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16022. }
  16023. else {
  16024. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16025. }
  16026. }
  16027. else {
  16028. if (internalOptions.generateStencil) {
  16029. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16030. }
  16031. else {
  16032. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16033. }
  16034. }
  16035. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16036. return internalTexture;
  16037. };
  16038. /**
  16039. * Creates a depth stencil cube texture.
  16040. * This is only available in WebGL 2.
  16041. * @param size The size of face edge in the cube texture.
  16042. * @param options The options defining the cube texture.
  16043. * @returns The cube texture
  16044. */
  16045. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  16046. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  16047. internalTexture.isCube = true;
  16048. if (this.webGLVersion === 1) {
  16049. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  16050. return internalTexture;
  16051. }
  16052. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16053. var gl = this._gl;
  16054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  16055. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16056. // Create the depth/stencil buffer
  16057. for (var face = 0; face < 6; face++) {
  16058. if (internalOptions.generateStencil) {
  16059. 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);
  16060. }
  16061. else {
  16062. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16063. }
  16064. }
  16065. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16066. return internalTexture;
  16067. };
  16068. /**
  16069. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  16070. * @param renderTarget The render target to set the frame buffer for
  16071. */
  16072. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  16073. // Create the framebuffer
  16074. var internalTexture = renderTarget.getInternalTexture();
  16075. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  16076. return;
  16077. }
  16078. var gl = this._gl;
  16079. var depthStencilTexture = renderTarget.depthStencilTexture;
  16080. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  16081. if (depthStencilTexture.isCube) {
  16082. if (depthStencilTexture._generateStencilBuffer) {
  16083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16084. }
  16085. else {
  16086. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16087. }
  16088. }
  16089. else {
  16090. if (depthStencilTexture._generateStencilBuffer) {
  16091. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16092. }
  16093. else {
  16094. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16095. }
  16096. }
  16097. this.bindUnboundFramebuffer(null);
  16098. };
  16099. /**
  16100. * Creates a new render target texture
  16101. * @param size defines the size of the texture
  16102. * @param options defines the options used to create the texture
  16103. * @returns a new render target texture stored in an InternalTexture
  16104. */
  16105. Engine.prototype.createRenderTargetTexture = function (size, options) {
  16106. var fullOptions = new RenderTargetCreationOptions();
  16107. if (options !== undefined && typeof options === "object") {
  16108. fullOptions.generateMipMaps = options.generateMipMaps;
  16109. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16110. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  16111. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  16112. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  16113. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  16114. }
  16115. else {
  16116. fullOptions.generateMipMaps = options;
  16117. fullOptions.generateDepthBuffer = true;
  16118. fullOptions.generateStencilBuffer = false;
  16119. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16120. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16121. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  16122. }
  16123. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16124. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16125. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16126. }
  16127. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16128. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16129. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16130. }
  16131. var gl = this._gl;
  16132. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16133. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16134. var width = size.width || size;
  16135. var height = size.height || size;
  16136. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16137. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16138. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16139. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16140. }
  16141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16145. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16146. // Create the framebuffer
  16147. var currentFrameBuffer = this._currentFramebuffer;
  16148. var framebuffer = gl.createFramebuffer();
  16149. this.bindUnboundFramebuffer(framebuffer);
  16150. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16151. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16152. if (fullOptions.generateMipMaps) {
  16153. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16154. }
  16155. // Unbind
  16156. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16157. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16158. this.bindUnboundFramebuffer(currentFrameBuffer);
  16159. texture._framebuffer = framebuffer;
  16160. texture.baseWidth = width;
  16161. texture.baseHeight = height;
  16162. texture.width = width;
  16163. texture.height = height;
  16164. texture.isReady = true;
  16165. texture.samples = 1;
  16166. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16167. texture.samplingMode = fullOptions.samplingMode;
  16168. texture.type = fullOptions.type;
  16169. texture.format = fullOptions.format;
  16170. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16171. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16172. // this.resetTextureCache();
  16173. this._internalTexturesCache.push(texture);
  16174. return texture;
  16175. };
  16176. /**
  16177. * Create a multi render target texture
  16178. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16179. * @param size defines the size of the texture
  16180. * @param options defines the creation options
  16181. * @returns the cube texture as an InternalTexture
  16182. */
  16183. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16184. var generateMipMaps = false;
  16185. var generateDepthBuffer = true;
  16186. var generateStencilBuffer = false;
  16187. var generateDepthTexture = false;
  16188. var textureCount = 1;
  16189. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16190. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16191. var types = new Array();
  16192. var samplingModes = new Array();
  16193. if (options !== undefined) {
  16194. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16195. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16196. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16197. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16198. textureCount = options.textureCount || 1;
  16199. if (options.types) {
  16200. types = options.types;
  16201. }
  16202. if (options.samplingModes) {
  16203. samplingModes = options.samplingModes;
  16204. }
  16205. }
  16206. var gl = this._gl;
  16207. // Create the framebuffer
  16208. var framebuffer = gl.createFramebuffer();
  16209. this.bindUnboundFramebuffer(framebuffer);
  16210. var width = size.width || size;
  16211. var height = size.height || size;
  16212. var textures = [];
  16213. var attachments = [];
  16214. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16215. for (var i = 0; i < textureCount; i++) {
  16216. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16217. var type = types[i] || defaultType;
  16218. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16219. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16220. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16221. }
  16222. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16223. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16224. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16225. }
  16226. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16227. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16228. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16229. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16230. }
  16231. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16232. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16233. textures.push(texture);
  16234. attachments.push(attachment);
  16235. gl.activeTexture(gl["TEXTURE" + i]);
  16236. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16241. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16242. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16243. if (generateMipMaps) {
  16244. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16245. }
  16246. // Unbind
  16247. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16248. texture._framebuffer = framebuffer;
  16249. texture._depthStencilBuffer = depthStencilBuffer;
  16250. texture.baseWidth = width;
  16251. texture.baseHeight = height;
  16252. texture.width = width;
  16253. texture.height = height;
  16254. texture.isReady = true;
  16255. texture.samples = 1;
  16256. texture.generateMipMaps = generateMipMaps;
  16257. texture.samplingMode = samplingMode;
  16258. texture.type = type;
  16259. texture._generateDepthBuffer = generateDepthBuffer;
  16260. texture._generateStencilBuffer = generateStencilBuffer;
  16261. texture._attachments = attachments;
  16262. this._internalTexturesCache.push(texture);
  16263. }
  16264. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16265. // Depth texture
  16266. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16267. gl.activeTexture(gl.TEXTURE0);
  16268. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16273. 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);
  16274. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16275. depthTexture._framebuffer = framebuffer;
  16276. depthTexture.baseWidth = width;
  16277. depthTexture.baseHeight = height;
  16278. depthTexture.width = width;
  16279. depthTexture.height = height;
  16280. depthTexture.isReady = true;
  16281. depthTexture.samples = 1;
  16282. depthTexture.generateMipMaps = generateMipMaps;
  16283. depthTexture.samplingMode = gl.NEAREST;
  16284. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16285. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16286. textures.push(depthTexture);
  16287. this._internalTexturesCache.push(depthTexture);
  16288. }
  16289. gl.drawBuffers(attachments);
  16290. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16291. this.bindUnboundFramebuffer(null);
  16292. this.resetTextureCache();
  16293. return textures;
  16294. };
  16295. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16296. if (samples === void 0) { samples = 1; }
  16297. var depthStencilBuffer = null;
  16298. var gl = this._gl;
  16299. // Create the depth/stencil buffer
  16300. if (generateStencilBuffer) {
  16301. depthStencilBuffer = gl.createRenderbuffer();
  16302. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16303. if (samples > 1) {
  16304. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16305. }
  16306. else {
  16307. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16308. }
  16309. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16310. }
  16311. else if (generateDepthBuffer) {
  16312. depthStencilBuffer = gl.createRenderbuffer();
  16313. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16314. if (samples > 1) {
  16315. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16316. }
  16317. else {
  16318. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16319. }
  16320. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16321. }
  16322. return depthStencilBuffer;
  16323. };
  16324. /**
  16325. * Updates the sample count of a render target texture
  16326. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16327. * @param texture defines the texture to update
  16328. * @param samples defines the sample count to set
  16329. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16330. */
  16331. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16332. if (this.webGLVersion < 2 || !texture) {
  16333. return 1;
  16334. }
  16335. if (texture.samples === samples) {
  16336. return samples;
  16337. }
  16338. var gl = this._gl;
  16339. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16340. // Dispose previous render buffers
  16341. if (texture._depthStencilBuffer) {
  16342. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16343. texture._depthStencilBuffer = null;
  16344. }
  16345. if (texture._MSAAFramebuffer) {
  16346. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16347. texture._MSAAFramebuffer = null;
  16348. }
  16349. if (texture._MSAARenderBuffer) {
  16350. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16351. texture._MSAARenderBuffer = null;
  16352. }
  16353. if (samples > 1) {
  16354. var framebuffer = gl.createFramebuffer();
  16355. if (!framebuffer) {
  16356. throw new Error("Unable to create multi sampled framebuffer");
  16357. }
  16358. texture._MSAAFramebuffer = framebuffer;
  16359. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16360. var colorRenderbuffer = gl.createRenderbuffer();
  16361. if (!colorRenderbuffer) {
  16362. throw new Error("Unable to create multi sampled framebuffer");
  16363. }
  16364. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16365. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16366. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16367. texture._MSAARenderBuffer = colorRenderbuffer;
  16368. }
  16369. else {
  16370. this.bindUnboundFramebuffer(texture._framebuffer);
  16371. }
  16372. texture.samples = samples;
  16373. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16374. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16375. this.bindUnboundFramebuffer(null);
  16376. return samples;
  16377. };
  16378. /**
  16379. * Update the sample count for a given multiple render target texture
  16380. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16381. * @param textures defines the textures to update
  16382. * @param samples defines the sample count to set
  16383. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16384. */
  16385. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16386. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16387. return 1;
  16388. }
  16389. if (textures[0].samples === samples) {
  16390. return samples;
  16391. }
  16392. var gl = this._gl;
  16393. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16394. // Dispose previous render buffers
  16395. if (textures[0]._depthStencilBuffer) {
  16396. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16397. textures[0]._depthStencilBuffer = null;
  16398. }
  16399. if (textures[0]._MSAAFramebuffer) {
  16400. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16401. textures[0]._MSAAFramebuffer = null;
  16402. }
  16403. for (var i = 0; i < textures.length; i++) {
  16404. if (textures[i]._MSAARenderBuffer) {
  16405. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16406. textures[i]._MSAARenderBuffer = null;
  16407. }
  16408. }
  16409. if (samples > 1) {
  16410. var framebuffer = gl.createFramebuffer();
  16411. if (!framebuffer) {
  16412. throw new Error("Unable to create multi sampled framebuffer");
  16413. }
  16414. this.bindUnboundFramebuffer(framebuffer);
  16415. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16416. var attachments = [];
  16417. for (var i = 0; i < textures.length; i++) {
  16418. var texture = textures[i];
  16419. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16420. var colorRenderbuffer = gl.createRenderbuffer();
  16421. if (!colorRenderbuffer) {
  16422. throw new Error("Unable to create multi sampled framebuffer");
  16423. }
  16424. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16425. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16426. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16427. texture._MSAAFramebuffer = framebuffer;
  16428. texture._MSAARenderBuffer = colorRenderbuffer;
  16429. texture.samples = samples;
  16430. texture._depthStencilBuffer = depthStencilBuffer;
  16431. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16432. attachments.push(attachment);
  16433. }
  16434. gl.drawBuffers(attachments);
  16435. }
  16436. else {
  16437. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16438. }
  16439. this.bindUnboundFramebuffer(null);
  16440. return samples;
  16441. };
  16442. /** @hidden */
  16443. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16444. if (faceIndex === void 0) { faceIndex = 0; }
  16445. if (lod === void 0) { lod = 0; }
  16446. var gl = this._gl;
  16447. var target = gl.TEXTURE_2D;
  16448. if (texture.isCube) {
  16449. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16450. }
  16451. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16452. };
  16453. /** @hidden */
  16454. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16455. if (faceIndex === void 0) { faceIndex = 0; }
  16456. if (lod === void 0) { lod = 0; }
  16457. var gl = this._gl;
  16458. var textureType = this._getWebGLTextureType(texture.type);
  16459. var format = this._getInternalFormat(texture.format);
  16460. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16461. this._unpackFlipY(texture.invertY);
  16462. var target = gl.TEXTURE_2D;
  16463. if (texture.isCube) {
  16464. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16465. }
  16466. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16467. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16468. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16469. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16470. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16471. };
  16472. /** @hidden */
  16473. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16474. if (faceIndex === void 0) { faceIndex = 0; }
  16475. if (lod === void 0) { lod = 0; }
  16476. var gl = this._gl;
  16477. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16478. this._bindTextureDirectly(bindTarget, texture, true);
  16479. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16480. this._bindTextureDirectly(bindTarget, null, true);
  16481. };
  16482. /** @hidden */
  16483. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16484. if (faceIndex === void 0) { faceIndex = 0; }
  16485. if (lod === void 0) { lod = 0; }
  16486. var gl = this._gl;
  16487. var textureType = this._getWebGLTextureType(texture.type);
  16488. var format = this._getInternalFormat(texture.format);
  16489. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16490. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16491. this._bindTextureDirectly(bindTarget, texture, true);
  16492. this._unpackFlipY(texture.invertY);
  16493. var target = gl.TEXTURE_2D;
  16494. if (texture.isCube) {
  16495. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16496. }
  16497. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16498. this._bindTextureDirectly(bindTarget, null, true);
  16499. };
  16500. /**
  16501. * Creates a new render target cube texture
  16502. * @param size defines the size of the texture
  16503. * @param options defines the options used to create the texture
  16504. * @returns a new render target cube texture stored in an InternalTexture
  16505. */
  16506. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16507. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16508. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16509. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16510. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16511. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16512. }
  16513. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16514. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16515. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16516. }
  16517. var gl = this._gl;
  16518. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16519. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16520. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16521. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16522. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16523. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16524. }
  16525. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16526. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16527. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16529. for (var face = 0; face < 6; face++) {
  16530. 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);
  16531. }
  16532. // Create the framebuffer
  16533. var framebuffer = gl.createFramebuffer();
  16534. this.bindUnboundFramebuffer(framebuffer);
  16535. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16536. // MipMaps
  16537. if (fullOptions.generateMipMaps) {
  16538. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16539. }
  16540. // Unbind
  16541. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16542. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16543. this.bindUnboundFramebuffer(null);
  16544. texture._framebuffer = framebuffer;
  16545. texture.width = size;
  16546. texture.height = size;
  16547. texture.isReady = true;
  16548. texture.isCube = true;
  16549. texture.samples = 1;
  16550. texture.generateMipMaps = fullOptions.generateMipMaps;
  16551. texture.samplingMode = fullOptions.samplingMode;
  16552. texture.type = fullOptions.type;
  16553. texture.format = fullOptions.format;
  16554. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16555. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16556. this._internalTexturesCache.push(texture);
  16557. return texture;
  16558. };
  16559. /**
  16560. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16561. * @param rootUrl defines the url where the file to load is located
  16562. * @param scene defines the current scene
  16563. * @param lodScale defines scale to apply to the mip map selection
  16564. * @param lodOffset defines offset to apply to the mip map selection
  16565. * @param onLoad defines an optional callback raised when the texture is loaded
  16566. * @param onError defines an optional callback raised if there is an issue to load the texture
  16567. * @param format defines the format of the data
  16568. * @param forcedExtension defines the extension to use to pick the right loader
  16569. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16570. * @returns the cube texture as an InternalTexture
  16571. */
  16572. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16573. var _this = this;
  16574. if (onLoad === void 0) { onLoad = null; }
  16575. if (onError === void 0) { onError = null; }
  16576. if (forcedExtension === void 0) { forcedExtension = null; }
  16577. if (createPolynomials === void 0) { createPolynomials = true; }
  16578. var callback = function (loadData) {
  16579. if (!loadData) {
  16580. if (onLoad) {
  16581. onLoad(null);
  16582. }
  16583. return;
  16584. }
  16585. var texture = loadData.texture;
  16586. if (!createPolynomials) {
  16587. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16588. }
  16589. else if (loadData.info.sphericalPolynomial) {
  16590. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16591. }
  16592. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16593. if (_this._caps.textureLOD) {
  16594. // Do not add extra process if texture lod is supported.
  16595. if (onLoad) {
  16596. onLoad(texture);
  16597. }
  16598. return;
  16599. }
  16600. var mipSlices = 3;
  16601. var gl = _this._gl;
  16602. var width = loadData.width;
  16603. if (!width) {
  16604. return;
  16605. }
  16606. var textures = [];
  16607. for (var i = 0; i < mipSlices; i++) {
  16608. //compute LOD from even spacing in smoothness (matching shader calculation)
  16609. var smoothness = i / (mipSlices - 1);
  16610. var roughness = 1 - smoothness;
  16611. var minLODIndex = lodOffset; // roughness = 0
  16612. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16613. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16614. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16615. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16616. glTextureFromLod.type = texture.type;
  16617. glTextureFromLod.format = texture.format;
  16618. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16619. glTextureFromLod.height = glTextureFromLod.width;
  16620. glTextureFromLod.isCube = true;
  16621. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16622. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16626. if (loadData.isDDS) {
  16627. var info = loadData.info;
  16628. var data = loadData.data;
  16629. _this._unpackFlipY(info.isCompressed);
  16630. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16631. }
  16632. else {
  16633. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16634. }
  16635. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16636. // Wrap in a base texture for easy binding.
  16637. var lodTexture = new BABYLON.BaseTexture(scene);
  16638. lodTexture.isCube = true;
  16639. lodTexture._texture = glTextureFromLod;
  16640. glTextureFromLod.isReady = true;
  16641. textures.push(lodTexture);
  16642. }
  16643. texture._lodTextureHigh = textures[2];
  16644. texture._lodTextureMid = textures[1];
  16645. texture._lodTextureLow = textures[0];
  16646. if (onLoad) {
  16647. onLoad(texture);
  16648. }
  16649. };
  16650. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16651. };
  16652. /**
  16653. * Creates a cube texture
  16654. * @param rootUrl defines the url where the files to load is located
  16655. * @param scene defines the current scene
  16656. * @param files defines the list of files to load (1 per face)
  16657. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16658. * @param onLoad defines an optional callback raised when the texture is loaded
  16659. * @param onError defines an optional callback raised if there is an issue to load the texture
  16660. * @param format defines the format of the data
  16661. * @param forcedExtension defines the extension to use to pick the right loader
  16662. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16663. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16664. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16665. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16666. * @returns the cube texture as an InternalTexture
  16667. */
  16668. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16669. var _this = this;
  16670. if (onLoad === void 0) { onLoad = null; }
  16671. if (onError === void 0) { onError = null; }
  16672. if (forcedExtension === void 0) { forcedExtension = null; }
  16673. if (createPolynomials === void 0) { createPolynomials = false; }
  16674. if (lodScale === void 0) { lodScale = 0; }
  16675. if (lodOffset === void 0) { lodOffset = 0; }
  16676. if (fallback === void 0) { fallback = null; }
  16677. var gl = this._gl;
  16678. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16679. texture.isCube = true;
  16680. texture.url = rootUrl;
  16681. texture.generateMipMaps = !noMipmap;
  16682. texture._lodGenerationScale = lodScale;
  16683. texture._lodGenerationOffset = lodOffset;
  16684. if (!this._doNotHandleContextLost) {
  16685. texture._extension = forcedExtension;
  16686. texture._files = files;
  16687. }
  16688. var lastDot = rootUrl.lastIndexOf('.');
  16689. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16690. var loader = null;
  16691. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16692. var availableLoader = _a[_i];
  16693. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16694. loader = availableLoader;
  16695. break;
  16696. }
  16697. }
  16698. var onInternalError = function (request, exception) {
  16699. if (loader) {
  16700. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16701. if (fallbackUrl) {
  16702. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16703. }
  16704. }
  16705. if (onError && request) {
  16706. onError(request.status + " " + request.statusText, exception);
  16707. }
  16708. };
  16709. if (loader) {
  16710. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16711. var onloaddata = function (data) {
  16712. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16713. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16714. };
  16715. if (files && files.length === 6) {
  16716. if (loader.supportCascades) {
  16717. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16718. }
  16719. else if (onError) {
  16720. onError("Textures type does not support cascades.");
  16721. }
  16722. }
  16723. else {
  16724. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16725. }
  16726. }
  16727. else {
  16728. if (!files) {
  16729. throw new Error("Cannot load cubemap because files were not defined");
  16730. }
  16731. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16732. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16733. var height = width;
  16734. _this._prepareWorkingCanvas();
  16735. if (!_this._workingCanvas || !_this._workingContext) {
  16736. return;
  16737. }
  16738. _this._workingCanvas.width = width;
  16739. _this._workingCanvas.height = height;
  16740. var faces = [
  16741. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16742. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16743. ];
  16744. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16745. _this._unpackFlipY(false);
  16746. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16747. for (var index = 0; index < faces.length; index++) {
  16748. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16749. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16750. }
  16751. if (!noMipmap) {
  16752. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16753. }
  16754. _this._setCubeMapTextureParams(!noMipmap);
  16755. texture.width = width;
  16756. texture.height = height;
  16757. texture.isReady = true;
  16758. if (format) {
  16759. texture.format = format;
  16760. }
  16761. texture.onLoadedObservable.notifyObservers(texture);
  16762. texture.onLoadedObservable.clear();
  16763. if (onLoad) {
  16764. onLoad();
  16765. }
  16766. }, files, onError);
  16767. }
  16768. this._internalTexturesCache.push(texture);
  16769. return texture;
  16770. };
  16771. /**
  16772. * @hidden
  16773. */
  16774. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16775. var gl = this._gl;
  16776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16780. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16781. // this.resetTextureCache();
  16782. };
  16783. /**
  16784. * Update a raw cube texture
  16785. * @param texture defines the texture to udpdate
  16786. * @param data defines the data to store
  16787. * @param format defines the data format
  16788. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16789. * @param invertY defines if data must be stored with Y axis inverted
  16790. * @param compression defines the compression used (null by default)
  16791. * @param level defines which level of the texture to update
  16792. */
  16793. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16794. if (compression === void 0) { compression = null; }
  16795. if (level === void 0) { level = 0; }
  16796. texture._bufferViewArray = data;
  16797. texture.format = format;
  16798. texture.type = type;
  16799. texture.invertY = invertY;
  16800. texture._compression = compression;
  16801. var gl = this._gl;
  16802. var textureType = this._getWebGLTextureType(type);
  16803. var internalFormat = this._getInternalFormat(format);
  16804. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16805. var needConversion = false;
  16806. if (internalFormat === gl.RGB) {
  16807. internalFormat = gl.RGBA;
  16808. needConversion = true;
  16809. }
  16810. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16811. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16812. if (texture.width % 4 !== 0) {
  16813. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16814. }
  16815. // Data are known to be in +X +Y +Z -X -Y -Z
  16816. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16817. var faceData = data[faceIndex];
  16818. if (compression) {
  16819. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16820. }
  16821. else {
  16822. if (needConversion) {
  16823. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16824. }
  16825. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16826. }
  16827. }
  16828. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16829. if (isPot && texture.generateMipMaps && level === 0) {
  16830. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16831. }
  16832. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16833. // this.resetTextureCache();
  16834. texture.isReady = true;
  16835. };
  16836. /**
  16837. * Creates a new raw cube texture
  16838. * @param data defines the array of data to use to create each face
  16839. * @param size defines the size of the textures
  16840. * @param format defines the format of the data
  16841. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16842. * @param generateMipMaps defines if the engine should generate the mip levels
  16843. * @param invertY defines if data must be stored with Y axis inverted
  16844. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16845. * @param compression defines the compression used (null by default)
  16846. * @returns the cube texture as an InternalTexture
  16847. */
  16848. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16849. if (compression === void 0) { compression = null; }
  16850. var gl = this._gl;
  16851. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16852. texture.isCube = true;
  16853. texture.format = format;
  16854. texture.type = type;
  16855. if (!this._doNotHandleContextLost) {
  16856. texture._bufferViewArray = data;
  16857. }
  16858. var textureType = this._getWebGLTextureType(type);
  16859. var internalFormat = this._getInternalFormat(format);
  16860. if (internalFormat === gl.RGB) {
  16861. internalFormat = gl.RGBA;
  16862. }
  16863. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16864. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16865. generateMipMaps = false;
  16866. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16867. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16868. }
  16869. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16870. generateMipMaps = false;
  16871. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16872. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16873. }
  16874. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16875. generateMipMaps = false;
  16876. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16877. }
  16878. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16879. generateMipMaps = false;
  16880. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16881. }
  16882. var width = size;
  16883. var height = width;
  16884. texture.width = width;
  16885. texture.height = height;
  16886. // Double check on POT to generate Mips.
  16887. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16888. if (!isPot) {
  16889. generateMipMaps = false;
  16890. }
  16891. // Upload data if needed. The texture won't be ready until then.
  16892. if (data) {
  16893. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16894. }
  16895. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16896. // Filters
  16897. if (data && generateMipMaps) {
  16898. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16899. }
  16900. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16906. texture.generateMipMaps = generateMipMaps;
  16907. return texture;
  16908. };
  16909. /**
  16910. * Creates a new raw cube texture from a specified url
  16911. * @param url defines the url where the data is located
  16912. * @param scene defines the current scene
  16913. * @param size defines the size of the textures
  16914. * @param format defines the format of the data
  16915. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16916. * @param noMipmap defines if the engine should avoid generating the mip levels
  16917. * @param callback defines a callback used to extract texture data from loaded data
  16918. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16919. * @param onLoad defines a callback called when texture is loaded
  16920. * @param onError defines a callback called if there is an error
  16921. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16922. * @param invertY defines if data must be stored with Y axis inverted
  16923. * @returns the cube texture as an InternalTexture
  16924. */
  16925. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16926. var _this = this;
  16927. if (onLoad === void 0) { onLoad = null; }
  16928. if (onError === void 0) { onError = null; }
  16929. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16930. if (invertY === void 0) { invertY = false; }
  16931. var gl = this._gl;
  16932. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16933. scene._addPendingData(texture);
  16934. texture.url = url;
  16935. this._internalTexturesCache.push(texture);
  16936. var onerror = function (request, exception) {
  16937. scene._removePendingData(texture);
  16938. if (onError && request) {
  16939. onError(request.status + " " + request.statusText, exception);
  16940. }
  16941. };
  16942. var internalCallback = function (data) {
  16943. var width = texture.width;
  16944. var faceDataArrays = callback(data);
  16945. if (!faceDataArrays) {
  16946. return;
  16947. }
  16948. if (mipmapGenerator) {
  16949. var textureType = _this._getWebGLTextureType(type);
  16950. var internalFormat = _this._getInternalFormat(format);
  16951. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16952. var needConversion = false;
  16953. if (internalFormat === gl.RGB) {
  16954. internalFormat = gl.RGBA;
  16955. needConversion = true;
  16956. }
  16957. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16958. _this._unpackFlipY(false);
  16959. var mipData = mipmapGenerator(faceDataArrays);
  16960. for (var level = 0; level < mipData.length; level++) {
  16961. var mipSize = width >> level;
  16962. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16963. var mipFaceData = mipData[level][faceIndex];
  16964. if (needConversion) {
  16965. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16966. }
  16967. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16968. }
  16969. }
  16970. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16971. }
  16972. else {
  16973. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16974. }
  16975. texture.isReady = true;
  16976. // this.resetTextureCache();
  16977. scene._removePendingData(texture);
  16978. if (onLoad) {
  16979. onLoad();
  16980. }
  16981. };
  16982. this._loadFile(url, function (data) {
  16983. internalCallback(data);
  16984. }, undefined, scene.offlineProvider, true, onerror);
  16985. return texture;
  16986. };
  16987. /**
  16988. * Update a raw 3D texture
  16989. * @param texture defines the texture to update
  16990. * @param data defines the data to store
  16991. * @param format defines the data format
  16992. * @param invertY defines if data must be stored with Y axis inverted
  16993. * @param compression defines the used compression (can be null)
  16994. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16995. */
  16996. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16997. if (compression === void 0) { compression = null; }
  16998. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16999. var internalType = this._getWebGLTextureType(textureType);
  17000. var internalFormat = this._getInternalFormat(format);
  17001. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  17002. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17003. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17004. if (!this._doNotHandleContextLost) {
  17005. texture._bufferView = data;
  17006. texture.format = format;
  17007. texture.invertY = invertY;
  17008. texture._compression = compression;
  17009. }
  17010. if (texture.width % 4 !== 0) {
  17011. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  17012. }
  17013. if (compression && data) {
  17014. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  17015. }
  17016. else {
  17017. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  17018. }
  17019. if (texture.generateMipMaps) {
  17020. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17021. }
  17022. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17023. // this.resetTextureCache();
  17024. texture.isReady = true;
  17025. };
  17026. /**
  17027. * Creates a new raw 3D texture
  17028. * @param data defines the data used to create the texture
  17029. * @param width defines the width of the texture
  17030. * @param height defines the height of the texture
  17031. * @param depth defines the depth of the texture
  17032. * @param format defines the format of the texture
  17033. * @param generateMipMaps defines if the engine must generate mip levels
  17034. * @param invertY defines if data must be stored with Y axis inverted
  17035. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17036. * @param compression defines the compressed used (can be null)
  17037. * @param textureType defines the compressed used (can be null)
  17038. * @returns a new raw 3D texture (stored in an InternalTexture)
  17039. */
  17040. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  17041. if (compression === void 0) { compression = null; }
  17042. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  17043. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  17044. texture.baseWidth = width;
  17045. texture.baseHeight = height;
  17046. texture.baseDepth = depth;
  17047. texture.width = width;
  17048. texture.height = height;
  17049. texture.depth = depth;
  17050. texture.format = format;
  17051. texture.type = textureType;
  17052. texture.generateMipMaps = generateMipMaps;
  17053. texture.samplingMode = samplingMode;
  17054. texture.is3D = true;
  17055. if (!this._doNotHandleContextLost) {
  17056. texture._bufferView = data;
  17057. }
  17058. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  17059. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17060. // Filters
  17061. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  17062. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  17063. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  17064. if (generateMipMaps) {
  17065. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17066. }
  17067. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17068. this._internalTexturesCache.push(texture);
  17069. return texture;
  17070. };
  17071. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  17072. var gl = this._gl;
  17073. if (!gl) {
  17074. return;
  17075. }
  17076. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  17077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  17078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  17079. if (!noMipmap && !isCompressed) {
  17080. gl.generateMipmap(gl.TEXTURE_2D);
  17081. }
  17082. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  17083. // this.resetTextureCache();
  17084. if (scene) {
  17085. scene._removePendingData(texture);
  17086. }
  17087. texture.onLoadedObservable.notifyObservers(texture);
  17088. texture.onLoadedObservable.clear();
  17089. };
  17090. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  17091. var _this = this;
  17092. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17093. var maxTextureSize = this.getCaps().maxTextureSize;
  17094. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  17095. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  17096. var gl = this._gl;
  17097. if (!gl) {
  17098. return;
  17099. }
  17100. if (!texture._webGLTexture) {
  17101. // this.resetTextureCache();
  17102. if (scene) {
  17103. scene._removePendingData(texture);
  17104. }
  17105. return;
  17106. }
  17107. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  17108. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17109. texture.baseWidth = width;
  17110. texture.baseHeight = height;
  17111. texture.width = potWidth;
  17112. texture.height = potHeight;
  17113. texture.isReady = true;
  17114. if (processFunction(potWidth, potHeight, function () {
  17115. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17116. })) {
  17117. // Returning as texture needs extra async steps
  17118. return;
  17119. }
  17120. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17121. };
  17122. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  17123. // Create new RGBA data container.
  17124. var rgbaData;
  17125. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  17126. rgbaData = new Float32Array(width * height * 4);
  17127. }
  17128. else {
  17129. rgbaData = new Uint32Array(width * height * 4);
  17130. }
  17131. // Convert each pixel.
  17132. for (var x = 0; x < width; x++) {
  17133. for (var y = 0; y < height; y++) {
  17134. var index = (y * width + x) * 3;
  17135. var newIndex = (y * width + x) * 4;
  17136. // Map Old Value to new value.
  17137. rgbaData[newIndex + 0] = rgbData[index + 0];
  17138. rgbaData[newIndex + 1] = rgbData[index + 1];
  17139. rgbaData[newIndex + 2] = rgbData[index + 2];
  17140. // Add fully opaque alpha channel.
  17141. rgbaData[newIndex + 3] = 1;
  17142. }
  17143. }
  17144. return rgbaData;
  17145. };
  17146. /** @hidden */
  17147. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17148. var gl = this._gl;
  17149. if (texture._framebuffer) {
  17150. gl.deleteFramebuffer(texture._framebuffer);
  17151. texture._framebuffer = null;
  17152. }
  17153. if (texture._depthStencilBuffer) {
  17154. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17155. texture._depthStencilBuffer = null;
  17156. }
  17157. if (texture._MSAAFramebuffer) {
  17158. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17159. texture._MSAAFramebuffer = null;
  17160. }
  17161. if (texture._MSAARenderBuffer) {
  17162. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17163. texture._MSAARenderBuffer = null;
  17164. }
  17165. };
  17166. /** @hidden */
  17167. Engine.prototype._releaseTexture = function (texture) {
  17168. var gl = this._gl;
  17169. this._releaseFramebufferObjects(texture);
  17170. gl.deleteTexture(texture._webGLTexture);
  17171. // Unbind channels
  17172. this.unbindAllTextures();
  17173. var index = this._internalTexturesCache.indexOf(texture);
  17174. if (index !== -1) {
  17175. this._internalTexturesCache.splice(index, 1);
  17176. }
  17177. // Integrated fixed lod samplers.
  17178. if (texture._lodTextureHigh) {
  17179. texture._lodTextureHigh.dispose();
  17180. }
  17181. if (texture._lodTextureMid) {
  17182. texture._lodTextureMid.dispose();
  17183. }
  17184. if (texture._lodTextureLow) {
  17185. texture._lodTextureLow.dispose();
  17186. }
  17187. // Set output texture of post process to null if the texture has been released/disposed
  17188. this.scenes.forEach(function (scene) {
  17189. scene.postProcesses.forEach(function (postProcess) {
  17190. if (postProcess._outputTexture == texture) {
  17191. postProcess._outputTexture = null;
  17192. }
  17193. });
  17194. scene.cameras.forEach(function (camera) {
  17195. camera._postProcesses.forEach(function (postProcess) {
  17196. if (postProcess) {
  17197. if (postProcess._outputTexture == texture) {
  17198. postProcess._outputTexture = null;
  17199. }
  17200. }
  17201. });
  17202. });
  17203. });
  17204. };
  17205. Engine.prototype.setProgram = function (program) {
  17206. if (this._currentProgram !== program) {
  17207. this._gl.useProgram(program);
  17208. this._currentProgram = program;
  17209. }
  17210. };
  17211. /**
  17212. * Binds an effect to the webGL context
  17213. * @param effect defines the effect to bind
  17214. */
  17215. Engine.prototype.bindSamplers = function (effect) {
  17216. this.setProgram(effect.getProgram());
  17217. var samplers = effect.getSamplers();
  17218. for (var index = 0; index < samplers.length; index++) {
  17219. var uniform = effect.getUniform(samplers[index]);
  17220. if (uniform) {
  17221. this._boundUniforms[index] = uniform;
  17222. }
  17223. }
  17224. this._currentEffect = null;
  17225. };
  17226. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17227. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17228. return;
  17229. }
  17230. // Remove
  17231. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17232. // Bind last to it
  17233. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17234. // Bind to dummy
  17235. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17236. };
  17237. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17238. if (!internalTexture) {
  17239. return -1;
  17240. }
  17241. internalTexture._initialSlot = channel;
  17242. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17243. if (channel !== internalTexture._designatedSlot) {
  17244. this._textureCollisions.addCount(1, false);
  17245. }
  17246. }
  17247. else {
  17248. if (channel !== internalTexture._designatedSlot) {
  17249. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17250. return internalTexture._designatedSlot;
  17251. }
  17252. else {
  17253. // No slot for this texture, let's pick a new one (if we find a free slot)
  17254. if (this._nextFreeTextureSlots.length) {
  17255. return this._nextFreeTextureSlots[0];
  17256. }
  17257. // We need to recycle the oldest bound texture, sorry.
  17258. this._textureCollisions.addCount(1, false);
  17259. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17260. }
  17261. }
  17262. }
  17263. return channel;
  17264. };
  17265. Engine.prototype._linkTrackers = function (previous, next) {
  17266. previous.next = next;
  17267. next.previous = previous;
  17268. };
  17269. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17270. var currentSlot = internalTexture._designatedSlot;
  17271. if (currentSlot === -1) {
  17272. return -1;
  17273. }
  17274. internalTexture._designatedSlot = -1;
  17275. if (this.disableTextureBindingOptimization) {
  17276. return -1;
  17277. }
  17278. // Remove from bound list
  17279. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17280. // Free the slot
  17281. this._boundTexturesCache[currentSlot] = null;
  17282. this._nextFreeTextureSlots.push(currentSlot);
  17283. return currentSlot;
  17284. };
  17285. Engine.prototype._activateCurrentTexture = function () {
  17286. if (this._currentTextureChannel !== this._activeChannel) {
  17287. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17288. this._currentTextureChannel = this._activeChannel;
  17289. }
  17290. };
  17291. /** @hidden */
  17292. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17293. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17294. if (force === void 0) { force = false; }
  17295. var wasPreviouslyBound = false;
  17296. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17297. this._activeChannel = texture._designatedSlot;
  17298. }
  17299. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17300. var isTextureForRendering = texture && texture._initialSlot > -1;
  17301. if (currentTextureBound !== texture || force) {
  17302. if (currentTextureBound) {
  17303. this._removeDesignatedSlot(currentTextureBound);
  17304. }
  17305. this._activateCurrentTexture();
  17306. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17307. this._boundTexturesCache[this._activeChannel] = texture;
  17308. if (texture) {
  17309. if (!this.disableTextureBindingOptimization) {
  17310. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17311. if (slotIndex > -1) {
  17312. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17313. }
  17314. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17315. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17316. }
  17317. texture._designatedSlot = this._activeChannel;
  17318. }
  17319. }
  17320. else if (forTextureDataUpdate) {
  17321. wasPreviouslyBound = true;
  17322. this._activateCurrentTexture();
  17323. }
  17324. if (isTextureForRendering && !forTextureDataUpdate) {
  17325. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17326. }
  17327. return wasPreviouslyBound;
  17328. };
  17329. /** @hidden */
  17330. Engine.prototype._bindTexture = function (channel, texture) {
  17331. if (channel < 0) {
  17332. return;
  17333. }
  17334. if (texture) {
  17335. channel = this._getCorrectTextureChannel(channel, texture);
  17336. }
  17337. this._activeChannel = channel;
  17338. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17339. };
  17340. /**
  17341. * Sets a texture to the webGL context from a postprocess
  17342. * @param channel defines the channel to use
  17343. * @param postProcess defines the source postprocess
  17344. */
  17345. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17346. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17347. };
  17348. /**
  17349. * Binds the output of the passed in post process to the texture channel specified
  17350. * @param channel The channel the texture should be bound to
  17351. * @param postProcess The post process which's output should be bound
  17352. */
  17353. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17354. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17355. };
  17356. /**
  17357. * Unbind all textures from the webGL context
  17358. */
  17359. Engine.prototype.unbindAllTextures = function () {
  17360. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17361. this._activeChannel = channel;
  17362. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17363. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17364. if (this.webGLVersion > 1) {
  17365. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17366. }
  17367. }
  17368. };
  17369. /**
  17370. * Sets a texture to the according uniform.
  17371. * @param channel The texture channel
  17372. * @param uniform The uniform to set
  17373. * @param texture The texture to apply
  17374. */
  17375. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17376. if (channel < 0) {
  17377. return;
  17378. }
  17379. if (uniform) {
  17380. this._boundUniforms[channel] = uniform;
  17381. }
  17382. this._setTexture(channel, texture);
  17383. };
  17384. /**
  17385. * Sets a depth stencil texture from a render target to the according uniform.
  17386. * @param channel The texture channel
  17387. * @param uniform The uniform to set
  17388. * @param texture The render target texture containing the depth stencil texture to apply
  17389. */
  17390. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17391. if (channel < 0) {
  17392. return;
  17393. }
  17394. if (uniform) {
  17395. this._boundUniforms[channel] = uniform;
  17396. }
  17397. if (!texture || !texture.depthStencilTexture) {
  17398. this._setTexture(channel, null);
  17399. }
  17400. else {
  17401. this._setTexture(channel, texture, false, true);
  17402. }
  17403. };
  17404. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17405. var uniform = this._boundUniforms[sourceSlot];
  17406. if (uniform._currentState === destination) {
  17407. return;
  17408. }
  17409. this._gl.uniform1i(uniform, destination);
  17410. uniform._currentState = destination;
  17411. };
  17412. Engine.prototype._getTextureWrapMode = function (mode) {
  17413. switch (mode) {
  17414. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17415. return this._gl.REPEAT;
  17416. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17417. return this._gl.CLAMP_TO_EDGE;
  17418. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17419. return this._gl.MIRRORED_REPEAT;
  17420. }
  17421. return this._gl.REPEAT;
  17422. };
  17423. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17424. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17425. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17426. // Not ready?
  17427. if (!texture) {
  17428. if (this._boundTexturesCache[channel] != null) {
  17429. this._activeChannel = channel;
  17430. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17431. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17432. if (this.webGLVersion > 1) {
  17433. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17434. }
  17435. }
  17436. return false;
  17437. }
  17438. // Video
  17439. if (texture.video) {
  17440. this._activeChannel = channel;
  17441. texture.update();
  17442. }
  17443. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17444. texture.delayLoad();
  17445. return false;
  17446. }
  17447. var internalTexture;
  17448. if (depthStencilTexture) {
  17449. internalTexture = texture.depthStencilTexture;
  17450. }
  17451. else if (texture.isReady()) {
  17452. internalTexture = texture.getInternalTexture();
  17453. }
  17454. else if (texture.isCube) {
  17455. internalTexture = this.emptyCubeTexture;
  17456. }
  17457. else if (texture.is3D) {
  17458. internalTexture = this.emptyTexture3D;
  17459. }
  17460. else {
  17461. internalTexture = this.emptyTexture;
  17462. }
  17463. if (!isPartOfTextureArray) {
  17464. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17465. }
  17466. var needToBind = true;
  17467. if (this._boundTexturesCache[channel] === internalTexture) {
  17468. this._moveBoundTextureOnTop(internalTexture);
  17469. if (!isPartOfTextureArray) {
  17470. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17471. }
  17472. needToBind = false;
  17473. }
  17474. this._activeChannel = channel;
  17475. if (internalTexture && internalTexture.is3D) {
  17476. if (needToBind) {
  17477. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17478. }
  17479. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17480. internalTexture._cachedWrapU = texture.wrapU;
  17481. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17482. }
  17483. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17484. internalTexture._cachedWrapV = texture.wrapV;
  17485. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17486. }
  17487. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17488. internalTexture._cachedWrapR = texture.wrapR;
  17489. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17490. }
  17491. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17492. }
  17493. else if (internalTexture && internalTexture.isCube) {
  17494. if (needToBind) {
  17495. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17496. }
  17497. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17498. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17499. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17500. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17501. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17502. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17503. }
  17504. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17505. }
  17506. else {
  17507. if (needToBind) {
  17508. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17509. }
  17510. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17511. internalTexture._cachedWrapU = texture.wrapU;
  17512. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17513. }
  17514. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17515. internalTexture._cachedWrapV = texture.wrapV;
  17516. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17517. }
  17518. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17519. }
  17520. return true;
  17521. };
  17522. /**
  17523. * Sets an array of texture to the webGL context
  17524. * @param channel defines the channel where the texture array must be set
  17525. * @param uniform defines the associated uniform location
  17526. * @param textures defines the array of textures to bind
  17527. */
  17528. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17529. if (channel < 0 || !uniform) {
  17530. return;
  17531. }
  17532. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17533. this._textureUnits = new Int32Array(textures.length);
  17534. }
  17535. for (var i = 0; i < textures.length; i++) {
  17536. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17537. }
  17538. this._gl.uniform1iv(uniform, this._textureUnits);
  17539. for (var index = 0; index < textures.length; index++) {
  17540. this._setTexture(this._textureUnits[index], textures[index], true);
  17541. }
  17542. };
  17543. /** @hidden */
  17544. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17545. var internalTexture = texture.getInternalTexture();
  17546. if (!internalTexture) {
  17547. return;
  17548. }
  17549. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17550. var value = texture.anisotropicFilteringLevel;
  17551. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17552. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17553. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17554. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17555. }
  17556. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17557. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17558. internalTexture._cachedAnisotropicFilteringLevel = value;
  17559. }
  17560. };
  17561. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17562. this._bindTextureDirectly(target, texture, true, true);
  17563. this._gl.texParameterf(target, parameter, value);
  17564. };
  17565. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17566. if (texture) {
  17567. this._bindTextureDirectly(target, texture, true, true);
  17568. }
  17569. this._gl.texParameteri(target, parameter, value);
  17570. };
  17571. /**
  17572. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17573. * @param x defines the x coordinate of the rectangle where pixels must be read
  17574. * @param y defines the y coordinate of the rectangle where pixels must be read
  17575. * @param width defines the width of the rectangle where pixels must be read
  17576. * @param height defines the height of the rectangle where pixels must be read
  17577. * @returns a Uint8Array containing RGBA colors
  17578. */
  17579. Engine.prototype.readPixels = function (x, y, width, height) {
  17580. var data = new Uint8Array(height * width * 4);
  17581. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17582. return data;
  17583. };
  17584. /**
  17585. * Add an externaly attached data from its key.
  17586. * This method call will fail and return false, if such key already exists.
  17587. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17588. * @param key the unique key that identifies the data
  17589. * @param data the data object to associate to the key for this Engine instance
  17590. * @return true if no such key were already present and the data was added successfully, false otherwise
  17591. */
  17592. Engine.prototype.addExternalData = function (key, data) {
  17593. if (!this._externalData) {
  17594. this._externalData = new BABYLON.StringDictionary();
  17595. }
  17596. return this._externalData.add(key, data);
  17597. };
  17598. /**
  17599. * Get an externaly attached data from its key
  17600. * @param key the unique key that identifies the data
  17601. * @return the associated data, if present (can be null), or undefined if not present
  17602. */
  17603. Engine.prototype.getExternalData = function (key) {
  17604. if (!this._externalData) {
  17605. this._externalData = new BABYLON.StringDictionary();
  17606. }
  17607. return this._externalData.get(key);
  17608. };
  17609. /**
  17610. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17611. * @param key the unique key that identifies the data
  17612. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17613. * @return the associated data, can be null if the factory returned null.
  17614. */
  17615. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17616. if (!this._externalData) {
  17617. this._externalData = new BABYLON.StringDictionary();
  17618. }
  17619. return this._externalData.getOrAddWithFactory(key, factory);
  17620. };
  17621. /**
  17622. * Remove an externaly attached data from the Engine instance
  17623. * @param key the unique key that identifies the data
  17624. * @return true if the data was successfully removed, false if it doesn't exist
  17625. */
  17626. Engine.prototype.removeExternalData = function (key) {
  17627. if (!this._externalData) {
  17628. this._externalData = new BABYLON.StringDictionary();
  17629. }
  17630. return this._externalData.remove(key);
  17631. };
  17632. /**
  17633. * Unbind all vertex attributes from the webGL context
  17634. */
  17635. Engine.prototype.unbindAllAttributes = function () {
  17636. if (this._mustWipeVertexAttributes) {
  17637. this._mustWipeVertexAttributes = false;
  17638. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17639. this._gl.disableVertexAttribArray(i);
  17640. this._vertexAttribArraysEnabled[i] = false;
  17641. this._currentBufferPointers[i].active = false;
  17642. }
  17643. return;
  17644. }
  17645. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17646. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17647. continue;
  17648. }
  17649. this._gl.disableVertexAttribArray(i);
  17650. this._vertexAttribArraysEnabled[i] = false;
  17651. this._currentBufferPointers[i].active = false;
  17652. }
  17653. };
  17654. /**
  17655. * 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
  17656. */
  17657. Engine.prototype.releaseEffects = function () {
  17658. for (var name in this._compiledEffects) {
  17659. this._deleteProgram(this._compiledEffects[name]._program);
  17660. }
  17661. this._compiledEffects = {};
  17662. };
  17663. /**
  17664. * Dispose and release all associated resources
  17665. */
  17666. Engine.prototype.dispose = function () {
  17667. this.hideLoadingUI();
  17668. this.stopRenderLoop();
  17669. // Release postProcesses
  17670. while (this.postProcesses.length) {
  17671. this.postProcesses[0].dispose();
  17672. }
  17673. // Empty texture
  17674. if (this._emptyTexture) {
  17675. this._releaseTexture(this._emptyTexture);
  17676. this._emptyTexture = null;
  17677. }
  17678. if (this._emptyCubeTexture) {
  17679. this._releaseTexture(this._emptyCubeTexture);
  17680. this._emptyCubeTexture = null;
  17681. }
  17682. // Rescale PP
  17683. if (this._rescalePostProcess) {
  17684. this._rescalePostProcess.dispose();
  17685. }
  17686. // Release scenes
  17687. while (this.scenes.length) {
  17688. this.scenes[0].dispose();
  17689. }
  17690. // Release audio engine
  17691. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17692. Engine.audioEngine.dispose();
  17693. }
  17694. // Release effects
  17695. this.releaseEffects();
  17696. // Unbind
  17697. this.unbindAllAttributes();
  17698. this._boundUniforms = [];
  17699. if (this._dummyFramebuffer) {
  17700. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17701. }
  17702. //WebVR
  17703. this.disableVR();
  17704. // Events
  17705. if (BABYLON.Tools.IsWindowObjectExist()) {
  17706. window.removeEventListener("blur", this._onBlur);
  17707. window.removeEventListener("focus", this._onFocus);
  17708. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17709. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17710. if (this._renderingCanvas) {
  17711. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17712. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17713. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17714. if (!this._doNotHandleContextLost) {
  17715. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17716. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17717. }
  17718. }
  17719. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17720. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17721. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17722. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17723. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17724. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17725. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17726. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17727. if (this._onVrDisplayConnect) {
  17728. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17729. if (this._onVrDisplayDisconnect) {
  17730. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17731. }
  17732. if (this._onVrDisplayPresentChange) {
  17733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17734. }
  17735. this._onVrDisplayConnect = null;
  17736. this._onVrDisplayDisconnect = null;
  17737. }
  17738. }
  17739. // Remove from Instances
  17740. var index = Engine.Instances.indexOf(this);
  17741. if (index >= 0) {
  17742. Engine.Instances.splice(index, 1);
  17743. }
  17744. this._workingCanvas = null;
  17745. this._workingContext = null;
  17746. this._currentBufferPointers = [];
  17747. this._renderingCanvas = null;
  17748. this._currentProgram = null;
  17749. this._bindedRenderFunction = null;
  17750. this.onResizeObservable.clear();
  17751. this.onCanvasBlurObservable.clear();
  17752. this.onCanvasFocusObservable.clear();
  17753. this.onCanvasPointerOutObservable.clear();
  17754. this.onBeginFrameObservable.clear();
  17755. this.onEndFrameObservable.clear();
  17756. BABYLON.Effect.ResetCache();
  17757. // Abort active requests
  17758. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17759. var request = _a[_i];
  17760. request.abort();
  17761. }
  17762. };
  17763. // Loading screen
  17764. /**
  17765. * Display the loading screen
  17766. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17767. */
  17768. Engine.prototype.displayLoadingUI = function () {
  17769. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17770. return;
  17771. }
  17772. var loadingScreen = this.loadingScreen;
  17773. if (loadingScreen) {
  17774. loadingScreen.displayLoadingUI();
  17775. }
  17776. };
  17777. /**
  17778. * Hide the loading screen
  17779. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17780. */
  17781. Engine.prototype.hideLoadingUI = function () {
  17782. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17783. return;
  17784. }
  17785. var loadingScreen = this.loadingScreen;
  17786. if (loadingScreen) {
  17787. loadingScreen.hideLoadingUI();
  17788. }
  17789. };
  17790. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17791. /**
  17792. * Gets the current loading screen object
  17793. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17794. */
  17795. get: function () {
  17796. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17797. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17798. }
  17799. return this._loadingScreen;
  17800. },
  17801. /**
  17802. * Sets the current loading screen object
  17803. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17804. */
  17805. set: function (loadingScreen) {
  17806. this._loadingScreen = loadingScreen;
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17812. /**
  17813. * Sets the current loading screen text
  17814. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17815. */
  17816. set: function (text) {
  17817. this.loadingScreen.loadingUIText = text;
  17818. },
  17819. enumerable: true,
  17820. configurable: true
  17821. });
  17822. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17823. /**
  17824. * Sets the current loading screen background color
  17825. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17826. */
  17827. set: function (color) {
  17828. this.loadingScreen.loadingUIBackgroundColor = color;
  17829. },
  17830. enumerable: true,
  17831. configurable: true
  17832. });
  17833. /**
  17834. * Attach a new callback raised when context lost event is fired
  17835. * @param callback defines the callback to call
  17836. */
  17837. Engine.prototype.attachContextLostEvent = function (callback) {
  17838. if (this._renderingCanvas) {
  17839. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17840. }
  17841. };
  17842. /**
  17843. * Attach a new callback raised when context restored event is fired
  17844. * @param callback defines the callback to call
  17845. */
  17846. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17847. if (this._renderingCanvas) {
  17848. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17849. }
  17850. };
  17851. /**
  17852. * Gets the source code of the vertex shader associated with a specific webGL program
  17853. * @param program defines the program to use
  17854. * @returns a string containing the source code of the vertex shader associated with the program
  17855. */
  17856. Engine.prototype.getVertexShaderSource = function (program) {
  17857. var shaders = this._gl.getAttachedShaders(program);
  17858. if (!shaders) {
  17859. return null;
  17860. }
  17861. return this._gl.getShaderSource(shaders[0]);
  17862. };
  17863. /**
  17864. * Gets the source code of the fragment shader associated with a specific webGL program
  17865. * @param program defines the program to use
  17866. * @returns a string containing the source code of the fragment shader associated with the program
  17867. */
  17868. Engine.prototype.getFragmentShaderSource = function (program) {
  17869. var shaders = this._gl.getAttachedShaders(program);
  17870. if (!shaders) {
  17871. return null;
  17872. }
  17873. return this._gl.getShaderSource(shaders[1]);
  17874. };
  17875. /**
  17876. * Get the current error code of the webGL context
  17877. * @returns the error code
  17878. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17879. */
  17880. Engine.prototype.getError = function () {
  17881. return this._gl.getError();
  17882. };
  17883. // FPS
  17884. /**
  17885. * Gets the current framerate
  17886. * @returns a number representing the framerate
  17887. */
  17888. Engine.prototype.getFps = function () {
  17889. return this._fps;
  17890. };
  17891. /**
  17892. * Gets the time spent between current and previous frame
  17893. * @returns a number representing the delta time in ms
  17894. */
  17895. Engine.prototype.getDeltaTime = function () {
  17896. return this._deltaTime;
  17897. };
  17898. Engine.prototype._measureFps = function () {
  17899. this._performanceMonitor.sampleFrame();
  17900. this._fps = this._performanceMonitor.averageFPS;
  17901. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17902. };
  17903. /** @hidden */
  17904. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17905. if (faceIndex === void 0) { faceIndex = -1; }
  17906. if (level === void 0) { level = 0; }
  17907. if (buffer === void 0) { buffer = null; }
  17908. var gl = this._gl;
  17909. if (!this._dummyFramebuffer) {
  17910. var dummy = gl.createFramebuffer();
  17911. if (!dummy) {
  17912. throw new Error("Unable to create dummy framebuffer");
  17913. }
  17914. this._dummyFramebuffer = dummy;
  17915. }
  17916. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17917. if (faceIndex > -1) {
  17918. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17919. }
  17920. else {
  17921. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17922. }
  17923. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17924. switch (readType) {
  17925. case gl.UNSIGNED_BYTE:
  17926. if (!buffer) {
  17927. buffer = new Uint8Array(4 * width * height);
  17928. }
  17929. readType = gl.UNSIGNED_BYTE;
  17930. break;
  17931. default:
  17932. if (!buffer) {
  17933. buffer = new Float32Array(4 * width * height);
  17934. }
  17935. readType = gl.FLOAT;
  17936. break;
  17937. }
  17938. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17939. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17940. return buffer;
  17941. };
  17942. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17943. if (this._webGLVersion > 1) {
  17944. return this._caps.colorBufferFloat;
  17945. }
  17946. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17947. };
  17948. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17949. if (this._webGLVersion > 1) {
  17950. return this._caps.colorBufferFloat;
  17951. }
  17952. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17953. };
  17954. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17955. Engine.prototype._canRenderToFramebuffer = function (type) {
  17956. var gl = this._gl;
  17957. //clear existing errors
  17958. while (gl.getError() !== gl.NO_ERROR) { }
  17959. var successful = true;
  17960. var texture = gl.createTexture();
  17961. gl.bindTexture(gl.TEXTURE_2D, texture);
  17962. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17965. var fb = gl.createFramebuffer();
  17966. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17967. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17968. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17969. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17970. successful = successful && (gl.getError() === gl.NO_ERROR);
  17971. //try render by clearing frame buffer's color buffer
  17972. if (successful) {
  17973. gl.clear(gl.COLOR_BUFFER_BIT);
  17974. successful = successful && (gl.getError() === gl.NO_ERROR);
  17975. }
  17976. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17977. if (successful) {
  17978. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17979. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17980. var readFormat = gl.RGBA;
  17981. var readType = gl.UNSIGNED_BYTE;
  17982. var buffer = new Uint8Array(4);
  17983. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17984. successful = successful && (gl.getError() === gl.NO_ERROR);
  17985. }
  17986. //clean up
  17987. gl.deleteTexture(texture);
  17988. gl.deleteFramebuffer(fb);
  17989. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17990. //clear accumulated errors
  17991. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17992. return successful;
  17993. };
  17994. /** @hidden */
  17995. Engine.prototype._getWebGLTextureType = function (type) {
  17996. if (this._webGLVersion === 1) {
  17997. switch (type) {
  17998. case Engine.TEXTURETYPE_FLOAT:
  17999. return this._gl.FLOAT;
  18000. case Engine.TEXTURETYPE_HALF_FLOAT:
  18001. return this._gl.HALF_FLOAT_OES;
  18002. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18003. return this._gl.UNSIGNED_BYTE;
  18004. }
  18005. return this._gl.UNSIGNED_BYTE;
  18006. }
  18007. switch (type) {
  18008. case Engine.TEXTURETYPE_BYTE:
  18009. return this._gl.BYTE;
  18010. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18011. return this._gl.UNSIGNED_BYTE;
  18012. case Engine.TEXTURETYPE_SHORT:
  18013. return this._gl.SHORT;
  18014. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18015. return this._gl.UNSIGNED_SHORT;
  18016. case Engine.TEXTURETYPE_INT:
  18017. return this._gl.INT;
  18018. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18019. return this._gl.UNSIGNED_INT;
  18020. case Engine.TEXTURETYPE_FLOAT:
  18021. return this._gl.FLOAT;
  18022. case Engine.TEXTURETYPE_HALF_FLOAT:
  18023. return this._gl.HALF_FLOAT;
  18024. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18025. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  18026. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18027. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  18028. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18029. return this._gl.UNSIGNED_SHORT_5_6_5;
  18030. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18031. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  18032. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  18033. return this._gl.UNSIGNED_INT_24_8;
  18034. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18035. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  18036. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18037. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  18038. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  18039. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  18040. }
  18041. return this._gl.UNSIGNED_BYTE;
  18042. };
  18043. Engine.prototype._getInternalFormat = function (format) {
  18044. var internalFormat = this._gl.RGBA;
  18045. switch (format) {
  18046. case Engine.TEXTUREFORMAT_ALPHA:
  18047. internalFormat = this._gl.ALPHA;
  18048. break;
  18049. case Engine.TEXTUREFORMAT_LUMINANCE:
  18050. internalFormat = this._gl.LUMINANCE;
  18051. break;
  18052. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18053. internalFormat = this._gl.LUMINANCE_ALPHA;
  18054. break;
  18055. case Engine.TEXTUREFORMAT_RED:
  18056. internalFormat = this._gl.RED;
  18057. break;
  18058. case Engine.TEXTUREFORMAT_RG:
  18059. internalFormat = this._gl.RG;
  18060. break;
  18061. case Engine.TEXTUREFORMAT_RGB:
  18062. internalFormat = this._gl.RGB;
  18063. break;
  18064. case Engine.TEXTUREFORMAT_RGBA:
  18065. internalFormat = this._gl.RGBA;
  18066. break;
  18067. }
  18068. if (this._webGLVersion > 1) {
  18069. switch (format) {
  18070. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18071. internalFormat = this._gl.RED_INTEGER;
  18072. break;
  18073. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18074. internalFormat = this._gl.RG_INTEGER;
  18075. break;
  18076. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18077. internalFormat = this._gl.RGB_INTEGER;
  18078. break;
  18079. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18080. internalFormat = this._gl.RGBA_INTEGER;
  18081. break;
  18082. }
  18083. }
  18084. return internalFormat;
  18085. };
  18086. /** @hidden */
  18087. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  18088. if (this._webGLVersion === 1) {
  18089. if (format !== undefined) {
  18090. switch (format) {
  18091. case Engine.TEXTUREFORMAT_ALPHA:
  18092. return this._gl.ALPHA;
  18093. case Engine.TEXTUREFORMAT_LUMINANCE:
  18094. return this._gl.LUMINANCE;
  18095. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18096. return this._gl.LUMINANCE_ALPHA;
  18097. }
  18098. }
  18099. return this._gl.RGBA;
  18100. }
  18101. switch (type) {
  18102. case Engine.TEXTURETYPE_BYTE:
  18103. switch (format) {
  18104. case Engine.TEXTUREFORMAT_RED:
  18105. return this._gl.R8_SNORM;
  18106. case Engine.TEXTUREFORMAT_RG:
  18107. return this._gl.RG8_SNORM;
  18108. case Engine.TEXTUREFORMAT_RGB:
  18109. return this._gl.RGB8_SNORM;
  18110. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18111. return this._gl.R8I;
  18112. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18113. return this._gl.RG8I;
  18114. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18115. return this._gl.RGB8I;
  18116. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18117. return this._gl.RGBA8I;
  18118. default:
  18119. return this._gl.RGBA8_SNORM;
  18120. }
  18121. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18122. switch (format) {
  18123. case Engine.TEXTUREFORMAT_RED:
  18124. return this._gl.R8;
  18125. case Engine.TEXTUREFORMAT_RG:
  18126. return this._gl.RG8;
  18127. case Engine.TEXTUREFORMAT_RGB:
  18128. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  18129. case Engine.TEXTUREFORMAT_RGBA:
  18130. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  18131. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18132. return this._gl.R8UI;
  18133. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18134. return this._gl.RG8UI;
  18135. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18136. return this._gl.RGB8UI;
  18137. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18138. return this._gl.RGBA8UI;
  18139. default:
  18140. return this._gl.RGBA8;
  18141. }
  18142. case Engine.TEXTURETYPE_SHORT:
  18143. switch (format) {
  18144. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18145. return this._gl.R16I;
  18146. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18147. return this._gl.RG16I;
  18148. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18149. return this._gl.RGB16I;
  18150. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18151. return this._gl.RGBA16I;
  18152. default:
  18153. return this._gl.RGBA16I;
  18154. }
  18155. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18156. switch (format) {
  18157. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18158. return this._gl.R16UI;
  18159. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18160. return this._gl.RG16UI;
  18161. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18162. return this._gl.RGB16UI;
  18163. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18164. return this._gl.RGBA16UI;
  18165. default:
  18166. return this._gl.RGBA16UI;
  18167. }
  18168. case Engine.TEXTURETYPE_INT:
  18169. switch (format) {
  18170. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18171. return this._gl.R32I;
  18172. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18173. return this._gl.RG32I;
  18174. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18175. return this._gl.RGB32I;
  18176. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18177. return this._gl.RGBA32I;
  18178. default:
  18179. return this._gl.RGBA32I;
  18180. }
  18181. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18182. switch (format) {
  18183. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18184. return this._gl.R32UI;
  18185. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18186. return this._gl.RG32UI;
  18187. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18188. return this._gl.RGB32UI;
  18189. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18190. return this._gl.RGBA32UI;
  18191. default:
  18192. return this._gl.RGBA32UI;
  18193. }
  18194. case Engine.TEXTURETYPE_FLOAT:
  18195. switch (format) {
  18196. case Engine.TEXTUREFORMAT_RED:
  18197. return this._gl.R32F; // By default. Other possibility is R16F.
  18198. case Engine.TEXTUREFORMAT_RG:
  18199. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18200. case Engine.TEXTUREFORMAT_RGB:
  18201. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18202. case Engine.TEXTUREFORMAT_RGBA:
  18203. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18204. default:
  18205. return this._gl.RGBA32F;
  18206. }
  18207. case Engine.TEXTURETYPE_HALF_FLOAT:
  18208. switch (format) {
  18209. case Engine.TEXTUREFORMAT_RED:
  18210. return this._gl.R16F;
  18211. case Engine.TEXTUREFORMAT_RG:
  18212. return this._gl.RG16F;
  18213. case Engine.TEXTUREFORMAT_RGB:
  18214. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18215. case Engine.TEXTUREFORMAT_RGBA:
  18216. return this._gl.RGBA16F;
  18217. default:
  18218. return this._gl.RGBA16F;
  18219. }
  18220. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18221. return this._gl.RGB565;
  18222. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18223. return this._gl.R11F_G11F_B10F;
  18224. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18225. return this._gl.RGB9_E5;
  18226. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18227. return this._gl.RGBA4;
  18228. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18229. return this._gl.RGB5_A1;
  18230. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18231. switch (format) {
  18232. case Engine.TEXTUREFORMAT_RGBA:
  18233. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18234. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18235. return this._gl.RGB10_A2UI;
  18236. default:
  18237. return this._gl.RGB10_A2;
  18238. }
  18239. }
  18240. return this._gl.RGBA8;
  18241. };
  18242. /** @hidden */
  18243. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18244. if (type === Engine.TEXTURETYPE_FLOAT) {
  18245. return this._gl.RGBA32F;
  18246. }
  18247. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18248. return this._gl.RGBA16F;
  18249. }
  18250. return this._gl.RGBA8;
  18251. };
  18252. /** @hidden */
  18253. Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  18254. var _this = this;
  18255. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  18256. this._activeRequests.push(request);
  18257. request.onCompleteObservable.add(function (request) {
  18258. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18259. });
  18260. return request;
  18261. };
  18262. /** @hidden */
  18263. Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
  18264. var _this = this;
  18265. return new Promise(function (resolve, reject) {
  18266. _this._loadFile(url, function (data) {
  18267. resolve(data);
  18268. }, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  18269. reject(exception);
  18270. });
  18271. });
  18272. };
  18273. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18274. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18275. var onload = function (data) {
  18276. loadedFiles[index] = data;
  18277. loadedFiles._internalCount++;
  18278. if (loadedFiles._internalCount === 6) {
  18279. onfinish(loadedFiles);
  18280. }
  18281. };
  18282. var onerror = function (request, exception) {
  18283. if (onErrorCallBack && request) {
  18284. onErrorCallBack(request.status + " " + request.statusText, exception);
  18285. }
  18286. };
  18287. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18288. };
  18289. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18290. if (onError === void 0) { onError = null; }
  18291. var loadedFiles = [];
  18292. loadedFiles._internalCount = 0;
  18293. for (var index = 0; index < 6; index++) {
  18294. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18295. }
  18296. };
  18297. // Statics
  18298. /**
  18299. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18300. * @returns true if the engine can be created
  18301. * @ignorenaming
  18302. */
  18303. Engine.isSupported = function () {
  18304. try {
  18305. var tempcanvas = document.createElement("canvas");
  18306. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18307. return gl != null && !!window.WebGLRenderingContext;
  18308. }
  18309. catch (e) {
  18310. return false;
  18311. }
  18312. };
  18313. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18314. Engine.ExceptionList = [
  18315. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18316. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18317. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18318. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18319. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18320. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18321. ];
  18322. /** Gets the list of created engines */
  18323. Engine.Instances = new Array();
  18324. /**
  18325. * Hidden
  18326. */
  18327. Engine._TextureLoaders = [];
  18328. // Const statics
  18329. /** Defines that alpha blending is disabled */
  18330. Engine.ALPHA_DISABLE = 0;
  18331. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18332. Engine.ALPHA_ADD = 1;
  18333. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18334. Engine.ALPHA_COMBINE = 2;
  18335. /** Defines that alpha blending to DEST - SRC * DEST */
  18336. Engine.ALPHA_SUBTRACT = 3;
  18337. /** Defines that alpha blending to SRC * DEST */
  18338. Engine.ALPHA_MULTIPLY = 4;
  18339. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18340. Engine.ALPHA_MAXIMIZED = 5;
  18341. /** Defines that alpha blending to SRC + DEST */
  18342. Engine.ALPHA_ONEONE = 6;
  18343. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18344. Engine.ALPHA_PREMULTIPLIED = 7;
  18345. /**
  18346. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18347. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18348. */
  18349. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18350. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18351. Engine.ALPHA_INTERPOLATE = 9;
  18352. /**
  18353. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18354. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18355. */
  18356. Engine.ALPHA_SCREENMODE = 10;
  18357. /** Defines that the ressource is not delayed*/
  18358. Engine.DELAYLOADSTATE_NONE = 0;
  18359. /** Defines that the ressource was successfully delay loaded */
  18360. Engine.DELAYLOADSTATE_LOADED = 1;
  18361. /** Defines that the ressource is currently delay loading */
  18362. Engine.DELAYLOADSTATE_LOADING = 2;
  18363. /** Defines that the ressource is delayed and has not started loading */
  18364. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18365. // Depht or Stencil test Constants.
  18366. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18367. Engine.NEVER = 0x0200;
  18368. /** 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 */
  18369. Engine.ALWAYS = 0x0207;
  18370. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18371. Engine.LESS = 0x0201;
  18372. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18373. Engine.EQUAL = 0x0202;
  18374. /** 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 */
  18375. Engine.LEQUAL = 0x0203;
  18376. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18377. Engine.GREATER = 0x0204;
  18378. /** 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 */
  18379. Engine.GEQUAL = 0x0206;
  18380. /** 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 */
  18381. Engine.NOTEQUAL = 0x0205;
  18382. // Stencil Actions Constants.
  18383. /** Passed to stencilOperation to specify that stencil value must be kept */
  18384. Engine.KEEP = 0x1E00;
  18385. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18386. Engine.REPLACE = 0x1E01;
  18387. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18388. Engine.INCR = 0x1E02;
  18389. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18390. Engine.DECR = 0x1E03;
  18391. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18392. Engine.INVERT = 0x150A;
  18393. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18394. Engine.INCR_WRAP = 0x8507;
  18395. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18396. Engine.DECR_WRAP = 0x8508;
  18397. /** Texture is not repeating outside of 0..1 UVs */
  18398. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18399. /** Texture is repeating outside of 0..1 UVs */
  18400. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18401. /** Texture is repeating and mirrored */
  18402. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18403. /** ALPHA */
  18404. Engine.TEXTUREFORMAT_ALPHA = 0;
  18405. /** LUMINANCE */
  18406. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18407. /** LUMINANCE_ALPHA */
  18408. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18409. /** RGB */
  18410. Engine.TEXTUREFORMAT_RGB = 4;
  18411. /** RGBA */
  18412. Engine.TEXTUREFORMAT_RGBA = 5;
  18413. /** RED */
  18414. Engine.TEXTUREFORMAT_RED = 6;
  18415. /** RED (2nd reference) */
  18416. Engine.TEXTUREFORMAT_R = 6;
  18417. /** RG */
  18418. Engine.TEXTUREFORMAT_RG = 7;
  18419. /** RED_INTEGER */
  18420. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18421. /** RED_INTEGER (2nd reference) */
  18422. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18423. /** RG_INTEGER */
  18424. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18425. /** RGB_INTEGER */
  18426. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18427. /** RGBA_INTEGER */
  18428. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18429. /** UNSIGNED_BYTE */
  18430. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18431. /** UNSIGNED_BYTE (2nd reference) */
  18432. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18433. /** FLOAT */
  18434. Engine.TEXTURETYPE_FLOAT = 1;
  18435. /** HALF_FLOAT */
  18436. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18437. /** BYTE */
  18438. Engine.TEXTURETYPE_BYTE = 3;
  18439. /** SHORT */
  18440. Engine.TEXTURETYPE_SHORT = 4;
  18441. /** UNSIGNED_SHORT */
  18442. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18443. /** INT */
  18444. Engine.TEXTURETYPE_INT = 6;
  18445. /** UNSIGNED_INT */
  18446. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18447. /** UNSIGNED_SHORT_4_4_4_4 */
  18448. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18449. /** UNSIGNED_SHORT_5_5_5_1 */
  18450. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18451. /** UNSIGNED_SHORT_5_6_5 */
  18452. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18453. /** UNSIGNED_INT_2_10_10_10_REV */
  18454. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18455. /** UNSIGNED_INT_24_8 */
  18456. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18457. /** UNSIGNED_INT_10F_11F_11F_REV */
  18458. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18459. /** UNSIGNED_INT_5_9_9_9_REV */
  18460. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18461. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18462. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18463. /** nearest is mag = nearest and min = nearest and mip = linear */
  18464. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18465. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18466. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18467. /** Trilinear is mag = linear and min = linear and mip = linear */
  18468. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18469. /** nearest is mag = nearest and min = nearest and mip = linear */
  18470. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18471. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18472. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18473. /** Trilinear is mag = linear and min = linear and mip = linear */
  18474. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18475. /** mag = nearest and min = nearest and mip = nearest */
  18476. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18477. /** mag = nearest and min = linear and mip = nearest */
  18478. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18479. /** mag = nearest and min = linear and mip = linear */
  18480. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18481. /** mag = nearest and min = linear and mip = none */
  18482. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18483. /** mag = nearest and min = nearest and mip = none */
  18484. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18485. /** mag = linear and min = nearest and mip = nearest */
  18486. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18487. /** mag = linear and min = nearest and mip = linear */
  18488. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18489. /** mag = linear and min = linear and mip = none */
  18490. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18491. /** mag = linear and min = nearest and mip = none */
  18492. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18493. /** Explicit coordinates mode */
  18494. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18495. /** Spherical coordinates mode */
  18496. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18497. /** Planar coordinates mode */
  18498. Engine.TEXTURE_PLANAR_MODE = 2;
  18499. /** Cubic coordinates mode */
  18500. Engine.TEXTURE_CUBIC_MODE = 3;
  18501. /** Projection coordinates mode */
  18502. Engine.TEXTURE_PROJECTION_MODE = 4;
  18503. /** Skybox coordinates mode */
  18504. Engine.TEXTURE_SKYBOX_MODE = 5;
  18505. /** Inverse Cubic coordinates mode */
  18506. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18507. /** Equirectangular coordinates mode */
  18508. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18509. /** Equirectangular Fixed coordinates mode */
  18510. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18511. /** Equirectangular Fixed Mirrored coordinates mode */
  18512. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18513. // Texture rescaling mode
  18514. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18515. Engine.SCALEMODE_FLOOR = 1;
  18516. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18517. Engine.SCALEMODE_NEAREST = 2;
  18518. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18519. Engine.SCALEMODE_CEILING = 3;
  18520. // Updatable statics so stick with vars here
  18521. /**
  18522. * Gets or sets the epsilon value used by collision engine
  18523. */
  18524. Engine.CollisionsEpsilon = 0.001;
  18525. /**
  18526. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18527. */
  18528. Engine.CodeRepository = "src/";
  18529. /**
  18530. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18531. */
  18532. Engine.ShadersRepository = "src/Shaders/";
  18533. return Engine;
  18534. }());
  18535. BABYLON.Engine = Engine;
  18536. })(BABYLON || (BABYLON = {}));
  18537. //# sourceMappingURL=babylon.engine.js.map
  18538. var BABYLON;
  18539. (function (BABYLON) {
  18540. /**
  18541. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18542. */
  18543. var Node = /** @class */ (function () {
  18544. /**
  18545. * Creates a new Node
  18546. * @param name the name and id to be given to this node
  18547. * @param scene the scene this node will be added to
  18548. */
  18549. function Node(name, scene) {
  18550. if (scene === void 0) { scene = null; }
  18551. /**
  18552. * Gets or sets a string used to store user defined state for the node
  18553. */
  18554. this.state = "";
  18555. /**
  18556. * Gets or sets an object used to store user defined information for the node
  18557. */
  18558. this.metadata = null;
  18559. /**
  18560. * Gets or sets a boolean used to define if the node must be serialized
  18561. */
  18562. this.doNotSerialize = false;
  18563. /** @hidden */
  18564. this._isDisposed = false;
  18565. /**
  18566. * Gets a list of Animations associated with the node
  18567. */
  18568. this.animations = new Array();
  18569. this._ranges = {};
  18570. this._isEnabled = true;
  18571. this._isParentEnabled = true;
  18572. this._isReady = true;
  18573. /** @hidden */
  18574. this._currentRenderId = -1;
  18575. this._parentRenderId = -1;
  18576. this._childRenderId = -1;
  18577. /** @hidden */
  18578. this._worldMatrix = BABYLON.Matrix.Identity();
  18579. /** @hidden */
  18580. this._worldMatrixDeterminant = 0;
  18581. /** @hidden */
  18582. this._sceneRootNodesIndex = -1;
  18583. this._animationPropertiesOverride = null;
  18584. /**
  18585. * An event triggered when the mesh is disposed
  18586. */
  18587. this.onDisposeObservable = new BABYLON.Observable();
  18588. // Behaviors
  18589. this._behaviors = new Array();
  18590. this.name = name;
  18591. this.id = name;
  18592. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18593. this.uniqueId = this._scene.getUniqueId();
  18594. this._initCache();
  18595. this.addToSceneRootNodes();
  18596. }
  18597. /**
  18598. * Add a new node constructor
  18599. * @param type defines the type name of the node to construct
  18600. * @param constructorFunc defines the constructor function
  18601. */
  18602. Node.AddNodeConstructor = function (type, constructorFunc) {
  18603. this._NodeConstructors[type] = constructorFunc;
  18604. };
  18605. /**
  18606. * Returns a node constructor based on type name
  18607. * @param type defines the type name
  18608. * @param name defines the new node name
  18609. * @param scene defines the hosting scene
  18610. * @param options defines optional options to transmit to constructors
  18611. * @returns the new constructor or null
  18612. */
  18613. Node.Construct = function (type, name, scene, options) {
  18614. var constructorFunc = this._NodeConstructors[type];
  18615. if (!constructorFunc) {
  18616. return null;
  18617. }
  18618. return constructorFunc(name, scene, options);
  18619. };
  18620. /**
  18621. * Gets a boolean indicating if the node has been disposed
  18622. * @returns true if the node was disposed
  18623. */
  18624. Node.prototype.isDisposed = function () {
  18625. return this._isDisposed;
  18626. };
  18627. Object.defineProperty(Node.prototype, "parent", {
  18628. get: function () {
  18629. return this._parentNode;
  18630. },
  18631. /**
  18632. * Gets or sets the parent of the node
  18633. */
  18634. set: function (parent) {
  18635. if (this._parentNode === parent) {
  18636. return;
  18637. }
  18638. var previousParentNode = this._parentNode;
  18639. // Remove self from list of children of parent
  18640. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18641. var index = this._parentNode._children.indexOf(this);
  18642. if (index !== -1) {
  18643. this._parentNode._children.splice(index, 1);
  18644. }
  18645. if (!parent) {
  18646. this.addToSceneRootNodes();
  18647. }
  18648. }
  18649. // Store new parent
  18650. this._parentNode = parent;
  18651. // Add as child to new parent
  18652. if (this._parentNode) {
  18653. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18654. this._parentNode._children = new Array();
  18655. }
  18656. this._parentNode._children.push(this);
  18657. if (!previousParentNode) {
  18658. this.removeFromSceneRootNodes();
  18659. }
  18660. }
  18661. // Enabled state
  18662. this._syncParentEnabledState();
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. Node.prototype.addToSceneRootNodes = function () {
  18668. if (this._sceneRootNodesIndex === -1) {
  18669. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18670. this._scene.rootNodes.push(this);
  18671. }
  18672. };
  18673. Node.prototype.removeFromSceneRootNodes = function () {
  18674. if (this._sceneRootNodesIndex !== -1) {
  18675. var rootNodes = this._scene.rootNodes;
  18676. var lastIdx = rootNodes.length - 1;
  18677. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18678. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18679. this._scene.rootNodes.pop();
  18680. this._sceneRootNodesIndex = -1;
  18681. }
  18682. };
  18683. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18684. /**
  18685. * Gets or sets the animation properties override
  18686. */
  18687. get: function () {
  18688. if (!this._animationPropertiesOverride) {
  18689. return this._scene.animationPropertiesOverride;
  18690. }
  18691. return this._animationPropertiesOverride;
  18692. },
  18693. set: function (value) {
  18694. this._animationPropertiesOverride = value;
  18695. },
  18696. enumerable: true,
  18697. configurable: true
  18698. });
  18699. /**
  18700. * Gets a string idenfifying the name of the class
  18701. * @returns "Node" string
  18702. */
  18703. Node.prototype.getClassName = function () {
  18704. return "Node";
  18705. };
  18706. Object.defineProperty(Node.prototype, "onDispose", {
  18707. /**
  18708. * Sets a callback that will be raised when the node will be disposed
  18709. */
  18710. set: function (callback) {
  18711. if (this._onDisposeObserver) {
  18712. this.onDisposeObservable.remove(this._onDisposeObserver);
  18713. }
  18714. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. /**
  18720. * Gets the scene of the node
  18721. * @returns a scene
  18722. */
  18723. Node.prototype.getScene = function () {
  18724. return this._scene;
  18725. };
  18726. /**
  18727. * Gets the engine of the node
  18728. * @returns a Engine
  18729. */
  18730. Node.prototype.getEngine = function () {
  18731. return this._scene.getEngine();
  18732. };
  18733. /**
  18734. * Attach a behavior to the node
  18735. * @see http://doc.babylonjs.com/features/behaviour
  18736. * @param behavior defines the behavior to attach
  18737. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18738. * @returns the current Node
  18739. */
  18740. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18741. var _this = this;
  18742. if (attachImmediately === void 0) { attachImmediately = false; }
  18743. var index = this._behaviors.indexOf(behavior);
  18744. if (index !== -1) {
  18745. return this;
  18746. }
  18747. behavior.init();
  18748. if (this._scene.isLoading && !attachImmediately) {
  18749. // We defer the attach when the scene will be loaded
  18750. this._scene.onDataLoadedObservable.addOnce(function () {
  18751. behavior.attach(_this);
  18752. });
  18753. }
  18754. else {
  18755. behavior.attach(this);
  18756. }
  18757. this._behaviors.push(behavior);
  18758. return this;
  18759. };
  18760. /**
  18761. * Remove an attached behavior
  18762. * @see http://doc.babylonjs.com/features/behaviour
  18763. * @param behavior defines the behavior to attach
  18764. * @returns the current Node
  18765. */
  18766. Node.prototype.removeBehavior = function (behavior) {
  18767. var index = this._behaviors.indexOf(behavior);
  18768. if (index === -1) {
  18769. return this;
  18770. }
  18771. this._behaviors[index].detach();
  18772. this._behaviors.splice(index, 1);
  18773. return this;
  18774. };
  18775. Object.defineProperty(Node.prototype, "behaviors", {
  18776. /**
  18777. * Gets the list of attached behaviors
  18778. * @see http://doc.babylonjs.com/features/behaviour
  18779. */
  18780. get: function () {
  18781. return this._behaviors;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. /**
  18787. * Gets an attached behavior by name
  18788. * @param name defines the name of the behavior to look for
  18789. * @see http://doc.babylonjs.com/features/behaviour
  18790. * @returns null if behavior was not found else the requested behavior
  18791. */
  18792. Node.prototype.getBehaviorByName = function (name) {
  18793. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18794. var behavior = _a[_i];
  18795. if (behavior.name === name) {
  18796. return behavior;
  18797. }
  18798. }
  18799. return null;
  18800. };
  18801. /**
  18802. * Returns the latest update of the World matrix
  18803. * @returns a Matrix
  18804. */
  18805. Node.prototype.getWorldMatrix = function () {
  18806. if (this._currentRenderId !== this._scene.getRenderId()) {
  18807. this.computeWorldMatrix();
  18808. }
  18809. return this._worldMatrix;
  18810. };
  18811. /** @hidden */
  18812. Node.prototype._getWorldMatrixDeterminant = function () {
  18813. return this._worldMatrixDeterminant;
  18814. };
  18815. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18816. /**
  18817. * Returns directly the latest state of the mesh World matrix.
  18818. * A Matrix is returned.
  18819. */
  18820. get: function () {
  18821. return this._worldMatrix;
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. // override it in derived class if you add new variables to the cache
  18827. // and call the parent class method
  18828. /** @hidden */
  18829. Node.prototype._initCache = function () {
  18830. this._cache = {};
  18831. this._cache.parent = undefined;
  18832. };
  18833. /** @hidden */
  18834. Node.prototype.updateCache = function (force) {
  18835. if (!force && this.isSynchronized()) {
  18836. return;
  18837. }
  18838. this._cache.parent = this.parent;
  18839. this._updateCache();
  18840. };
  18841. // override it in derived class if you add new variables to the cache
  18842. // and call the parent class method if !ignoreParentClass
  18843. /** @hidden */
  18844. Node.prototype._updateCache = function (ignoreParentClass) {
  18845. };
  18846. // override it in derived class if you add new variables to the cache
  18847. /** @hidden */
  18848. Node.prototype._isSynchronized = function () {
  18849. return true;
  18850. };
  18851. /** @hidden */
  18852. Node.prototype._markSyncedWithParent = function () {
  18853. if (this._parentNode) {
  18854. this._parentRenderId = this._parentNode._childRenderId;
  18855. }
  18856. };
  18857. /** @hidden */
  18858. Node.prototype.isSynchronizedWithParent = function () {
  18859. if (!this._parentNode) {
  18860. return true;
  18861. }
  18862. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18863. return false;
  18864. }
  18865. return this._parentNode.isSynchronized();
  18866. };
  18867. /** @hidden */
  18868. Node.prototype.isSynchronized = function () {
  18869. if (this._cache.parent != this._parentNode) {
  18870. this._cache.parent = this._parentNode;
  18871. return false;
  18872. }
  18873. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18874. return false;
  18875. }
  18876. return this._isSynchronized();
  18877. };
  18878. /**
  18879. * Is this node ready to be used/rendered
  18880. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18881. * @return true if the node is ready
  18882. */
  18883. Node.prototype.isReady = function (completeCheck) {
  18884. if (completeCheck === void 0) { completeCheck = false; }
  18885. return this._isReady;
  18886. };
  18887. /**
  18888. * Is this node enabled?
  18889. * 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
  18890. * @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
  18891. * @return whether this node (and its parent) is enabled
  18892. */
  18893. Node.prototype.isEnabled = function (checkAncestors) {
  18894. if (checkAncestors === void 0) { checkAncestors = true; }
  18895. if (checkAncestors === false) {
  18896. return this._isEnabled;
  18897. }
  18898. if (!this._isEnabled) {
  18899. return false;
  18900. }
  18901. return this._isParentEnabled;
  18902. };
  18903. /** @hidden */
  18904. Node.prototype._syncParentEnabledState = function () {
  18905. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18906. if (this._children) {
  18907. this._children.forEach(function (c) {
  18908. c._syncParentEnabledState(); // Force children to update accordingly
  18909. });
  18910. }
  18911. };
  18912. /**
  18913. * Set the enabled state of this node
  18914. * @param value defines the new enabled state
  18915. */
  18916. Node.prototype.setEnabled = function (value) {
  18917. this._isEnabled = value;
  18918. this._syncParentEnabledState();
  18919. };
  18920. /**
  18921. * Is this node a descendant of the given node?
  18922. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18923. * @param ancestor defines the parent node to inspect
  18924. * @returns a boolean indicating if this node is a descendant of the given node
  18925. */
  18926. Node.prototype.isDescendantOf = function (ancestor) {
  18927. if (this.parent) {
  18928. if (this.parent === ancestor) {
  18929. return true;
  18930. }
  18931. return this.parent.isDescendantOf(ancestor);
  18932. }
  18933. return false;
  18934. };
  18935. /** @hidden */
  18936. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18937. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18938. if (!this._children) {
  18939. return;
  18940. }
  18941. for (var index = 0; index < this._children.length; index++) {
  18942. var item = this._children[index];
  18943. if (!predicate || predicate(item)) {
  18944. results.push(item);
  18945. }
  18946. if (!directDescendantsOnly) {
  18947. item._getDescendants(results, false, predicate);
  18948. }
  18949. }
  18950. };
  18951. /**
  18952. * Will return all nodes that have this node as ascendant
  18953. * @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
  18954. * @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
  18955. * @return all children nodes of all types
  18956. */
  18957. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18958. var results = new Array();
  18959. this._getDescendants(results, directDescendantsOnly, predicate);
  18960. return results;
  18961. };
  18962. /**
  18963. * Get all child-meshes of this node
  18964. * @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
  18965. * @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
  18966. * @returns an array of AbstractMesh
  18967. */
  18968. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18969. var results = [];
  18970. this._getDescendants(results, directDescendantsOnly, function (node) {
  18971. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18972. });
  18973. return results;
  18974. };
  18975. /**
  18976. * Get all child-transformNodes of this node
  18977. * @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
  18978. * @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
  18979. * @returns an array of TransformNode
  18980. */
  18981. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18982. var results = [];
  18983. this._getDescendants(results, directDescendantsOnly, function (node) {
  18984. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18985. });
  18986. return results;
  18987. };
  18988. /**
  18989. * Get all direct children of this node
  18990. * @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
  18991. * @returns an array of Node
  18992. */
  18993. Node.prototype.getChildren = function (predicate) {
  18994. return this.getDescendants(true, predicate);
  18995. };
  18996. /** @hidden */
  18997. Node.prototype._setReady = function (state) {
  18998. if (state === this._isReady) {
  18999. return;
  19000. }
  19001. if (!state) {
  19002. this._isReady = false;
  19003. return;
  19004. }
  19005. if (this.onReady) {
  19006. this.onReady(this);
  19007. }
  19008. this._isReady = true;
  19009. };
  19010. /**
  19011. * Get an animation by name
  19012. * @param name defines the name of the animation to look for
  19013. * @returns null if not found else the requested animation
  19014. */
  19015. Node.prototype.getAnimationByName = function (name) {
  19016. for (var i = 0; i < this.animations.length; i++) {
  19017. var animation = this.animations[i];
  19018. if (animation.name === name) {
  19019. return animation;
  19020. }
  19021. }
  19022. return null;
  19023. };
  19024. /**
  19025. * Creates an animation range for this node
  19026. * @param name defines the name of the range
  19027. * @param from defines the starting key
  19028. * @param to defines the end key
  19029. */
  19030. Node.prototype.createAnimationRange = function (name, from, to) {
  19031. // check name not already in use
  19032. if (!this._ranges[name]) {
  19033. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  19034. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19035. if (this.animations[i]) {
  19036. this.animations[i].createRange(name, from, to);
  19037. }
  19038. }
  19039. }
  19040. };
  19041. /**
  19042. * Delete a specific animation range
  19043. * @param name defines the name of the range to delete
  19044. * @param deleteFrames defines if animation frames from the range must be deleted as well
  19045. */
  19046. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  19047. if (deleteFrames === void 0) { deleteFrames = true; }
  19048. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19049. if (this.animations[i]) {
  19050. this.animations[i].deleteRange(name, deleteFrames);
  19051. }
  19052. }
  19053. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  19054. };
  19055. /**
  19056. * Get an animation range by name
  19057. * @param name defines the name of the animation range to look for
  19058. * @returns null if not found else the requested animation range
  19059. */
  19060. Node.prototype.getAnimationRange = function (name) {
  19061. return this._ranges[name];
  19062. };
  19063. /**
  19064. * Will start the animation sequence
  19065. * @param name defines the range frames for animation sequence
  19066. * @param loop defines if the animation should loop (false by default)
  19067. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  19068. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  19069. * @returns the object created for this animation. If range does not exist, it will return null
  19070. */
  19071. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  19072. var range = this.getAnimationRange(name);
  19073. if (!range) {
  19074. return null;
  19075. }
  19076. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  19077. };
  19078. /**
  19079. * Serialize animation ranges into a JSON compatible object
  19080. * @returns serialization object
  19081. */
  19082. Node.prototype.serializeAnimationRanges = function () {
  19083. var serializationRanges = [];
  19084. for (var name in this._ranges) {
  19085. var localRange = this._ranges[name];
  19086. if (!localRange) {
  19087. continue;
  19088. }
  19089. var range = {};
  19090. range.name = name;
  19091. range.from = localRange.from;
  19092. range.to = localRange.to;
  19093. serializationRanges.push(range);
  19094. }
  19095. return serializationRanges;
  19096. };
  19097. /**
  19098. * Computes the world matrix of the node
  19099. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19100. * @returns the world matrix
  19101. */
  19102. Node.prototype.computeWorldMatrix = function (force) {
  19103. if (!this._worldMatrix) {
  19104. this._worldMatrix = BABYLON.Matrix.Identity();
  19105. }
  19106. return this._worldMatrix;
  19107. };
  19108. /**
  19109. * Releases resources associated with this node.
  19110. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19111. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19112. */
  19113. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19114. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19115. if (!doNotRecurse) {
  19116. var nodes = this.getDescendants(true);
  19117. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  19118. var node = nodes_1[_i];
  19119. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  19120. }
  19121. }
  19122. else {
  19123. var transformNodes = this.getChildTransformNodes(true);
  19124. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  19125. var transformNode = transformNodes_1[_a];
  19126. transformNode.parent = null;
  19127. transformNode.computeWorldMatrix(true);
  19128. }
  19129. }
  19130. if (!this.parent) {
  19131. this.removeFromSceneRootNodes();
  19132. }
  19133. else {
  19134. this.parent = null;
  19135. }
  19136. // Callback
  19137. this.onDisposeObservable.notifyObservers(this);
  19138. this.onDisposeObservable.clear();
  19139. // Behaviors
  19140. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19141. var behavior = _c[_b];
  19142. behavior.detach();
  19143. }
  19144. this._behaviors = [];
  19145. this._isDisposed = true;
  19146. };
  19147. /**
  19148. * Parse animation range data from a serialization object and store them into a given node
  19149. * @param node defines where to store the animation ranges
  19150. * @param parsedNode defines the serialization object to read data from
  19151. * @param scene defines the hosting scene
  19152. */
  19153. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19154. if (parsedNode.ranges) {
  19155. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19156. var data = parsedNode.ranges[index];
  19157. node.createAnimationRange(data.name, data.from, data.to);
  19158. }
  19159. }
  19160. };
  19161. Node._NodeConstructors = {};
  19162. __decorate([
  19163. BABYLON.serialize()
  19164. ], Node.prototype, "name", void 0);
  19165. __decorate([
  19166. BABYLON.serialize()
  19167. ], Node.prototype, "id", void 0);
  19168. __decorate([
  19169. BABYLON.serialize()
  19170. ], Node.prototype, "uniqueId", void 0);
  19171. __decorate([
  19172. BABYLON.serialize()
  19173. ], Node.prototype, "state", void 0);
  19174. __decorate([
  19175. BABYLON.serialize()
  19176. ], Node.prototype, "metadata", void 0);
  19177. return Node;
  19178. }());
  19179. BABYLON.Node = Node;
  19180. })(BABYLON || (BABYLON = {}));
  19181. //# sourceMappingURL=babylon.node.js.map
  19182. var BABYLON;
  19183. (function (BABYLON) {
  19184. // This matrix is used as a value to reset the bounding box.
  19185. var _identityMatrix = BABYLON.Matrix.Identity();
  19186. /**
  19187. * Class used to store bounding sphere information
  19188. */
  19189. var BoundingSphere = /** @class */ (function () {
  19190. /**
  19191. * Creates a new bounding sphere
  19192. * @param min defines the minimum vector (in local space)
  19193. * @param max defines the maximum vector (in local space)
  19194. * @param worldMatrix defines the new world matrix
  19195. */
  19196. function BoundingSphere(min, max, worldMatrix) {
  19197. /**
  19198. * Gets the center of the bounding sphere in local space
  19199. */
  19200. this.center = BABYLON.Vector3.Zero();
  19201. /**
  19202. * Gets the center of the bounding sphere in world space
  19203. */
  19204. this.centerWorld = BABYLON.Vector3.Zero();
  19205. /**
  19206. * Gets the minimum vector in local space
  19207. */
  19208. this.minimum = BABYLON.Vector3.Zero();
  19209. /**
  19210. * Gets the maximum vector in local space
  19211. */
  19212. this.maximum = BABYLON.Vector3.Zero();
  19213. this.reConstruct(min, max, worldMatrix);
  19214. }
  19215. /**
  19216. * Recreates the entire bounding sphere from scratch
  19217. * @param min defines the new minimum vector (in local space)
  19218. * @param max defines the new maximum vector (in local space)
  19219. * @param worldMatrix defines the new world matrix
  19220. */
  19221. BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
  19222. this.minimum.copyFrom(min);
  19223. this.maximum.copyFrom(max);
  19224. var distance = BABYLON.Vector3.Distance(min, max);
  19225. max.addToRef(min, this.center).scaleInPlace(0.5);
  19226. this.radius = distance * 0.5;
  19227. this._update(worldMatrix || _identityMatrix);
  19228. };
  19229. /**
  19230. * Scale the current bounding sphere by applying a scale factor
  19231. * @param factor defines the scale factor to apply
  19232. * @returns the current bounding box
  19233. */
  19234. BoundingSphere.prototype.scale = function (factor) {
  19235. var newRadius = this.radius * factor;
  19236. var tmpVectors = BoundingSphere.TmpVector3;
  19237. var tempRadiusVector = tmpVectors[0].setAll(newRadius);
  19238. var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
  19239. var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
  19240. this.reConstruct(min, max);
  19241. return this;
  19242. };
  19243. // Methods
  19244. /** @hidden */
  19245. BoundingSphere.prototype._update = function (world) {
  19246. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19247. var tempVector = BoundingSphere.TmpVector3[0];
  19248. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19249. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19250. };
  19251. /**
  19252. * Tests if the bounding sphere is intersecting the frustum planes
  19253. * @param frustumPlanes defines the frustum planes to test
  19254. * @returns true if there is an intersection
  19255. */
  19256. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19257. for (var i = 0; i < 6; i++) {
  19258. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19259. return false;
  19260. }
  19261. }
  19262. return true;
  19263. };
  19264. /**
  19265. * Tests if a point is inside the bounding sphere
  19266. * @param point defines the point to test
  19267. * @returns true if the point is inside the bounding sphere
  19268. */
  19269. BoundingSphere.prototype.intersectsPoint = function (point) {
  19270. var squareDistance = BABYLON.Vector3.DistanceSquared(this.centerWorld, point);
  19271. if (this.radiusWorld * this.radiusWorld < squareDistance) {
  19272. return false;
  19273. }
  19274. return true;
  19275. };
  19276. // Statics
  19277. /**
  19278. * Checks if two sphere intersct
  19279. * @param sphere0 sphere 0
  19280. * @param sphere1 sphere 1
  19281. * @returns true if the speres intersect
  19282. */
  19283. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19284. var squareDistance = BABYLON.Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
  19285. var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
  19286. if (radiusSum * radiusSum < squareDistance) {
  19287. return false;
  19288. }
  19289. return true;
  19290. };
  19291. BoundingSphere.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19292. return BoundingSphere;
  19293. }());
  19294. BABYLON.BoundingSphere = BoundingSphere;
  19295. })(BABYLON || (BABYLON = {}));
  19296. //# sourceMappingURL=babylon.boundingSphere.js.map
  19297. var BABYLON;
  19298. (function (BABYLON) {
  19299. /**
  19300. * Class used to store bounding box information
  19301. */
  19302. var BoundingBox = /** @class */ (function () {
  19303. /**
  19304. * Creates a new bounding box
  19305. * @param min defines the minimum vector (in local space)
  19306. * @param max defines the maximum vector (in local space)
  19307. * @param worldMatrix defines the new world matrix
  19308. */
  19309. function BoundingBox(min, max, worldMatrix) {
  19310. /**
  19311. * Gets the 8 vectors representing the bounding box in local space
  19312. */
  19313. this.vectors = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19314. /**
  19315. * Gets the center of the bounding box in local space
  19316. */
  19317. this.center = BABYLON.Vector3.Zero();
  19318. /**
  19319. * Gets the center of the bounding box in world space
  19320. */
  19321. this.centerWorld = BABYLON.Vector3.Zero();
  19322. /**
  19323. * Gets the extend size in local space
  19324. */
  19325. this.extendSize = BABYLON.Vector3.Zero();
  19326. /**
  19327. * Gets the extend size in world space
  19328. */
  19329. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19330. /**
  19331. * Gets the OBB (object bounding box) directions
  19332. */
  19333. this.directions = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19334. /**
  19335. * Gets the 8 vectors representing the bounding box in world space
  19336. */
  19337. this.vectorsWorld = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19338. /**
  19339. * Gets the minimum vector in world space
  19340. */
  19341. this.minimumWorld = BABYLON.Vector3.Zero();
  19342. /**
  19343. * Gets the maximum vector in world space
  19344. */
  19345. this.maximumWorld = BABYLON.Vector3.Zero();
  19346. /**
  19347. * Gets the minimum vector in local space
  19348. */
  19349. this.minimum = BABYLON.Vector3.Zero();
  19350. /**
  19351. * Gets the maximum vector in local space
  19352. */
  19353. this.maximum = BABYLON.Vector3.Zero();
  19354. this.reConstruct(min, max, worldMatrix);
  19355. }
  19356. // Methods
  19357. /**
  19358. * Recreates the entire bounding box from scratch
  19359. * @param min defines the new minimum vector (in local space)
  19360. * @param max defines the new maximum vector (in local space)
  19361. * @param worldMatrix defines the new world matrix
  19362. */
  19363. BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
  19364. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19365. var vectors = this.vectors;
  19366. this.minimum.copyFromFloats(minX, minY, minZ);
  19367. this.maximum.copyFromFloats(maxX, maxY, maxZ);
  19368. vectors[0].copyFromFloats(minX, minY, minZ);
  19369. vectors[1].copyFromFloats(maxX, maxY, maxZ);
  19370. vectors[2].copyFromFloats(maxX, minY, minZ);
  19371. vectors[3].copyFromFloats(minX, maxY, minZ);
  19372. vectors[4].copyFromFloats(minX, minY, maxZ);
  19373. vectors[5].copyFromFloats(maxX, maxY, minZ);
  19374. vectors[6].copyFromFloats(minX, maxY, maxZ);
  19375. vectors[7].copyFromFloats(maxX, minY, maxZ);
  19376. // OBB
  19377. max.addToRef(min, this.center).scaleInPlace(0.5);
  19378. max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
  19379. this._update(worldMatrix || this._worldMatrix || BABYLON.Matrix.Identity());
  19380. };
  19381. /**
  19382. * Scale the current bounding box by applying a scale factor
  19383. * @param factor defines the scale factor to apply
  19384. * @returns the current bounding box
  19385. */
  19386. BoundingBox.prototype.scale = function (factor) {
  19387. var tmpVectors = BoundingBox.TmpVector3;
  19388. var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
  19389. var len = diff.length();
  19390. diff.normalizeFromLength(len);
  19391. var distance = len * factor;
  19392. var newRadius = diff.scaleInPlace(distance * 0.5);
  19393. var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
  19394. var max = this.center.addToRef(newRadius, tmpVectors[2]);
  19395. this.reConstruct(min, max);
  19396. return this;
  19397. };
  19398. /**
  19399. * Gets the world matrix of the bounding box
  19400. * @returns a matrix
  19401. */
  19402. BoundingBox.prototype.getWorldMatrix = function () {
  19403. return this._worldMatrix;
  19404. };
  19405. /**
  19406. * Sets the world matrix stored in the bounding box
  19407. * @param matrix defines the matrix to store
  19408. * @returns current bounding box
  19409. */
  19410. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19411. this._worldMatrix.copyFrom(matrix);
  19412. return this;
  19413. };
  19414. /** @hidden */
  19415. BoundingBox.prototype._update = function (world) {
  19416. var minWorld = this.minimumWorld;
  19417. var maxWorld = this.maximumWorld;
  19418. var directions = this.directions;
  19419. minWorld.setAll(Number.MAX_VALUE);
  19420. maxWorld.setAll(-Number.MAX_VALUE);
  19421. var vectorsWorld = this.vectorsWorld;
  19422. var vectors = this.vectors;
  19423. for (var index = 0; index < 8; ++index) {
  19424. var v = vectorsWorld[index];
  19425. BABYLON.Vector3.TransformCoordinatesToRef(vectors[index], world, v);
  19426. minWorld.minimizeInPlace(v);
  19427. maxWorld.maximizeInPlace(v);
  19428. }
  19429. // Extend
  19430. maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
  19431. // OOBB
  19432. maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
  19433. BABYLON.Vector3.FromArrayToRef(world.m, 0, directions[0]);
  19434. BABYLON.Vector3.FromArrayToRef(world.m, 4, directions[1]);
  19435. BABYLON.Vector3.FromArrayToRef(world.m, 8, directions[2]);
  19436. this._worldMatrix = world;
  19437. };
  19438. /**
  19439. * Tests if the bounding box is intersecting the frustum planes
  19440. * @param frustumPlanes defines the frustum planes to test
  19441. * @returns true if there is an intersection
  19442. */
  19443. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19444. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19445. };
  19446. /**
  19447. * Tests if the bounding box is entirely inside the frustum planes
  19448. * @param frustumPlanes defines the frustum planes to test
  19449. * @returns true if there is an inclusion
  19450. */
  19451. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19452. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19453. };
  19454. /**
  19455. * Tests if a point is inside the bounding box
  19456. * @param point defines the point to test
  19457. * @returns true if the point is inside the bounding box
  19458. */
  19459. BoundingBox.prototype.intersectsPoint = function (point) {
  19460. var min = this.minimumWorld;
  19461. var max = this.maximumWorld;
  19462. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19463. var pointX = point.x, pointY = point.y, pointZ = point.z;
  19464. var delta = -BABYLON.Epsilon;
  19465. if (maxX - pointX < delta || delta > pointX - minX) {
  19466. return false;
  19467. }
  19468. if (maxY - pointY < delta || delta > pointY - minY) {
  19469. return false;
  19470. }
  19471. if (maxZ - pointZ < delta || delta > pointZ - minZ) {
  19472. return false;
  19473. }
  19474. return true;
  19475. };
  19476. /**
  19477. * Tests if the bounding box intersects with a bounding sphere
  19478. * @param sphere defines the sphere to test
  19479. * @returns true if there is an intersection
  19480. */
  19481. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19482. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19483. };
  19484. /**
  19485. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19486. * @param min defines the min vector to use
  19487. * @param max defines the max vector to use
  19488. * @returns true if there is an intersection
  19489. */
  19490. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19491. var myMin = this.minimumWorld;
  19492. var myMax = this.maximumWorld;
  19493. var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
  19494. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19495. if (myMaxX < minX || myMinX > maxX) {
  19496. return false;
  19497. }
  19498. if (myMaxY < minY || myMinY > maxY) {
  19499. return false;
  19500. }
  19501. if (myMaxZ < minZ || myMinZ > maxZ) {
  19502. return false;
  19503. }
  19504. return true;
  19505. };
  19506. // Statics
  19507. /**
  19508. * Tests if two bounding boxes are intersections
  19509. * @param box0 defines the first box to test
  19510. * @param box1 defines the second box to test
  19511. * @returns true if there is an intersection
  19512. */
  19513. BoundingBox.Intersects = function (box0, box1) {
  19514. return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  19515. };
  19516. /**
  19517. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19518. * @param minPoint defines the minimum vector of the bounding box
  19519. * @param maxPoint defines the maximum vector of the bounding box
  19520. * @param sphereCenter defines the sphere center
  19521. * @param sphereRadius defines the sphere radius
  19522. * @returns true if there is an intersection
  19523. */
  19524. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19525. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19526. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19527. return (num <= (sphereRadius * sphereRadius));
  19528. };
  19529. /**
  19530. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19531. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19532. * @param frustumPlanes defines the frustum planes to test
  19533. * @return true if there is an inclusion
  19534. */
  19535. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19536. for (var p = 0; p < 6; ++p) {
  19537. var frustumPlane = frustumPlanes[p];
  19538. for (var i = 0; i < 8; ++i) {
  19539. if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
  19540. return false;
  19541. }
  19542. }
  19543. }
  19544. return true;
  19545. };
  19546. /**
  19547. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19548. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19549. * @param frustumPlanes defines the frustum planes to test
  19550. * @return true if there is an intersection
  19551. */
  19552. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19553. for (var p = 0; p < 6; ++p) {
  19554. var canReturnFalse = true;
  19555. var frustumPlane = frustumPlanes[p];
  19556. for (var i = 0; i < 8; ++i) {
  19557. if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
  19558. canReturnFalse = false;
  19559. break;
  19560. }
  19561. }
  19562. if (canReturnFalse) {
  19563. return false;
  19564. }
  19565. }
  19566. return true;
  19567. };
  19568. BoundingBox.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19569. return BoundingBox;
  19570. }());
  19571. BABYLON.BoundingBox = BoundingBox;
  19572. })(BABYLON || (BABYLON = {}));
  19573. //# sourceMappingURL=babylon.boundingBox.js.map
  19574. var BABYLON;
  19575. (function (BABYLON) {
  19576. var computeBoxExtents = function (axis, box) {
  19577. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19578. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19579. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19580. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19581. var r = r0 + r1 + r2;
  19582. return {
  19583. min: p - r,
  19584. max: p + r
  19585. };
  19586. };
  19587. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19588. var axisOverlap = function (axis, box0, box1) {
  19589. var result0 = computeBoxExtents(axis, box0);
  19590. var result1 = computeBoxExtents(axis, box1);
  19591. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19592. };
  19593. /**
  19594. * Info for a bounding data of a mesh
  19595. */
  19596. var BoundingInfo = /** @class */ (function () {
  19597. /**
  19598. * Constructs bounding info
  19599. * @param minimum min vector of the bounding box/sphere
  19600. * @param maximum max vector of the bounding box/sphere
  19601. * @param worldMatrix defines the new world matrix
  19602. */
  19603. function BoundingInfo(minimum, maximum, worldMatrix) {
  19604. this._isLocked = false;
  19605. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum, worldMatrix);
  19606. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum, worldMatrix);
  19607. }
  19608. /**
  19609. * Recreates the entire bounding info from scratch
  19610. * @param min defines the new minimum vector (in local space)
  19611. * @param max defines the new maximum vector (in local space)
  19612. * @param worldMatrix defines the new world matrix
  19613. */
  19614. BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
  19615. this.boundingBox.reConstruct(min, max, worldMatrix);
  19616. this.boundingSphere.reConstruct(min, max, worldMatrix);
  19617. };
  19618. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19619. /**
  19620. * min vector of the bounding box/sphere
  19621. */
  19622. get: function () {
  19623. return this.boundingBox.minimum;
  19624. },
  19625. enumerable: true,
  19626. configurable: true
  19627. });
  19628. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19629. /**
  19630. * max vector of the bounding box/sphere
  19631. */
  19632. get: function () {
  19633. return this.boundingBox.maximum;
  19634. },
  19635. enumerable: true,
  19636. configurable: true
  19637. });
  19638. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19639. /**
  19640. * If the info is locked and won't be updated to avoid perf overhead
  19641. */
  19642. get: function () {
  19643. return this._isLocked;
  19644. },
  19645. set: function (value) {
  19646. this._isLocked = value;
  19647. },
  19648. enumerable: true,
  19649. configurable: true
  19650. });
  19651. // Methods
  19652. /**
  19653. * Updates the boudning sphere and box
  19654. * @param world world matrix to be used to update
  19655. */
  19656. BoundingInfo.prototype.update = function (world) {
  19657. if (this._isLocked) {
  19658. return;
  19659. }
  19660. this.boundingBox._update(world);
  19661. this.boundingSphere._update(world);
  19662. };
  19663. /**
  19664. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19665. * @param center New center of the bounding info
  19666. * @param extend New extend of the bounding info
  19667. * @returns the current bounding info
  19668. */
  19669. BoundingInfo.prototype.centerOn = function (center, extend) {
  19670. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19671. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19672. this.boundingBox.reConstruct(minimum, maximum);
  19673. this.boundingSphere.reConstruct(minimum, maximum);
  19674. return this;
  19675. };
  19676. /**
  19677. * Scale the current bounding info by applying a scale factor
  19678. * @param factor defines the scale factor to apply
  19679. * @returns the current bounding info
  19680. */
  19681. BoundingInfo.prototype.scale = function (factor) {
  19682. this.boundingBox.scale(factor);
  19683. this.boundingSphere.scale(factor);
  19684. return this;
  19685. };
  19686. /**
  19687. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19688. * @param frustumPlanes defines the frustum to test
  19689. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19690. * @returns true if the bounding info is in the frustum planes
  19691. */
  19692. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19693. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19694. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19695. return false;
  19696. }
  19697. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19698. return true;
  19699. }
  19700. return this.boundingBox.isInFrustum(frustumPlanes);
  19701. };
  19702. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19703. /**
  19704. * Gets the world distance between the min and max points of the bounding box
  19705. */
  19706. get: function () {
  19707. var boundingBox = this.boundingBox;
  19708. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19709. return size.length();
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. /**
  19715. * Checks if a cullable object (mesh...) is in the camera frustum
  19716. * Unlike isInFrustum this cheks the full bounding box
  19717. * @param frustumPlanes Camera near/planes
  19718. * @returns true if the object is in frustum otherwise false
  19719. */
  19720. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19721. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19722. };
  19723. /** @hidden */
  19724. BoundingInfo.prototype._checkCollision = function (collider) {
  19725. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19726. };
  19727. /**
  19728. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19729. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19730. * @param point the point to check intersection with
  19731. * @returns if the point intersects
  19732. */
  19733. BoundingInfo.prototype.intersectsPoint = function (point) {
  19734. if (!this.boundingSphere.centerWorld) {
  19735. return false;
  19736. }
  19737. if (!this.boundingSphere.intersectsPoint(point)) {
  19738. return false;
  19739. }
  19740. if (!this.boundingBox.intersectsPoint(point)) {
  19741. return false;
  19742. }
  19743. return true;
  19744. };
  19745. /**
  19746. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19747. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19748. * @param boundingInfo the bounding info to check intersection with
  19749. * @param precise if the intersection should be done using OBB
  19750. * @returns if the bounding info intersects
  19751. */
  19752. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19753. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19754. return false;
  19755. }
  19756. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19757. return false;
  19758. }
  19759. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19760. return false;
  19761. }
  19762. if (!precise) {
  19763. return true;
  19764. }
  19765. var box0 = this.boundingBox;
  19766. var box1 = boundingInfo.boundingBox;
  19767. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19768. return false;
  19769. }
  19770. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19771. return false;
  19772. }
  19773. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19774. return false;
  19775. }
  19776. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19777. return false;
  19778. }
  19779. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19780. return false;
  19781. }
  19782. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19783. return false;
  19784. }
  19785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19786. return false;
  19787. }
  19788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19789. return false;
  19790. }
  19791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19792. return false;
  19793. }
  19794. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19795. return false;
  19796. }
  19797. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19798. return false;
  19799. }
  19800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19801. return false;
  19802. }
  19803. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19804. return false;
  19805. }
  19806. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19807. return false;
  19808. }
  19809. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19810. return false;
  19811. }
  19812. return true;
  19813. };
  19814. return BoundingInfo;
  19815. }());
  19816. BABYLON.BoundingInfo = BoundingInfo;
  19817. })(BABYLON || (BABYLON = {}));
  19818. //# sourceMappingURL=babylon.boundingInfo.js.map
  19819. var BABYLON;
  19820. (function (BABYLON) {
  19821. /**
  19822. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19823. * @see https://doc.babylonjs.com/how_to/transformnode
  19824. */
  19825. var TransformNode = /** @class */ (function (_super) {
  19826. __extends(TransformNode, _super);
  19827. function TransformNode(name, scene, isPure) {
  19828. if (scene === void 0) { scene = null; }
  19829. if (isPure === void 0) { isPure = true; }
  19830. var _this = _super.call(this, name, scene) || this;
  19831. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19832. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19833. _this._up = new BABYLON.Vector3(0, 1, 0);
  19834. _this._right = new BABYLON.Vector3(1, 0, 0);
  19835. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19836. // Properties
  19837. _this._position = BABYLON.Vector3.Zero();
  19838. _this._rotation = BABYLON.Vector3.Zero();
  19839. _this._scaling = BABYLON.Vector3.One();
  19840. _this._isDirty = false;
  19841. /**
  19842. * Set the billboard mode. Default is 0.
  19843. *
  19844. * | Value | Type | Description |
  19845. * | --- | --- | --- |
  19846. * | 0 | BILLBOARDMODE_NONE | |
  19847. * | 1 | BILLBOARDMODE_X | |
  19848. * | 2 | BILLBOARDMODE_Y | |
  19849. * | 4 | BILLBOARDMODE_Z | |
  19850. * | 7 | BILLBOARDMODE_ALL | |
  19851. *
  19852. */
  19853. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19854. /**
  19855. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19856. */
  19857. _this.scalingDeterminant = 1;
  19858. /**
  19859. * Sets the distance of the object to max, often used by skybox
  19860. */
  19861. _this.infiniteDistance = false;
  19862. /**
  19863. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19864. * By default the system will update normals to compensate
  19865. */
  19866. _this.ignoreNonUniformScaling = false;
  19867. _this._localWorld = BABYLON.Matrix.Zero();
  19868. _this._absolutePosition = BABYLON.Vector3.Zero();
  19869. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19870. _this._postMultiplyPivotMatrix = false;
  19871. _this._isWorldMatrixFrozen = false;
  19872. /** @hidden */
  19873. _this._indexInSceneTransformNodesArray = -1;
  19874. /**
  19875. * An event triggered after the world matrix is updated
  19876. */
  19877. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19878. _this._nonUniformScaling = false;
  19879. if (isPure) {
  19880. _this.getScene().addTransformNode(_this);
  19881. }
  19882. return _this;
  19883. }
  19884. /**
  19885. * Gets a string identifying the name of the class
  19886. * @returns "TransformNode" string
  19887. */
  19888. TransformNode.prototype.getClassName = function () {
  19889. return "TransformNode";
  19890. };
  19891. Object.defineProperty(TransformNode.prototype, "position", {
  19892. /**
  19893. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19894. */
  19895. get: function () {
  19896. return this._position;
  19897. },
  19898. set: function (newPosition) {
  19899. this._position = newPosition;
  19900. this._isDirty = true;
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. Object.defineProperty(TransformNode.prototype, "rotation", {
  19906. /**
  19907. * 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)).
  19908. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19909. */
  19910. get: function () {
  19911. return this._rotation;
  19912. },
  19913. set: function (newRotation) {
  19914. this._rotation = newRotation;
  19915. this._isDirty = true;
  19916. },
  19917. enumerable: true,
  19918. configurable: true
  19919. });
  19920. Object.defineProperty(TransformNode.prototype, "scaling", {
  19921. /**
  19922. * 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)).
  19923. */
  19924. get: function () {
  19925. return this._scaling;
  19926. },
  19927. set: function (newScaling) {
  19928. this._scaling = newScaling;
  19929. this._isDirty = true;
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19935. /**
  19936. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19937. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19938. */
  19939. get: function () {
  19940. return this._rotationQuaternion;
  19941. },
  19942. set: function (quaternion) {
  19943. this._rotationQuaternion = quaternion;
  19944. //reset the rotation vector.
  19945. if (quaternion) {
  19946. this.rotation.setAll(0.0);
  19947. }
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Object.defineProperty(TransformNode.prototype, "forward", {
  19953. /**
  19954. * The forward direction of that transform in world space.
  19955. */
  19956. get: function () {
  19957. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19958. },
  19959. enumerable: true,
  19960. configurable: true
  19961. });
  19962. Object.defineProperty(TransformNode.prototype, "up", {
  19963. /**
  19964. * The up direction of that transform in world space.
  19965. */
  19966. get: function () {
  19967. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(TransformNode.prototype, "right", {
  19973. /**
  19974. * The right direction of that transform in world space.
  19975. */
  19976. get: function () {
  19977. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. /**
  19983. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19984. * @param matrix the matrix to copy the pose from
  19985. * @returns this TransformNode.
  19986. */
  19987. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19988. this._poseMatrix.copyFrom(matrix);
  19989. return this;
  19990. };
  19991. /**
  19992. * Returns the mesh Pose matrix.
  19993. * @returns the pose matrix
  19994. */
  19995. TransformNode.prototype.getPoseMatrix = function () {
  19996. return this._poseMatrix;
  19997. };
  19998. /** @hidden */
  19999. TransformNode.prototype._isSynchronized = function () {
  20000. if (this._isDirty) {
  20001. return false;
  20002. }
  20003. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20004. return false;
  20005. }
  20006. if (this._cache.pivotMatrixUpdated) {
  20007. return false;
  20008. }
  20009. if (this.infiniteDistance) {
  20010. return false;
  20011. }
  20012. if (!this._cache.position.equals(this._position)) {
  20013. return false;
  20014. }
  20015. if (this._rotationQuaternion) {
  20016. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  20017. return false;
  20018. }
  20019. }
  20020. if (!this._cache.rotation.equals(this._rotation)) {
  20021. return false;
  20022. }
  20023. if (!this._cache.scaling.equals(this._scaling)) {
  20024. return false;
  20025. }
  20026. return true;
  20027. };
  20028. /** @hidden */
  20029. TransformNode.prototype._initCache = function () {
  20030. _super.prototype._initCache.call(this);
  20031. this._cache.localMatrixUpdated = false;
  20032. this._cache.position = BABYLON.Vector3.Zero();
  20033. this._cache.scaling = BABYLON.Vector3.Zero();
  20034. this._cache.rotation = BABYLON.Vector3.Zero();
  20035. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  20036. this._cache.billboardMode = -1;
  20037. };
  20038. /**
  20039. * Flag the transform node as dirty (Forcing it to update everything)
  20040. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  20041. * @returns this transform node
  20042. */
  20043. TransformNode.prototype.markAsDirty = function (property) {
  20044. if (property === "rotation") {
  20045. this.rotationQuaternion = null;
  20046. }
  20047. this._currentRenderId = Number.MAX_VALUE;
  20048. this._isDirty = true;
  20049. return this;
  20050. };
  20051. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  20052. /**
  20053. * Returns the current mesh absolute position.
  20054. * Returns a Vector3.
  20055. */
  20056. get: function () {
  20057. return this._absolutePosition;
  20058. },
  20059. enumerable: true,
  20060. configurable: true
  20061. });
  20062. /**
  20063. * Sets a new matrix to apply before all other transformation
  20064. * @param matrix defines the transform matrix
  20065. * @returns the current TransformNode
  20066. */
  20067. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  20068. return this.setPivotMatrix(matrix, false);
  20069. };
  20070. /**
  20071. * Sets a new pivot matrix to the current node
  20072. * @param matrix defines the new pivot matrix to use
  20073. * @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
  20074. * @returns the current TransformNode
  20075. */
  20076. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  20077. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  20078. this._pivotMatrix.copyFrom(matrix);
  20079. this._cache.pivotMatrixUpdated = true;
  20080. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  20081. if (this._postMultiplyPivotMatrix) {
  20082. if (!this._pivotMatrixInverse) {
  20083. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  20084. }
  20085. else {
  20086. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  20087. }
  20088. }
  20089. return this;
  20090. };
  20091. /**
  20092. * Returns the mesh pivot matrix.
  20093. * Default : Identity.
  20094. * @returns the matrix
  20095. */
  20096. TransformNode.prototype.getPivotMatrix = function () {
  20097. return this._pivotMatrix;
  20098. };
  20099. /**
  20100. * Prevents the World matrix to be computed any longer.
  20101. * @returns the TransformNode.
  20102. */
  20103. TransformNode.prototype.freezeWorldMatrix = function () {
  20104. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  20105. this.computeWorldMatrix(true);
  20106. this._isWorldMatrixFrozen = true;
  20107. return this;
  20108. };
  20109. /**
  20110. * Allows back the World matrix computation.
  20111. * @returns the TransformNode.
  20112. */
  20113. TransformNode.prototype.unfreezeWorldMatrix = function () {
  20114. this._isWorldMatrixFrozen = false;
  20115. this.computeWorldMatrix(true);
  20116. return this;
  20117. };
  20118. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  20119. /**
  20120. * True if the World matrix has been frozen.
  20121. */
  20122. get: function () {
  20123. return this._isWorldMatrixFrozen;
  20124. },
  20125. enumerable: true,
  20126. configurable: true
  20127. });
  20128. /**
  20129. * Retuns the mesh absolute position in the World.
  20130. * @returns a Vector3.
  20131. */
  20132. TransformNode.prototype.getAbsolutePosition = function () {
  20133. this.computeWorldMatrix();
  20134. return this._absolutePosition;
  20135. };
  20136. /**
  20137. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20138. * @param absolutePosition the absolute position to set
  20139. * @returns the TransformNode.
  20140. */
  20141. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20142. if (!absolutePosition) {
  20143. return this;
  20144. }
  20145. var absolutePositionX;
  20146. var absolutePositionY;
  20147. var absolutePositionZ;
  20148. if (absolutePosition.x === undefined) {
  20149. if (arguments.length < 3) {
  20150. return this;
  20151. }
  20152. absolutePositionX = arguments[0];
  20153. absolutePositionY = arguments[1];
  20154. absolutePositionZ = arguments[2];
  20155. }
  20156. else {
  20157. absolutePositionX = absolutePosition.x;
  20158. absolutePositionY = absolutePosition.y;
  20159. absolutePositionZ = absolutePosition.z;
  20160. }
  20161. if (this.parent) {
  20162. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20163. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  20165. }
  20166. else {
  20167. this.position.x = absolutePositionX;
  20168. this.position.y = absolutePositionY;
  20169. this.position.z = absolutePositionZ;
  20170. }
  20171. return this;
  20172. };
  20173. /**
  20174. * Sets the mesh position in its local space.
  20175. * @param vector3 the position to set in localspace
  20176. * @returns the TransformNode.
  20177. */
  20178. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20179. this.computeWorldMatrix();
  20180. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20181. return this;
  20182. };
  20183. /**
  20184. * Returns the mesh position in the local space from the current World matrix values.
  20185. * @returns a new Vector3.
  20186. */
  20187. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20188. this.computeWorldMatrix();
  20189. var invLocalWorldMatrix = BABYLON.Tmp.Matrix[0];
  20190. this._localWorld.invertToRef(invLocalWorldMatrix);
  20191. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20192. };
  20193. /**
  20194. * Translates the mesh along the passed Vector3 in its local space.
  20195. * @param vector3 the distance to translate in localspace
  20196. * @returns the TransformNode.
  20197. */
  20198. TransformNode.prototype.locallyTranslate = function (vector3) {
  20199. this.computeWorldMatrix(true);
  20200. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20201. return this;
  20202. };
  20203. /**
  20204. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20205. * @param targetPoint the position (must be in same space as current mesh) to look at
  20206. * @param yawCor optional yaw (y-axis) correction in radians
  20207. * @param pitchCor optional pitch (x-axis) correction in radians
  20208. * @param rollCor optional roll (z-axis) correction in radians
  20209. * @param space the choosen space of the target
  20210. * @returns the TransformNode.
  20211. */
  20212. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20213. if (yawCor === void 0) { yawCor = 0; }
  20214. if (pitchCor === void 0) { pitchCor = 0; }
  20215. if (rollCor === void 0) { rollCor = 0; }
  20216. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20217. var dv = TransformNode._lookAtVectorCache;
  20218. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20219. targetPoint.subtractToRef(pos, dv);
  20220. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20221. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20222. var pitch = Math.atan2(dv.y, len);
  20223. if (this.rotationQuaternion) {
  20224. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20225. }
  20226. else {
  20227. this.rotation.x = pitch + pitchCor;
  20228. this.rotation.y = yaw + yawCor;
  20229. this.rotation.z = rollCor;
  20230. }
  20231. return this;
  20232. };
  20233. /**
  20234. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20235. * This Vector3 is expressed in the World space.
  20236. * @param localAxis axis to rotate
  20237. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20238. */
  20239. TransformNode.prototype.getDirection = function (localAxis) {
  20240. var result = BABYLON.Vector3.Zero();
  20241. this.getDirectionToRef(localAxis, result);
  20242. return result;
  20243. };
  20244. /**
  20245. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20246. * localAxis is expressed in the mesh local space.
  20247. * result is computed in the Wordl space from the mesh World matrix.
  20248. * @param localAxis axis to rotate
  20249. * @param result the resulting transformnode
  20250. * @returns this TransformNode.
  20251. */
  20252. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20253. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20254. return this;
  20255. };
  20256. /**
  20257. * Sets a new pivot point to the current node
  20258. * @param point defines the new pivot point to use
  20259. * @param space defines if the point is in world or local space (local by default)
  20260. * @returns the current TransformNode
  20261. */
  20262. TransformNode.prototype.setPivotPoint = function (point, space) {
  20263. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20264. if (this.getScene().getRenderId() == 0) {
  20265. this.computeWorldMatrix(true);
  20266. }
  20267. var wm = this.getWorldMatrix();
  20268. if (space == BABYLON.Space.WORLD) {
  20269. var tmat = BABYLON.Tmp.Matrix[0];
  20270. wm.invertToRef(tmat);
  20271. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20272. }
  20273. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20274. };
  20275. /**
  20276. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20277. * @returns the pivot point
  20278. */
  20279. TransformNode.prototype.getPivotPoint = function () {
  20280. var point = BABYLON.Vector3.Zero();
  20281. this.getPivotPointToRef(point);
  20282. return point;
  20283. };
  20284. /**
  20285. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20286. * @param result the vector3 to store the result
  20287. * @returns this TransformNode.
  20288. */
  20289. TransformNode.prototype.getPivotPointToRef = function (result) {
  20290. result.x = -this._pivotMatrix.m[12];
  20291. result.y = -this._pivotMatrix.m[13];
  20292. result.z = -this._pivotMatrix.m[14];
  20293. return this;
  20294. };
  20295. /**
  20296. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20297. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20298. */
  20299. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20300. var point = BABYLON.Vector3.Zero();
  20301. this.getAbsolutePivotPointToRef(point);
  20302. return point;
  20303. };
  20304. /**
  20305. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20306. * @param result vector3 to store the result
  20307. * @returns this TransformNode.
  20308. */
  20309. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20310. result.x = this._pivotMatrix.m[12];
  20311. result.y = this._pivotMatrix.m[13];
  20312. result.z = this._pivotMatrix.m[14];
  20313. this.getPivotPointToRef(result);
  20314. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20315. return this;
  20316. };
  20317. /**
  20318. * Defines the passed node as the parent of the current node.
  20319. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20320. * @param node the node ot set as the parent
  20321. * @returns this TransformNode.
  20322. */
  20323. TransformNode.prototype.setParent = function (node) {
  20324. if (!node && !this.parent) {
  20325. return this;
  20326. }
  20327. var quatRotation = BABYLON.Tmp.Quaternion[0];
  20328. var position = BABYLON.Tmp.Vector3[0];
  20329. var scale = BABYLON.Tmp.Vector3[1];
  20330. if (!node) {
  20331. if (this.parent && this.parent.computeWorldMatrix) {
  20332. this.parent.computeWorldMatrix(true);
  20333. }
  20334. this.computeWorldMatrix(true);
  20335. this.getWorldMatrix().decompose(scale, quatRotation, position);
  20336. }
  20337. else {
  20338. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20339. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20340. this.computeWorldMatrix(true);
  20341. node.computeWorldMatrix(true);
  20342. node.getWorldMatrix().invertToRef(invParentMatrix);
  20343. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20344. diffMatrix.decompose(scale, quatRotation, position);
  20345. }
  20346. if (this.rotationQuaternion) {
  20347. this.rotationQuaternion.copyFrom(quatRotation);
  20348. }
  20349. else {
  20350. quatRotation.toEulerAnglesToRef(this.rotation);
  20351. }
  20352. this.scaling.copyFrom(scale);
  20353. this.position.copyFrom(position);
  20354. this.parent = node;
  20355. return this;
  20356. };
  20357. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20358. /**
  20359. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20360. */
  20361. get: function () {
  20362. return this._nonUniformScaling;
  20363. },
  20364. enumerable: true,
  20365. configurable: true
  20366. });
  20367. /** @hidden */
  20368. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20369. if (this._nonUniformScaling === value) {
  20370. return false;
  20371. }
  20372. this._nonUniformScaling = value;
  20373. return true;
  20374. };
  20375. /**
  20376. * Attach the current TransformNode to another TransformNode associated with a bone
  20377. * @param bone Bone affecting the TransformNode
  20378. * @param affectedTransformNode TransformNode associated with the bone
  20379. * @returns this object
  20380. */
  20381. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20382. this._transformToBoneReferal = affectedTransformNode;
  20383. this.parent = bone;
  20384. if (bone.getWorldMatrix().determinant() < 0) {
  20385. this.scalingDeterminant *= -1;
  20386. }
  20387. return this;
  20388. };
  20389. /**
  20390. * Detach the transform node if its associated with a bone
  20391. * @returns this object
  20392. */
  20393. TransformNode.prototype.detachFromBone = function () {
  20394. if (!this.parent) {
  20395. return this;
  20396. }
  20397. if (this.parent.getWorldMatrix().determinant() < 0) {
  20398. this.scalingDeterminant *= -1;
  20399. }
  20400. this._transformToBoneReferal = null;
  20401. this.parent = null;
  20402. return this;
  20403. };
  20404. /**
  20405. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20406. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20407. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20408. * The passed axis is also normalized.
  20409. * @param axis the axis to rotate around
  20410. * @param amount the amount to rotate in radians
  20411. * @param space Space to rotate in (Default: local)
  20412. * @returns the TransformNode.
  20413. */
  20414. TransformNode.prototype.rotate = function (axis, amount, space) {
  20415. axis.normalize();
  20416. if (!this.rotationQuaternion) {
  20417. this.rotationQuaternion = this.rotation.toQuaternion();
  20418. this.rotation.setAll(0);
  20419. }
  20420. var rotationQuaternion;
  20421. if (!space || space === BABYLON.Space.LOCAL) {
  20422. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20423. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20424. }
  20425. else {
  20426. if (this.parent) {
  20427. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20428. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20429. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20430. }
  20431. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20432. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20433. }
  20434. return this;
  20435. };
  20436. /**
  20437. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20438. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20439. * The passed axis is also normalized. .
  20440. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20441. * @param point the point to rotate around
  20442. * @param axis the axis to rotate around
  20443. * @param amount the amount to rotate in radians
  20444. * @returns the TransformNode
  20445. */
  20446. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20447. axis.normalize();
  20448. if (!this.rotationQuaternion) {
  20449. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20450. this.rotation.setAll(0);
  20451. }
  20452. var tmpVector = BABYLON.Tmp.Vector3[0];
  20453. var finalScale = BABYLON.Tmp.Vector3[1];
  20454. var finalTranslation = BABYLON.Tmp.Vector3[2];
  20455. var finalRotation = BABYLON.Tmp.Quaternion[0];
  20456. var translationMatrix = BABYLON.Tmp.Matrix[0]; // T
  20457. var translationMatrixInv = BABYLON.Tmp.Matrix[1]; // T'
  20458. var rotationMatrix = BABYLON.Tmp.Matrix[2]; // R
  20459. var finalMatrix = BABYLON.Tmp.Matrix[3]; // T' x R x T
  20460. point.subtractToRef(this.position, tmpVector);
  20461. BABYLON.Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  20462. BABYLON.Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  20463. BABYLON.Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  20464. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  20465. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  20466. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  20467. this.position.addInPlace(finalTranslation);
  20468. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20469. return this;
  20470. };
  20471. /**
  20472. * Translates the mesh along the axis vector for the passed distance in the given space.
  20473. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20474. * @param axis the axis to translate in
  20475. * @param distance the distance to translate
  20476. * @param space Space to rotate in (Default: local)
  20477. * @returns the TransformNode.
  20478. */
  20479. TransformNode.prototype.translate = function (axis, distance, space) {
  20480. var displacementVector = axis.scale(distance);
  20481. if (!space || space === BABYLON.Space.LOCAL) {
  20482. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20483. this.setPositionWithLocalVector(tempV3);
  20484. }
  20485. else {
  20486. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20487. }
  20488. return this;
  20489. };
  20490. /**
  20491. * Adds a rotation step to the mesh current rotation.
  20492. * x, y, z are Euler angles expressed in radians.
  20493. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20494. * This means this rotation is made in the mesh local space only.
  20495. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20496. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20497. * ```javascript
  20498. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20499. * ```
  20500. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20501. * 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.
  20502. * @param x Rotation to add
  20503. * @param y Rotation to add
  20504. * @param z Rotation to add
  20505. * @returns the TransformNode.
  20506. */
  20507. TransformNode.prototype.addRotation = function (x, y, z) {
  20508. var rotationQuaternion;
  20509. if (this.rotationQuaternion) {
  20510. rotationQuaternion = this.rotationQuaternion;
  20511. }
  20512. else {
  20513. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20514. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20515. }
  20516. var accumulation = BABYLON.Tmp.Quaternion[0];
  20517. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20518. rotationQuaternion.multiplyInPlace(accumulation);
  20519. if (!this.rotationQuaternion) {
  20520. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20521. }
  20522. return this;
  20523. };
  20524. /**
  20525. * Computes the world matrix of the node
  20526. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20527. * @returns the world matrix
  20528. */
  20529. TransformNode.prototype.computeWorldMatrix = function (force) {
  20530. if (this._isWorldMatrixFrozen) {
  20531. return this._worldMatrix;
  20532. }
  20533. if (!force && this.isSynchronized()) {
  20534. this._currentRenderId = this.getScene().getRenderId();
  20535. return this._worldMatrix;
  20536. }
  20537. this._updateCache();
  20538. this._cache.position.copyFrom(this.position);
  20539. this._cache.scaling.copyFrom(this.scaling);
  20540. this._cache.pivotMatrixUpdated = false;
  20541. this._cache.billboardMode = this.billboardMode;
  20542. this._currentRenderId = this.getScene().getRenderId();
  20543. this._childRenderId = this.getScene().getRenderId();
  20544. this._isDirty = false;
  20545. // Scaling
  20546. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20547. // Rotation
  20548. //rotate, if quaternion is set and rotation was used
  20549. if (this.rotationQuaternion) {
  20550. var len = this.rotation.length();
  20551. if (len) {
  20552. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20553. this.rotation.copyFromFloats(0, 0, 0);
  20554. }
  20555. }
  20556. if (this.rotationQuaternion) {
  20557. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20558. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20559. }
  20560. else {
  20561. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20562. this._cache.rotation.copyFrom(this.rotation);
  20563. }
  20564. // Translation
  20565. var camera = this.getScene().activeCamera;
  20566. if (this.infiniteDistance && !this.parent && camera) {
  20567. var cameraWorldMatrix = camera.getWorldMatrix();
  20568. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20569. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20570. }
  20571. else {
  20572. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20573. }
  20574. // Composing transformations
  20575. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20576. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20577. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20578. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20579. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20580. // Need to decompose each rotation here
  20581. var currentPosition = BABYLON.Tmp.Vector3[3];
  20582. if (this.parent && this.parent.getWorldMatrix) {
  20583. if (this._transformToBoneReferal) {
  20584. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20585. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20586. }
  20587. else {
  20588. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20589. }
  20590. }
  20591. else {
  20592. currentPosition.copyFrom(this.position);
  20593. }
  20594. currentPosition.subtractInPlace(camera.globalPosition);
  20595. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20596. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20597. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20598. }
  20599. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20600. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20601. }
  20602. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20603. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20604. }
  20605. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20606. }
  20607. else {
  20608. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20609. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20610. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20611. }
  20612. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20613. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20614. }
  20615. // Post multiply inverse of pivotMatrix
  20616. if (this._postMultiplyPivotMatrix) {
  20617. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20618. }
  20619. // Local world
  20620. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20621. // Parent
  20622. if (this.parent && this.parent.getWorldMatrix) {
  20623. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20624. if (this._transformToBoneReferal) {
  20625. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20626. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20627. }
  20628. else {
  20629. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20630. }
  20631. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20632. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20633. this._worldMatrix.copyFrom(this._localWorld);
  20634. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20635. }
  20636. else {
  20637. if (this._transformToBoneReferal) {
  20638. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20639. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20640. }
  20641. else {
  20642. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20643. }
  20644. }
  20645. this._markSyncedWithParent();
  20646. }
  20647. else {
  20648. this._worldMatrix.copyFrom(this._localWorld);
  20649. }
  20650. // Normal matrix
  20651. if (!this.ignoreNonUniformScaling) {
  20652. if (this.scaling.isNonUniform) {
  20653. this._updateNonUniformScalingState(true);
  20654. }
  20655. else if (this.parent && this.parent._nonUniformScaling) {
  20656. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20657. }
  20658. else {
  20659. this._updateNonUniformScalingState(false);
  20660. }
  20661. }
  20662. else {
  20663. this._updateNonUniformScalingState(false);
  20664. }
  20665. this._afterComputeWorldMatrix();
  20666. // Absolute position
  20667. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20668. // Callbacks
  20669. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20670. if (!this._poseMatrix) {
  20671. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20672. }
  20673. // Cache the determinant
  20674. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20675. return this._worldMatrix;
  20676. };
  20677. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20678. };
  20679. /**
  20680. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20681. * @param func callback function to add
  20682. *
  20683. * @returns the TransformNode.
  20684. */
  20685. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20686. this.onAfterWorldMatrixUpdateObservable.add(func);
  20687. return this;
  20688. };
  20689. /**
  20690. * Removes a registered callback function.
  20691. * @param func callback function to remove
  20692. * @returns the TransformNode.
  20693. */
  20694. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20695. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20696. return this;
  20697. };
  20698. /**
  20699. * Clone the current transform node
  20700. * @param name Name of the new clone
  20701. * @param newParent New parent for the clone
  20702. * @param doNotCloneChildren Do not clone children hierarchy
  20703. * @returns the new transform node
  20704. */
  20705. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20706. var _this = this;
  20707. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20708. result.name = name;
  20709. result.id = name;
  20710. if (newParent) {
  20711. result.parent = newParent;
  20712. }
  20713. if (!doNotCloneChildren) {
  20714. // Children
  20715. var directDescendants = this.getDescendants(true);
  20716. for (var index = 0; index < directDescendants.length; index++) {
  20717. var child = directDescendants[index];
  20718. if (child.clone) {
  20719. child.clone(name + "." + child.name, result);
  20720. }
  20721. }
  20722. }
  20723. return result;
  20724. };
  20725. /**
  20726. * Serializes the objects information.
  20727. * @param currentSerializationObject defines the object to serialize in
  20728. * @returns the serialized object
  20729. */
  20730. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20731. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20732. serializationObject.type = this.getClassName();
  20733. // Parent
  20734. if (this.parent) {
  20735. serializationObject.parentId = this.parent.id;
  20736. }
  20737. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20738. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20739. }
  20740. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20741. serializationObject.isEnabled = this.isEnabled();
  20742. // Parent
  20743. if (this.parent) {
  20744. serializationObject.parentId = this.parent.id;
  20745. }
  20746. return serializationObject;
  20747. };
  20748. // Statics
  20749. /**
  20750. * Returns a new TransformNode object parsed from the source provided.
  20751. * @param parsedTransformNode is the source.
  20752. * @param scene the scne the object belongs to
  20753. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20754. * @returns a new TransformNode object parsed from the source provided.
  20755. */
  20756. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20757. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20758. if (BABYLON.Tags) {
  20759. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20760. }
  20761. if (parsedTransformNode.localMatrix) {
  20762. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20763. }
  20764. else if (parsedTransformNode.pivotMatrix) {
  20765. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20766. }
  20767. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20768. // Parent
  20769. if (parsedTransformNode.parentId) {
  20770. transformNode._waitingParentId = parsedTransformNode.parentId;
  20771. }
  20772. return transformNode;
  20773. };
  20774. /**
  20775. * Releases resources associated with this transform node.
  20776. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20777. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20778. */
  20779. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20780. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20781. // Animations
  20782. this.getScene().stopAnimation(this);
  20783. // Remove from scene
  20784. this.getScene().removeTransformNode(this);
  20785. this.onAfterWorldMatrixUpdateObservable.clear();
  20786. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20787. };
  20788. // Statics
  20789. /**
  20790. * Object will not rotate to face the camera
  20791. */
  20792. TransformNode.BILLBOARDMODE_NONE = 0;
  20793. /**
  20794. * Object will rotate to face the camera but only on the x axis
  20795. */
  20796. TransformNode.BILLBOARDMODE_X = 1;
  20797. /**
  20798. * Object will rotate to face the camera but only on the y axis
  20799. */
  20800. TransformNode.BILLBOARDMODE_Y = 2;
  20801. /**
  20802. * Object will rotate to face the camera but only on the z axis
  20803. */
  20804. TransformNode.BILLBOARDMODE_Z = 4;
  20805. /**
  20806. * Object will rotate to face the camera
  20807. */
  20808. TransformNode.BILLBOARDMODE_ALL = 7;
  20809. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20810. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20811. __decorate([
  20812. BABYLON.serializeAsVector3("position")
  20813. ], TransformNode.prototype, "_position", void 0);
  20814. __decorate([
  20815. BABYLON.serializeAsVector3("rotation")
  20816. ], TransformNode.prototype, "_rotation", void 0);
  20817. __decorate([
  20818. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20819. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20820. __decorate([
  20821. BABYLON.serializeAsVector3("scaling")
  20822. ], TransformNode.prototype, "_scaling", void 0);
  20823. __decorate([
  20824. BABYLON.serialize()
  20825. ], TransformNode.prototype, "billboardMode", void 0);
  20826. __decorate([
  20827. BABYLON.serialize()
  20828. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20829. __decorate([
  20830. BABYLON.serialize()
  20831. ], TransformNode.prototype, "infiniteDistance", void 0);
  20832. __decorate([
  20833. BABYLON.serialize()
  20834. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20835. return TransformNode;
  20836. }(BABYLON.Node));
  20837. BABYLON.TransformNode = TransformNode;
  20838. })(BABYLON || (BABYLON = {}));
  20839. //# sourceMappingURL=babylon.transformNode.js.map
  20840. var BABYLON;
  20841. (function (BABYLON) {
  20842. /** @hidden */
  20843. var _FacetDataStorage = /** @class */ (function () {
  20844. function _FacetDataStorage() {
  20845. this.facetNb = 0; // facet number
  20846. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20847. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20848. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20849. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20850. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20851. this.subDiv = {
  20852. max: 1,
  20853. X: 1,
  20854. Y: 1,
  20855. Z: 1
  20856. };
  20857. this.facetDepthSort = false; // is the facet depth sort to be computed
  20858. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20859. }
  20860. return _FacetDataStorage;
  20861. }());
  20862. /**
  20863. * Class used to store all common mesh properties
  20864. */
  20865. var AbstractMesh = /** @class */ (function (_super) {
  20866. __extends(AbstractMesh, _super);
  20867. // Constructor
  20868. /**
  20869. * Creates a new AbstractMesh
  20870. * @param name defines the name of the mesh
  20871. * @param scene defines the hosting scene
  20872. */
  20873. function AbstractMesh(name, scene) {
  20874. if (scene === void 0) { scene = null; }
  20875. var _this = _super.call(this, name, scene, false) || this;
  20876. _this._facetData = new _FacetDataStorage();
  20877. /** Gets ot sets the culling strategy to use to find visible meshes */
  20878. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20879. // Events
  20880. /**
  20881. * An event triggered when this mesh collides with another one
  20882. */
  20883. _this.onCollideObservable = new BABYLON.Observable();
  20884. /**
  20885. * An event triggered when the collision's position changes
  20886. */
  20887. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20888. /**
  20889. * An event triggered when material is changed
  20890. */
  20891. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20892. // Properties
  20893. /**
  20894. * Gets or sets the orientation for POV movement & rotation
  20895. */
  20896. _this.definedFacingForward = true;
  20897. _this._visibility = 1.0;
  20898. /** Gets or sets the alpha index used to sort transparent meshes
  20899. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20900. */
  20901. _this.alphaIndex = Number.MAX_VALUE;
  20902. /**
  20903. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20904. */
  20905. _this.isVisible = true;
  20906. /**
  20907. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20908. */
  20909. _this.isPickable = true;
  20910. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20911. _this.showSubMeshesBoundingBox = false;
  20912. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20913. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20914. */
  20915. _this.isBlocker = false;
  20916. /**
  20917. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20918. */
  20919. _this.enablePointerMoveEvents = false;
  20920. /**
  20921. * Specifies the rendering group id for this mesh (0 by default)
  20922. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20923. */
  20924. _this.renderingGroupId = 0;
  20925. _this._receiveShadows = false;
  20926. /** Defines color to use when rendering outline */
  20927. _this.outlineColor = BABYLON.Color3.Red();
  20928. /** Define width to use when rendering outline */
  20929. _this.outlineWidth = 0.02;
  20930. /** Defines color to use when rendering overlay */
  20931. _this.overlayColor = BABYLON.Color3.Red();
  20932. /** Defines alpha to use when rendering overlay */
  20933. _this.overlayAlpha = 0.5;
  20934. _this._hasVertexAlpha = false;
  20935. _this._useVertexColors = true;
  20936. _this._computeBonesUsingShaders = true;
  20937. _this._numBoneInfluencers = 4;
  20938. _this._applyFog = true;
  20939. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20940. _this.useOctreeForRenderingSelection = true;
  20941. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20942. _this.useOctreeForPicking = true;
  20943. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20944. _this.useOctreeForCollisions = true;
  20945. _this._layerMask = 0x0FFFFFFF;
  20946. /**
  20947. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20948. */
  20949. _this.alwaysSelectAsActiveMesh = false;
  20950. /**
  20951. * Gets or sets the current action manager
  20952. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20953. */
  20954. _this.actionManager = null;
  20955. // Collisions
  20956. _this._checkCollisions = false;
  20957. _this._collisionMask = -1;
  20958. _this._collisionGroup = -1;
  20959. /**
  20960. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20961. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20962. */
  20963. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20964. /**
  20965. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20966. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20967. */
  20968. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20969. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20970. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20971. // Edges
  20972. /**
  20973. * Defines edge width used when edgesRenderer is enabled
  20974. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20975. */
  20976. _this.edgesWidth = 1;
  20977. /**
  20978. * Defines edge color used when edgesRenderer is enabled
  20979. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20980. */
  20981. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20982. /** @hidden */
  20983. _this._renderId = 0;
  20984. /** @hidden */
  20985. _this._intersectionsInProgress = new Array();
  20986. /** @hidden */
  20987. _this._unIndexed = false;
  20988. /** @hidden */
  20989. _this._lightSources = new Array();
  20990. /**
  20991. * An event triggered when the mesh is rebuilt.
  20992. */
  20993. _this.onRebuildObservable = new BABYLON.Observable();
  20994. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20995. if (collidedMesh === void 0) { collidedMesh = null; }
  20996. //TODO move this to the collision coordinator!
  20997. if (_this.getScene().workerCollisions) {
  20998. newPosition.multiplyInPlace(_this._collider._radius);
  20999. }
  21000. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  21001. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  21002. _this.position.addInPlace(_this._diffPositionForCollisions);
  21003. }
  21004. if (collidedMesh) {
  21005. _this.onCollideObservable.notifyObservers(collidedMesh);
  21006. }
  21007. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  21008. };
  21009. _this.getScene().addMesh(_this);
  21010. _this._resyncLightSources();
  21011. return _this;
  21012. }
  21013. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  21014. /**
  21015. * No billboard
  21016. */
  21017. get: function () {
  21018. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  21024. /** Billboard on X axis */
  21025. get: function () {
  21026. return BABYLON.TransformNode.BILLBOARDMODE_X;
  21027. },
  21028. enumerable: true,
  21029. configurable: true
  21030. });
  21031. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  21032. /** Billboard on Y axis */
  21033. get: function () {
  21034. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  21035. },
  21036. enumerable: true,
  21037. configurable: true
  21038. });
  21039. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  21040. /** Billboard on Z axis */
  21041. get: function () {
  21042. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  21043. },
  21044. enumerable: true,
  21045. configurable: true
  21046. });
  21047. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  21048. /** Billboard on all axes */
  21049. get: function () {
  21050. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  21051. },
  21052. enumerable: true,
  21053. configurable: true
  21054. });
  21055. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  21056. /**
  21057. * Gets the number of facets in the mesh
  21058. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21059. */
  21060. get: function () {
  21061. return this._facetData.facetNb;
  21062. },
  21063. enumerable: true,
  21064. configurable: true
  21065. });
  21066. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  21067. /**
  21068. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  21069. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21070. */
  21071. get: function () {
  21072. return this._facetData.partitioningSubdivisions;
  21073. },
  21074. set: function (nb) {
  21075. this._facetData.partitioningSubdivisions = nb;
  21076. },
  21077. enumerable: true,
  21078. configurable: true
  21079. });
  21080. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  21081. /**
  21082. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  21083. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  21084. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21085. */
  21086. get: function () {
  21087. return this._facetData.partitioningBBoxRatio;
  21088. },
  21089. set: function (ratio) {
  21090. this._facetData.partitioningBBoxRatio = ratio;
  21091. },
  21092. enumerable: true,
  21093. configurable: true
  21094. });
  21095. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  21096. /**
  21097. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  21098. * Works only for updatable meshes.
  21099. * Doesn't work with multi-materials
  21100. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21101. */
  21102. get: function () {
  21103. return this._facetData.facetDepthSort;
  21104. },
  21105. set: function (sort) {
  21106. this._facetData.facetDepthSort = sort;
  21107. },
  21108. enumerable: true,
  21109. configurable: true
  21110. });
  21111. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  21112. /**
  21113. * The location (Vector3) where the facet depth sort must be computed from.
  21114. * By default, the active camera position.
  21115. * Used only when facet depth sort is enabled
  21116. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21117. */
  21118. get: function () {
  21119. return this._facetData.facetDepthSortFrom;
  21120. },
  21121. set: function (location) {
  21122. this._facetData.facetDepthSortFrom = location;
  21123. },
  21124. enumerable: true,
  21125. configurable: true
  21126. });
  21127. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21128. /**
  21129. * gets a boolean indicating if facetData is enabled
  21130. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21131. */
  21132. get: function () {
  21133. return this._facetData.facetDataEnabled;
  21134. },
  21135. enumerable: true,
  21136. configurable: true
  21137. });
  21138. /** @hidden */
  21139. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21140. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21141. return false;
  21142. }
  21143. this._markSubMeshesAsMiscDirty();
  21144. return true;
  21145. };
  21146. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21147. /** Set a function to call when this mesh collides with another one */
  21148. set: function (callback) {
  21149. if (this._onCollideObserver) {
  21150. this.onCollideObservable.remove(this._onCollideObserver);
  21151. }
  21152. this._onCollideObserver = this.onCollideObservable.add(callback);
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21158. /** Set a function to call when the collision's position changes */
  21159. set: function (callback) {
  21160. if (this._onCollisionPositionChangeObserver) {
  21161. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21162. }
  21163. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21164. },
  21165. enumerable: true,
  21166. configurable: true
  21167. });
  21168. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21169. /**
  21170. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21171. */
  21172. get: function () {
  21173. return this._visibility;
  21174. },
  21175. /**
  21176. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21177. */
  21178. set: function (value) {
  21179. if (this._visibility === value) {
  21180. return;
  21181. }
  21182. this._visibility = value;
  21183. this._markSubMeshesAsMiscDirty();
  21184. },
  21185. enumerable: true,
  21186. configurable: true
  21187. });
  21188. Object.defineProperty(AbstractMesh.prototype, "material", {
  21189. /** Gets or sets current material */
  21190. get: function () {
  21191. return this._material;
  21192. },
  21193. set: function (value) {
  21194. if (this._material === value) {
  21195. return;
  21196. }
  21197. // remove from material mesh map id needed
  21198. if (this._material && this._material.meshMap) {
  21199. this._material.meshMap[this.uniqueId] = undefined;
  21200. }
  21201. this._material = value;
  21202. if (value && value.meshMap) {
  21203. value.meshMap[this.uniqueId] = this;
  21204. }
  21205. if (this.onMaterialChangedObservable.hasObservers) {
  21206. this.onMaterialChangedObservable.notifyObservers(this);
  21207. }
  21208. if (!this.subMeshes) {
  21209. return;
  21210. }
  21211. this._unBindEffect();
  21212. },
  21213. enumerable: true,
  21214. configurable: true
  21215. });
  21216. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21217. /**
  21218. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21219. * @see http://doc.babylonjs.com/babylon101/shadows
  21220. */
  21221. get: function () {
  21222. return this._receiveShadows;
  21223. },
  21224. set: function (value) {
  21225. if (this._receiveShadows === value) {
  21226. return;
  21227. }
  21228. this._receiveShadows = value;
  21229. this._markSubMeshesAsLightDirty();
  21230. },
  21231. enumerable: true,
  21232. configurable: true
  21233. });
  21234. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21235. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21236. get: function () {
  21237. return this._hasVertexAlpha;
  21238. },
  21239. set: function (value) {
  21240. if (this._hasVertexAlpha === value) {
  21241. return;
  21242. }
  21243. this._hasVertexAlpha = value;
  21244. this._markSubMeshesAsAttributesDirty();
  21245. this._markSubMeshesAsMiscDirty();
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21251. /** 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) */
  21252. get: function () {
  21253. return this._useVertexColors;
  21254. },
  21255. set: function (value) {
  21256. if (this._useVertexColors === value) {
  21257. return;
  21258. }
  21259. this._useVertexColors = value;
  21260. this._markSubMeshesAsAttributesDirty();
  21261. },
  21262. enumerable: true,
  21263. configurable: true
  21264. });
  21265. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21266. /**
  21267. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21268. */
  21269. get: function () {
  21270. return this._computeBonesUsingShaders;
  21271. },
  21272. set: function (value) {
  21273. if (this._computeBonesUsingShaders === value) {
  21274. return;
  21275. }
  21276. this._computeBonesUsingShaders = value;
  21277. this._markSubMeshesAsAttributesDirty();
  21278. },
  21279. enumerable: true,
  21280. configurable: true
  21281. });
  21282. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21283. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21284. get: function () {
  21285. return this._numBoneInfluencers;
  21286. },
  21287. set: function (value) {
  21288. if (this._numBoneInfluencers === value) {
  21289. return;
  21290. }
  21291. this._numBoneInfluencers = value;
  21292. this._markSubMeshesAsAttributesDirty();
  21293. },
  21294. enumerable: true,
  21295. configurable: true
  21296. });
  21297. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21298. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21299. get: function () {
  21300. return this._applyFog;
  21301. },
  21302. set: function (value) {
  21303. if (this._applyFog === value) {
  21304. return;
  21305. }
  21306. this._applyFog = value;
  21307. this._markSubMeshesAsMiscDirty();
  21308. },
  21309. enumerable: true,
  21310. configurable: true
  21311. });
  21312. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21313. /**
  21314. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21315. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21316. */
  21317. get: function () {
  21318. return this._layerMask;
  21319. },
  21320. set: function (value) {
  21321. if (value === this._layerMask) {
  21322. return;
  21323. }
  21324. this._layerMask = value;
  21325. this._resyncLightSources();
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21331. /**
  21332. * Gets or sets a collision mask used to mask collisions (default is -1).
  21333. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21334. */
  21335. get: function () {
  21336. return this._collisionMask;
  21337. },
  21338. set: function (mask) {
  21339. this._collisionMask = !isNaN(mask) ? mask : -1;
  21340. },
  21341. enumerable: true,
  21342. configurable: true
  21343. });
  21344. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21345. /**
  21346. * Gets or sets the current collision group mask (-1 by default).
  21347. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21348. */
  21349. get: function () {
  21350. return this._collisionGroup;
  21351. },
  21352. set: function (mask) {
  21353. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21354. },
  21355. enumerable: true,
  21356. configurable: true
  21357. });
  21358. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21359. /** @hidden */
  21360. get: function () {
  21361. return null;
  21362. },
  21363. enumerable: true,
  21364. configurable: true
  21365. });
  21366. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21367. get: function () {
  21368. return this._skeleton;
  21369. },
  21370. /**
  21371. * Gets or sets a skeleton to apply skining transformations
  21372. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21373. */
  21374. set: function (value) {
  21375. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21376. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21377. }
  21378. if (value && value.needInitialSkinMatrix) {
  21379. value._registerMeshWithPoseMatrix(this);
  21380. }
  21381. this._skeleton = value;
  21382. if (!this._skeleton) {
  21383. this._bonesTransformMatrices = null;
  21384. }
  21385. this._markSubMeshesAsAttributesDirty();
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. /**
  21391. * Returns the string "AbstractMesh"
  21392. * @returns "AbstractMesh"
  21393. */
  21394. AbstractMesh.prototype.getClassName = function () {
  21395. return "AbstractMesh";
  21396. };
  21397. /**
  21398. * Gets a string representation of the current mesh
  21399. * @param fullDetails defines a boolean indicating if full details must be included
  21400. * @returns a string representation of the current mesh
  21401. */
  21402. AbstractMesh.prototype.toString = function (fullDetails) {
  21403. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21404. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21405. if (this._skeleton) {
  21406. ret += ", skeleton: " + this._skeleton.name;
  21407. }
  21408. if (fullDetails) {
  21409. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21410. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21411. }
  21412. return ret;
  21413. };
  21414. /** @hidden */
  21415. AbstractMesh.prototype._rebuild = function () {
  21416. this.onRebuildObservable.notifyObservers(this);
  21417. if (this._occlusionQuery) {
  21418. this._occlusionQuery = null;
  21419. }
  21420. if (!this.subMeshes) {
  21421. return;
  21422. }
  21423. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21424. var subMesh = _a[_i];
  21425. subMesh._rebuild();
  21426. }
  21427. };
  21428. /** @hidden */
  21429. AbstractMesh.prototype._resyncLightSources = function () {
  21430. this._lightSources.length = 0;
  21431. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21432. var light = _a[_i];
  21433. if (!light.isEnabled()) {
  21434. continue;
  21435. }
  21436. if (light.canAffectMesh(this)) {
  21437. this._lightSources.push(light);
  21438. }
  21439. }
  21440. this._markSubMeshesAsLightDirty();
  21441. };
  21442. /** @hidden */
  21443. AbstractMesh.prototype._resyncLighSource = function (light) {
  21444. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21445. var index = this._lightSources.indexOf(light);
  21446. if (index === -1) {
  21447. if (!isIn) {
  21448. return;
  21449. }
  21450. this._lightSources.push(light);
  21451. }
  21452. else {
  21453. if (isIn) {
  21454. return;
  21455. }
  21456. this._lightSources.splice(index, 1);
  21457. }
  21458. this._markSubMeshesAsLightDirty();
  21459. };
  21460. /** @hidden */
  21461. AbstractMesh.prototype._unBindEffect = function () {
  21462. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21463. var subMesh = _a[_i];
  21464. subMesh.setEffect(null);
  21465. }
  21466. };
  21467. /** @hidden */
  21468. AbstractMesh.prototype._removeLightSource = function (light) {
  21469. var index = this._lightSources.indexOf(light);
  21470. if (index === -1) {
  21471. return;
  21472. }
  21473. this._lightSources.splice(index, 1);
  21474. this._markSubMeshesAsLightDirty();
  21475. };
  21476. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21477. if (!this.subMeshes) {
  21478. return;
  21479. }
  21480. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21481. var subMesh = _a[_i];
  21482. if (subMesh._materialDefines) {
  21483. func(subMesh._materialDefines);
  21484. }
  21485. }
  21486. };
  21487. /** @hidden */
  21488. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21489. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21490. };
  21491. /** @hidden */
  21492. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21493. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21494. };
  21495. /** @hidden */
  21496. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21497. if (!this.subMeshes) {
  21498. return;
  21499. }
  21500. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21501. var subMesh = _a[_i];
  21502. var material = subMesh.getMaterial();
  21503. if (material) {
  21504. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21505. }
  21506. }
  21507. };
  21508. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21509. /**
  21510. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21511. */
  21512. get: function () {
  21513. return this._scaling;
  21514. },
  21515. set: function (newScaling) {
  21516. this._scaling = newScaling;
  21517. if (this.physicsImpostor) {
  21518. this.physicsImpostor.forceUpdate();
  21519. }
  21520. },
  21521. enumerable: true,
  21522. configurable: true
  21523. });
  21524. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21525. // Methods
  21526. /**
  21527. * Returns true if the mesh is blocked. Implemented by child classes
  21528. */
  21529. get: function () {
  21530. return false;
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. /**
  21536. * Returns the mesh itself by default. Implemented by child classes
  21537. * @param camera defines the camera to use to pick the right LOD level
  21538. * @returns the currentAbstractMesh
  21539. */
  21540. AbstractMesh.prototype.getLOD = function (camera) {
  21541. return this;
  21542. };
  21543. /**
  21544. * Returns 0 by default. Implemented by child classes
  21545. * @returns an integer
  21546. */
  21547. AbstractMesh.prototype.getTotalVertices = function () {
  21548. return 0;
  21549. };
  21550. /**
  21551. * Returns null by default. Implemented by child classes
  21552. * @returns null
  21553. */
  21554. AbstractMesh.prototype.getIndices = function () {
  21555. return null;
  21556. };
  21557. /**
  21558. * Returns the array of the requested vertex data kind. Implemented by child classes
  21559. * @param kind defines the vertex data kind to use
  21560. * @returns null
  21561. */
  21562. AbstractMesh.prototype.getVerticesData = function (kind) {
  21563. return null;
  21564. };
  21565. /**
  21566. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21567. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21568. * Note that a new underlying VertexBuffer object is created each call.
  21569. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21570. * @param kind defines vertex data kind:
  21571. * * BABYLON.VertexBuffer.PositionKind
  21572. * * BABYLON.VertexBuffer.UVKind
  21573. * * BABYLON.VertexBuffer.UV2Kind
  21574. * * BABYLON.VertexBuffer.UV3Kind
  21575. * * BABYLON.VertexBuffer.UV4Kind
  21576. * * BABYLON.VertexBuffer.UV5Kind
  21577. * * BABYLON.VertexBuffer.UV6Kind
  21578. * * BABYLON.VertexBuffer.ColorKind
  21579. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21580. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21581. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21582. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21583. * @param data defines the data source
  21584. * @param updatable defines if the data must be flagged as updatable (or static)
  21585. * @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
  21586. * @returns the current mesh
  21587. */
  21588. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21589. return this;
  21590. };
  21591. /**
  21592. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21593. * If the mesh has no geometry, it is simply returned as it is.
  21594. * @param kind defines vertex data kind:
  21595. * * BABYLON.VertexBuffer.PositionKind
  21596. * * BABYLON.VertexBuffer.UVKind
  21597. * * BABYLON.VertexBuffer.UV2Kind
  21598. * * BABYLON.VertexBuffer.UV3Kind
  21599. * * BABYLON.VertexBuffer.UV4Kind
  21600. * * BABYLON.VertexBuffer.UV5Kind
  21601. * * BABYLON.VertexBuffer.UV6Kind
  21602. * * BABYLON.VertexBuffer.ColorKind
  21603. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21604. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21605. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21606. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21607. * @param data defines the data source
  21608. * @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
  21609. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21610. * @returns the current mesh
  21611. */
  21612. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21613. return this;
  21614. };
  21615. /**
  21616. * Sets the mesh indices,
  21617. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21618. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21619. * @param totalVertices Defines the total number of vertices
  21620. * @returns the current mesh
  21621. */
  21622. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21623. return this;
  21624. };
  21625. /**
  21626. * Gets a boolean indicating if specific vertex data is present
  21627. * @param kind defines the vertex data kind to use
  21628. * @returns true is data kind is present
  21629. */
  21630. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21631. return false;
  21632. };
  21633. /**
  21634. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21635. * @returns a BoundingInfo
  21636. */
  21637. AbstractMesh.prototype.getBoundingInfo = function () {
  21638. if (this._masterMesh) {
  21639. return this._masterMesh.getBoundingInfo();
  21640. }
  21641. if (!this._boundingInfo) {
  21642. // this._boundingInfo is being created here
  21643. this._updateBoundingInfo();
  21644. }
  21645. // cannot be null.
  21646. return this._boundingInfo;
  21647. };
  21648. /**
  21649. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21650. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21651. * @returns the current mesh
  21652. */
  21653. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21654. if (includeDescendants === void 0) { includeDescendants = true; }
  21655. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21656. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21657. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21658. if (maxDimension === 0) {
  21659. return this;
  21660. }
  21661. var scale = 1 / maxDimension;
  21662. this.scaling.scaleInPlace(scale);
  21663. return this;
  21664. };
  21665. /**
  21666. * Overwrite the current bounding info
  21667. * @param boundingInfo defines the new bounding info
  21668. * @returns the current mesh
  21669. */
  21670. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21671. this._boundingInfo = boundingInfo;
  21672. return this;
  21673. };
  21674. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21675. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21676. get: function () {
  21677. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21678. },
  21679. enumerable: true,
  21680. configurable: true
  21681. });
  21682. /** @hidden */
  21683. AbstractMesh.prototype._preActivate = function () {
  21684. };
  21685. /** @hidden */
  21686. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21687. };
  21688. /** @hidden */
  21689. AbstractMesh.prototype._activate = function (renderId) {
  21690. this._renderId = renderId;
  21691. };
  21692. /**
  21693. * Gets the current world matrix
  21694. * @returns a Matrix
  21695. */
  21696. AbstractMesh.prototype.getWorldMatrix = function () {
  21697. if (this._masterMesh) {
  21698. return this._masterMesh.getWorldMatrix();
  21699. }
  21700. return _super.prototype.getWorldMatrix.call(this);
  21701. };
  21702. /** @hidden */
  21703. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21704. if (this._masterMesh) {
  21705. return this._masterMesh._getWorldMatrixDeterminant();
  21706. }
  21707. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21708. };
  21709. // ================================== Point of View Movement =================================
  21710. /**
  21711. * Perform relative position change from the point of view of behind the front of the mesh.
  21712. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21713. * Supports definition of mesh facing forward or backward
  21714. * @param amountRight defines the distance on the right axis
  21715. * @param amountUp defines the distance on the up axis
  21716. * @param amountForward defines the distance on the forward axis
  21717. * @returns the current mesh
  21718. */
  21719. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21720. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21721. return this;
  21722. };
  21723. /**
  21724. * Calculate relative position change from the point of view of behind the front of the mesh.
  21725. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21726. * Supports definition of mesh facing forward or backward
  21727. * @param amountRight defines the distance on the right axis
  21728. * @param amountUp defines the distance on the up axis
  21729. * @param amountForward defines the distance on the forward axis
  21730. * @returns the new displacement vector
  21731. */
  21732. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21733. var rotMatrix = new BABYLON.Matrix();
  21734. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21735. rotQuaternion.toRotationMatrix(rotMatrix);
  21736. var translationDelta = BABYLON.Vector3.Zero();
  21737. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21738. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21739. return translationDelta;
  21740. };
  21741. // ================================== Point of View Rotation =================================
  21742. /**
  21743. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21744. * Supports definition of mesh facing forward or backward
  21745. * @param flipBack defines the flip
  21746. * @param twirlClockwise defines the twirl
  21747. * @param tiltRight defines the tilt
  21748. * @returns the current mesh
  21749. */
  21750. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21751. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21752. return this;
  21753. };
  21754. /**
  21755. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21756. * Supports definition of mesh facing forward or backward.
  21757. * @param flipBack defines the flip
  21758. * @param twirlClockwise defines the twirl
  21759. * @param tiltRight defines the tilt
  21760. * @returns the new rotation vector
  21761. */
  21762. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21763. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21764. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21765. };
  21766. /**
  21767. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21768. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21769. * @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
  21770. * @returns the new bounding vectors
  21771. */
  21772. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21773. if (includeDescendants === void 0) { includeDescendants = true; }
  21774. if (predicate === void 0) { predicate = null; }
  21775. // Ensures that all world matrix will be recomputed.
  21776. this.getScene().incrementRenderId();
  21777. this.computeWorldMatrix(true);
  21778. var min;
  21779. var max;
  21780. var boundingInfo = this.getBoundingInfo();
  21781. if (!this.subMeshes) {
  21782. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21783. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21784. }
  21785. else {
  21786. min = boundingInfo.boundingBox.minimumWorld;
  21787. max = boundingInfo.boundingBox.maximumWorld;
  21788. }
  21789. if (includeDescendants) {
  21790. var descendants = this.getDescendants(false);
  21791. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21792. var descendant = descendants_1[_i];
  21793. var childMesh = descendant;
  21794. childMesh.computeWorldMatrix(true);
  21795. // Filters meshes based on custom predicate function.
  21796. if (predicate && !predicate(childMesh)) {
  21797. continue;
  21798. }
  21799. //make sure we have the needed params to get mix and max
  21800. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21801. continue;
  21802. }
  21803. var childBoundingInfo = childMesh.getBoundingInfo();
  21804. var boundingBox = childBoundingInfo.boundingBox;
  21805. var minBox = boundingBox.minimumWorld;
  21806. var maxBox = boundingBox.maximumWorld;
  21807. BABYLON.Tools.CheckExtends(minBox, min, max);
  21808. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21809. }
  21810. }
  21811. return {
  21812. min: min,
  21813. max: max
  21814. };
  21815. };
  21816. /** @hidden */
  21817. AbstractMesh.prototype._updateBoundingInfo = function () {
  21818. if (this._boundingInfo) {
  21819. this._boundingInfo.update(this.worldMatrixFromCache);
  21820. }
  21821. else {
  21822. this._boundingInfo = new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
  21823. }
  21824. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21825. return this;
  21826. };
  21827. /** @hidden */
  21828. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21829. if (!this.subMeshes) {
  21830. return this;
  21831. }
  21832. var count = this.subMeshes.length;
  21833. for (var subIndex = 0; subIndex < count; subIndex++) {
  21834. var subMesh = this.subMeshes[subIndex];
  21835. if (count > 1 || !subMesh.IsGlobal) {
  21836. subMesh.updateBoundingInfo(matrix);
  21837. }
  21838. }
  21839. return this;
  21840. };
  21841. /** @hidden */
  21842. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21843. // Bounding info
  21844. this._updateBoundingInfo();
  21845. };
  21846. /**
  21847. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21848. * A mesh is in the frustum if its bounding box intersects the frustum
  21849. * @param frustumPlanes defines the frustum to test
  21850. * @returns true if the mesh is in the frustum planes
  21851. */
  21852. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21853. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21854. };
  21855. /**
  21856. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21857. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21858. * @param frustumPlanes defines the frustum to test
  21859. * @returns true if the mesh is completely in the frustum planes
  21860. */
  21861. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21862. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21863. };
  21864. /**
  21865. * True if the mesh intersects another mesh or a SolidParticle object
  21866. * @param mesh defines a target mesh or SolidParticle to test
  21867. * @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)
  21868. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21869. * @returns true if there is an intersection
  21870. */
  21871. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21872. if (precise === void 0) { precise = false; }
  21873. if (!this._boundingInfo || !mesh._boundingInfo) {
  21874. return false;
  21875. }
  21876. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21877. return true;
  21878. }
  21879. if (includeDescendants) {
  21880. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21881. var child = _a[_i];
  21882. if (child.intersectsMesh(mesh, precise, true)) {
  21883. return true;
  21884. }
  21885. }
  21886. }
  21887. return false;
  21888. };
  21889. /**
  21890. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21891. * @param point defines the point to test
  21892. * @returns true if there is an intersection
  21893. */
  21894. AbstractMesh.prototype.intersectsPoint = function (point) {
  21895. if (!this._boundingInfo) {
  21896. return false;
  21897. }
  21898. return this._boundingInfo.intersectsPoint(point);
  21899. };
  21900. /**
  21901. * Gets the position of the current mesh in camera space
  21902. * @param camera defines the camera to use
  21903. * @returns a position
  21904. */
  21905. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21906. if (camera === void 0) { camera = null; }
  21907. if (!camera) {
  21908. camera = this.getScene().activeCamera;
  21909. }
  21910. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21911. };
  21912. /**
  21913. * Returns the distance from the mesh to the active camera
  21914. * @param camera defines the camera to use
  21915. * @returns the distance
  21916. */
  21917. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21918. if (camera === void 0) { camera = null; }
  21919. if (!camera) {
  21920. camera = this.getScene().activeCamera;
  21921. }
  21922. return this.absolutePosition.subtract(camera.position).length();
  21923. };
  21924. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21925. // Collisions
  21926. /**
  21927. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21928. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21929. */
  21930. get: function () {
  21931. return this._checkCollisions;
  21932. },
  21933. set: function (collisionEnabled) {
  21934. this._checkCollisions = collisionEnabled;
  21935. if (this.getScene().workerCollisions) {
  21936. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21937. }
  21938. },
  21939. enumerable: true,
  21940. configurable: true
  21941. });
  21942. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21943. /**
  21944. * Gets Collider object used to compute collisions (not physics)
  21945. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21946. */
  21947. get: function () {
  21948. return this._collider;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. /**
  21954. * Move the mesh using collision engine
  21955. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21956. * @param displacement defines the requested displacement vector
  21957. * @returns the current mesh
  21958. */
  21959. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21960. var globalPosition = this.getAbsolutePosition();
  21961. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21962. if (!this._collider) {
  21963. this._collider = new BABYLON.Collider();
  21964. }
  21965. this._collider._radius = this.ellipsoid;
  21966. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21967. return this;
  21968. };
  21969. // Collisions
  21970. /** @hidden */
  21971. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21972. this._generatePointsArray();
  21973. if (!this._positions) {
  21974. return this;
  21975. }
  21976. // Transformation
  21977. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21978. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21979. subMesh._lastColliderWorldVertices = [];
  21980. subMesh._trianglePlanes = [];
  21981. var start = subMesh.verticesStart;
  21982. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21983. for (var i = start; i < end; i++) {
  21984. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21985. }
  21986. }
  21987. // Collide
  21988. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21989. if (collider.collisionFound) {
  21990. collider.collidedMesh = this;
  21991. }
  21992. return this;
  21993. };
  21994. /** @hidden */
  21995. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21996. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21997. var len = subMeshes.length;
  21998. for (var index = 0; index < len; index++) {
  21999. var subMesh = subMeshes.data[index];
  22000. // Bounding test
  22001. if (len > 1 && !subMesh._checkCollision(collider)) {
  22002. continue;
  22003. }
  22004. this._collideForSubMesh(subMesh, transformMatrix, collider);
  22005. }
  22006. return this;
  22007. };
  22008. /** @hidden */
  22009. AbstractMesh.prototype._checkCollision = function (collider) {
  22010. // Bounding box test
  22011. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  22012. return this;
  22013. }
  22014. // Transformation matrix
  22015. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  22016. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  22017. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  22018. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  22019. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  22020. return this;
  22021. };
  22022. // Picking
  22023. /** @hidden */
  22024. AbstractMesh.prototype._generatePointsArray = function () {
  22025. return false;
  22026. };
  22027. /**
  22028. * Checks if the passed Ray intersects with the mesh
  22029. * @param ray defines the ray to use
  22030. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  22031. * @returns the picking info
  22032. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  22033. */
  22034. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  22035. var pickingInfo = new BABYLON.PickingInfo();
  22036. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  22037. return pickingInfo;
  22038. }
  22039. if (!this._generatePointsArray()) {
  22040. return pickingInfo;
  22041. }
  22042. var intersectInfo = null;
  22043. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  22044. var len = subMeshes.length;
  22045. for (var index = 0; index < len; index++) {
  22046. var subMesh = subMeshes.data[index];
  22047. // Bounding test
  22048. if (len > 1 && !subMesh.canIntersects(ray)) {
  22049. continue;
  22050. }
  22051. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  22052. if (currentIntersectInfo) {
  22053. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22054. intersectInfo = currentIntersectInfo;
  22055. intersectInfo.subMeshId = index;
  22056. if (fastCheck) {
  22057. break;
  22058. }
  22059. }
  22060. }
  22061. }
  22062. if (intersectInfo) {
  22063. // Get picked point
  22064. var world = this.getWorldMatrix();
  22065. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  22066. var direction = ray.direction.clone();
  22067. direction = direction.scale(intersectInfo.distance);
  22068. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  22069. var pickedPoint = worldOrigin.add(worldDirection);
  22070. // Return result
  22071. pickingInfo.hit = true;
  22072. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  22073. pickingInfo.pickedPoint = pickedPoint;
  22074. pickingInfo.pickedMesh = this;
  22075. pickingInfo.bu = intersectInfo.bu || 0;
  22076. pickingInfo.bv = intersectInfo.bv || 0;
  22077. pickingInfo.faceId = intersectInfo.faceId;
  22078. pickingInfo.subMeshId = intersectInfo.subMeshId;
  22079. return pickingInfo;
  22080. }
  22081. return pickingInfo;
  22082. };
  22083. /**
  22084. * Clones the current mesh
  22085. * @param name defines the mesh name
  22086. * @param newParent defines the new mesh parent
  22087. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  22088. * @returns the new mesh
  22089. */
  22090. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22091. return null;
  22092. };
  22093. /**
  22094. * Disposes all the submeshes of the current meshnp
  22095. * @returns the current mesh
  22096. */
  22097. AbstractMesh.prototype.releaseSubMeshes = function () {
  22098. if (this.subMeshes) {
  22099. while (this.subMeshes.length) {
  22100. this.subMeshes[0].dispose();
  22101. }
  22102. }
  22103. else {
  22104. this.subMeshes = new Array();
  22105. }
  22106. return this;
  22107. };
  22108. /**
  22109. * Releases resources associated with this abstract mesh.
  22110. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22111. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22112. */
  22113. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22114. var _this = this;
  22115. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22116. var index;
  22117. // Smart Array Retainers.
  22118. this.getScene().freeActiveMeshes();
  22119. this.getScene().freeRenderingGroups();
  22120. // Action manager
  22121. if (this.actionManager !== undefined && this.actionManager !== null) {
  22122. this.actionManager.dispose();
  22123. this.actionManager = null;
  22124. }
  22125. // Skeleton
  22126. this._skeleton = null;
  22127. // Intersections in progress
  22128. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  22129. var other = this._intersectionsInProgress[index];
  22130. var pos = other._intersectionsInProgress.indexOf(this);
  22131. other._intersectionsInProgress.splice(pos, 1);
  22132. }
  22133. this._intersectionsInProgress = [];
  22134. // Lights
  22135. var lights = this.getScene().lights;
  22136. lights.forEach(function (light) {
  22137. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22138. if (meshIndex !== -1) {
  22139. light.includedOnlyMeshes.splice(meshIndex, 1);
  22140. }
  22141. meshIndex = light.excludedMeshes.indexOf(_this);
  22142. if (meshIndex !== -1) {
  22143. light.excludedMeshes.splice(meshIndex, 1);
  22144. }
  22145. // Shadow generators
  22146. var generator = light.getShadowGenerator();
  22147. if (generator) {
  22148. var shadowMap = generator.getShadowMap();
  22149. if (shadowMap && shadowMap.renderList) {
  22150. meshIndex = shadowMap.renderList.indexOf(_this);
  22151. if (meshIndex !== -1) {
  22152. shadowMap.renderList.splice(meshIndex, 1);
  22153. }
  22154. }
  22155. }
  22156. });
  22157. // SubMeshes
  22158. if (this.getClassName() !== "InstancedMesh") {
  22159. this.releaseSubMeshes();
  22160. }
  22161. // Query
  22162. var engine = this.getScene().getEngine();
  22163. if (this._occlusionQuery) {
  22164. this.isOcclusionQueryInProgress = false;
  22165. engine.deleteQuery(this._occlusionQuery);
  22166. this._occlusionQuery = null;
  22167. }
  22168. // Engine
  22169. engine.wipeCaches();
  22170. // Remove from scene
  22171. this.getScene().removeMesh(this);
  22172. if (disposeMaterialAndTextures) {
  22173. if (this.material) {
  22174. this.material.dispose(false, true);
  22175. }
  22176. }
  22177. if (!doNotRecurse) {
  22178. // Particles
  22179. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22180. if (this.getScene().particleSystems[index].emitter === this) {
  22181. this.getScene().particleSystems[index].dispose();
  22182. index--;
  22183. }
  22184. }
  22185. }
  22186. // facet data
  22187. if (this._facetData.facetDataEnabled) {
  22188. this.disableFacetData();
  22189. }
  22190. this.onAfterWorldMatrixUpdateObservable.clear();
  22191. this.onCollideObservable.clear();
  22192. this.onCollisionPositionChangeObservable.clear();
  22193. this.onRebuildObservable.clear();
  22194. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22195. };
  22196. /**
  22197. * Adds the passed mesh as a child to the current mesh
  22198. * @param mesh defines the child mesh
  22199. * @returns the current mesh
  22200. */
  22201. AbstractMesh.prototype.addChild = function (mesh) {
  22202. mesh.setParent(this);
  22203. return this;
  22204. };
  22205. /**
  22206. * Removes the passed mesh from the current mesh children list
  22207. * @param mesh defines the child mesh
  22208. * @returns the current mesh
  22209. */
  22210. AbstractMesh.prototype.removeChild = function (mesh) {
  22211. mesh.setParent(null);
  22212. return this;
  22213. };
  22214. // Facet data
  22215. /** @hidden */
  22216. AbstractMesh.prototype._initFacetData = function () {
  22217. var data = this._facetData;
  22218. if (!data.facetNormals) {
  22219. data.facetNormals = new Array();
  22220. }
  22221. if (!data.facetPositions) {
  22222. data.facetPositions = new Array();
  22223. }
  22224. if (!data.facetPartitioning) {
  22225. data.facetPartitioning = new Array();
  22226. }
  22227. data.facetNb = (this.getIndices().length / 3) | 0;
  22228. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22229. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22230. for (var f = 0; f < data.facetNb; f++) {
  22231. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22232. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22233. }
  22234. data.facetDataEnabled = true;
  22235. return this;
  22236. };
  22237. /**
  22238. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22239. * This method can be called within the render loop.
  22240. * 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
  22241. * @returns the current mesh
  22242. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22243. */
  22244. AbstractMesh.prototype.updateFacetData = function () {
  22245. var data = this._facetData;
  22246. if (!data.facetDataEnabled) {
  22247. this._initFacetData();
  22248. }
  22249. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22250. var indices = this.getIndices();
  22251. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22252. var bInfo = this.getBoundingInfo();
  22253. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22254. // init arrays, matrix and sort function on first call
  22255. data.facetDepthSortEnabled = true;
  22256. if (indices instanceof Uint16Array) {
  22257. data.depthSortedIndices = new Uint16Array(indices);
  22258. }
  22259. else if (indices instanceof Uint32Array) {
  22260. data.depthSortedIndices = new Uint32Array(indices);
  22261. }
  22262. else {
  22263. var needs32bits = false;
  22264. for (var i = 0; i < indices.length; i++) {
  22265. if (indices[i] > 65535) {
  22266. needs32bits = true;
  22267. break;
  22268. }
  22269. }
  22270. if (needs32bits) {
  22271. data.depthSortedIndices = new Uint32Array(indices);
  22272. }
  22273. else {
  22274. data.depthSortedIndices = new Uint16Array(indices);
  22275. }
  22276. }
  22277. data.facetDepthSortFunction = function (f1, f2) {
  22278. return (f2.sqDistance - f1.sqDistance);
  22279. };
  22280. if (!data.facetDepthSortFrom) {
  22281. var camera = this.getScene().activeCamera;
  22282. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22283. }
  22284. data.depthSortedFacets = [];
  22285. for (var f = 0; f < data.facetNb; f++) {
  22286. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22287. data.depthSortedFacets.push(depthSortedFacet);
  22288. }
  22289. data.invertedMatrix = BABYLON.Matrix.Identity();
  22290. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22291. }
  22292. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22293. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22294. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22295. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22296. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22297. data.subDiv.max = data.partitioningSubdivisions;
  22298. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22299. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22300. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22301. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22302. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22303. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22304. // set the parameters for ComputeNormals()
  22305. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22306. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22307. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22308. data.facetParameters.bInfo = bInfo;
  22309. data.facetParameters.bbSize = data.bbSize;
  22310. data.facetParameters.subDiv = data.subDiv;
  22311. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22312. data.facetParameters.depthSort = data.facetDepthSort;
  22313. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22314. this.computeWorldMatrix(true);
  22315. this._worldMatrix.invertToRef(data.invertedMatrix);
  22316. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22317. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22318. }
  22319. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22320. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22321. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22322. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22323. var l = (data.depthSortedIndices.length / 3) | 0;
  22324. for (var f = 0; f < l; f++) {
  22325. var sind = data.depthSortedFacets[f].ind;
  22326. data.depthSortedIndices[f * 3] = indices[sind];
  22327. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22328. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22329. }
  22330. this.updateIndices(data.depthSortedIndices);
  22331. }
  22332. return this;
  22333. };
  22334. /**
  22335. * Returns the facetLocalNormals array.
  22336. * The normals are expressed in the mesh local spac
  22337. * @returns an array of Vector3
  22338. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22339. */
  22340. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22341. if (!this._facetData.facetNormals) {
  22342. this.updateFacetData();
  22343. }
  22344. return this._facetData.facetNormals;
  22345. };
  22346. /**
  22347. * Returns the facetLocalPositions array.
  22348. * The facet positions are expressed in the mesh local space
  22349. * @returns an array of Vector3
  22350. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22351. */
  22352. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22353. if (!this._facetData.facetPositions) {
  22354. this.updateFacetData();
  22355. }
  22356. return this._facetData.facetPositions;
  22357. };
  22358. /**
  22359. * Returns the facetLocalPartioning array
  22360. * @returns an array of array of numbers
  22361. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22362. */
  22363. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22364. if (!this._facetData.facetPartitioning) {
  22365. this.updateFacetData();
  22366. }
  22367. return this._facetData.facetPartitioning;
  22368. };
  22369. /**
  22370. * Returns the i-th facet position in the world system.
  22371. * This method allocates a new Vector3 per call
  22372. * @param i defines the facet index
  22373. * @returns a new Vector3
  22374. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22375. */
  22376. AbstractMesh.prototype.getFacetPosition = function (i) {
  22377. var pos = BABYLON.Vector3.Zero();
  22378. this.getFacetPositionToRef(i, pos);
  22379. return pos;
  22380. };
  22381. /**
  22382. * Sets the reference Vector3 with the i-th facet position in the world system
  22383. * @param i defines the facet index
  22384. * @param ref defines the target vector
  22385. * @returns the current mesh
  22386. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22387. */
  22388. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22389. var localPos = (this.getFacetLocalPositions())[i];
  22390. var world = this.getWorldMatrix();
  22391. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22392. return this;
  22393. };
  22394. /**
  22395. * Returns the i-th facet normal in the world system.
  22396. * This method allocates a new Vector3 per call
  22397. * @param i defines the facet index
  22398. * @returns a new Vector3
  22399. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22400. */
  22401. AbstractMesh.prototype.getFacetNormal = function (i) {
  22402. var norm = BABYLON.Vector3.Zero();
  22403. this.getFacetNormalToRef(i, norm);
  22404. return norm;
  22405. };
  22406. /**
  22407. * Sets the reference Vector3 with the i-th facet normal in the world system
  22408. * @param i defines the facet index
  22409. * @param ref defines the target vector
  22410. * @returns the current mesh
  22411. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22412. */
  22413. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22414. var localNorm = (this.getFacetLocalNormals())[i];
  22415. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22416. return this;
  22417. };
  22418. /**
  22419. * 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)
  22420. * @param x defines x coordinate
  22421. * @param y defines y coordinate
  22422. * @param z defines z coordinate
  22423. * @returns the array of facet indexes
  22424. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22425. */
  22426. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22427. var bInfo = this.getBoundingInfo();
  22428. var data = this._facetData;
  22429. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22430. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22431. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22432. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22433. return null;
  22434. }
  22435. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22436. };
  22437. /**
  22438. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22439. * @param projected sets as the (x,y,z) world projection on the facet
  22440. * @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
  22441. * @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
  22442. * @param x defines x coordinate
  22443. * @param y defines y coordinate
  22444. * @param z defines z coordinate
  22445. * @returns the face index if found (or null instead)
  22446. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22447. */
  22448. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22449. if (checkFace === void 0) { checkFace = false; }
  22450. if (facing === void 0) { facing = true; }
  22451. var world = this.getWorldMatrix();
  22452. var invMat = BABYLON.Tmp.Matrix[5];
  22453. world.invertToRef(invMat);
  22454. var invVect = BABYLON.Tmp.Vector3[8];
  22455. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22456. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22457. if (projected) {
  22458. // tranform the local computed projected vector to world coordinates
  22459. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22460. }
  22461. return closest;
  22462. };
  22463. /**
  22464. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22465. * @param projected sets as the (x,y,z) local projection on the facet
  22466. * @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
  22467. * @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
  22468. * @param x defines x coordinate
  22469. * @param y defines y coordinate
  22470. * @param z defines z coordinate
  22471. * @returns the face index if found (or null instead)
  22472. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22473. */
  22474. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22475. if (checkFace === void 0) { checkFace = false; }
  22476. if (facing === void 0) { facing = true; }
  22477. var closest = null;
  22478. var tmpx = 0.0;
  22479. var tmpy = 0.0;
  22480. var tmpz = 0.0;
  22481. var d = 0.0; // tmp dot facet normal * facet position
  22482. var t0 = 0.0;
  22483. var projx = 0.0;
  22484. var projy = 0.0;
  22485. var projz = 0.0;
  22486. // Get all the facets in the same partitioning block than (x, y, z)
  22487. var facetPositions = this.getFacetLocalPositions();
  22488. var facetNormals = this.getFacetLocalNormals();
  22489. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22490. if (!facetsInBlock) {
  22491. return null;
  22492. }
  22493. // Get the closest facet to (x, y, z)
  22494. var shortest = Number.MAX_VALUE; // init distance vars
  22495. var tmpDistance = shortest;
  22496. var fib; // current facet in the block
  22497. var norm; // current facet normal
  22498. var p0; // current facet barycenter position
  22499. // loop on all the facets in the current partitioning block
  22500. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22501. fib = facetsInBlock[idx];
  22502. norm = facetNormals[fib];
  22503. p0 = facetPositions[fib];
  22504. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22505. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22506. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22507. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22508. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22509. projx = x + norm.x * t0;
  22510. projy = y + norm.y * t0;
  22511. projz = z + norm.z * t0;
  22512. tmpx = projx - x;
  22513. tmpy = projy - y;
  22514. tmpz = projz - z;
  22515. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22516. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22517. shortest = tmpDistance;
  22518. closest = fib;
  22519. if (projected) {
  22520. projected.x = projx;
  22521. projected.y = projy;
  22522. projected.z = projz;
  22523. }
  22524. }
  22525. }
  22526. }
  22527. return closest;
  22528. };
  22529. /**
  22530. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22531. * @returns the parameters
  22532. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22533. */
  22534. AbstractMesh.prototype.getFacetDataParameters = function () {
  22535. return this._facetData.facetParameters;
  22536. };
  22537. /**
  22538. * Disables the feature FacetData and frees the related memory
  22539. * @returns the current mesh
  22540. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22541. */
  22542. AbstractMesh.prototype.disableFacetData = function () {
  22543. if (this._facetData.facetDataEnabled) {
  22544. this._facetData.facetDataEnabled = false;
  22545. this._facetData.facetPositions = new Array();
  22546. this._facetData.facetNormals = new Array();
  22547. this._facetData.facetPartitioning = new Array();
  22548. this._facetData.facetParameters = null;
  22549. this._facetData.depthSortedIndices = new Uint32Array(0);
  22550. }
  22551. return this;
  22552. };
  22553. /**
  22554. * Updates the AbstractMesh indices array
  22555. * @param indices defines the data source
  22556. * @returns the current mesh
  22557. */
  22558. AbstractMesh.prototype.updateIndices = function (indices) {
  22559. return this;
  22560. };
  22561. /**
  22562. * Creates new normals data for the mesh
  22563. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22564. * @returns the current mesh
  22565. */
  22566. AbstractMesh.prototype.createNormals = function (updatable) {
  22567. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22568. var indices = this.getIndices();
  22569. var normals;
  22570. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22571. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22572. }
  22573. else {
  22574. normals = [];
  22575. }
  22576. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22577. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22578. return this;
  22579. };
  22580. /**
  22581. * Align the mesh with a normal
  22582. * @param normal defines the normal to use
  22583. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22584. * @returns the current mesh
  22585. */
  22586. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22587. if (!upDirection) {
  22588. upDirection = BABYLON.Axis.Y;
  22589. }
  22590. var axisX = BABYLON.Tmp.Vector3[0];
  22591. var axisZ = BABYLON.Tmp.Vector3[1];
  22592. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22593. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22594. if (this.rotationQuaternion) {
  22595. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22596. }
  22597. else {
  22598. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22599. }
  22600. return this;
  22601. };
  22602. /** @hidden */
  22603. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22604. return false;
  22605. };
  22606. /** No occlusion */
  22607. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22608. /** Occlusion set to optimisitic */
  22609. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22610. /** Occlusion set to strict */
  22611. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22612. /** Use an accurante occlusion algorithm */
  22613. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22614. /** Use a conservative occlusion algorithm */
  22615. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22616. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22617. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22618. /** Culling strategy with bounding sphere only and then frustum culling */
  22619. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22620. return AbstractMesh;
  22621. }(BABYLON.TransformNode));
  22622. BABYLON.AbstractMesh = AbstractMesh;
  22623. })(BABYLON || (BABYLON = {}));
  22624. //# sourceMappingURL=babylon.abstractMesh.js.map
  22625. var BABYLON;
  22626. (function (BABYLON) {
  22627. /**
  22628. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22629. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22630. * 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.
  22631. */
  22632. var Light = /** @class */ (function (_super) {
  22633. __extends(Light, _super);
  22634. /**
  22635. * Creates a Light object in the scene.
  22636. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22637. * @param name The firendly name of the light
  22638. * @param scene The scene the light belongs too
  22639. */
  22640. function Light(name, scene) {
  22641. var _this = _super.call(this, name, scene) || this;
  22642. /**
  22643. * Diffuse gives the basic color to an object.
  22644. */
  22645. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22646. /**
  22647. * Specular produces a highlight color on an object.
  22648. * Note: This is note affecting PBR materials.
  22649. */
  22650. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22651. /**
  22652. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22653. * falling off base on range or angle.
  22654. * This can be set to any values in Light.FALLOFF_x.
  22655. *
  22656. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22657. * other types of materials.
  22658. */
  22659. _this.falloffType = Light.FALLOFF_DEFAULT;
  22660. /**
  22661. * Strength of the light.
  22662. * Note: By default it is define in the framework own unit.
  22663. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22664. */
  22665. _this.intensity = 1.0;
  22666. _this._range = Number.MAX_VALUE;
  22667. _this._inverseSquaredRange = 0;
  22668. /**
  22669. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22670. * of light.
  22671. */
  22672. _this._photometricScale = 1.0;
  22673. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22674. _this._radius = 0.00001;
  22675. /**
  22676. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22677. * exceeding the number allowed of the materials.
  22678. */
  22679. _this.renderPriority = 0;
  22680. _this._shadowEnabled = true;
  22681. _this._excludeWithLayerMask = 0;
  22682. _this._includeOnlyWithLayerMask = 0;
  22683. _this._lightmapMode = 0;
  22684. /**
  22685. * @hidden Internal use only.
  22686. */
  22687. _this._excludedMeshesIds = new Array();
  22688. /**
  22689. * @hidden Internal use only.
  22690. */
  22691. _this._includedOnlyMeshesIds = new Array();
  22692. _this.getScene().addLight(_this);
  22693. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22694. _this._buildUniformLayout();
  22695. _this.includedOnlyMeshes = new Array();
  22696. _this.excludedMeshes = new Array();
  22697. _this._resyncMeshes();
  22698. return _this;
  22699. }
  22700. Object.defineProperty(Light.prototype, "range", {
  22701. /**
  22702. * Defines how far from the source the light is impacting in scene units.
  22703. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22704. */
  22705. get: function () {
  22706. return this._range;
  22707. },
  22708. /**
  22709. * Defines how far from the source the light is impacting in scene units.
  22710. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22711. */
  22712. set: function (value) {
  22713. this._range = value;
  22714. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22715. },
  22716. enumerable: true,
  22717. configurable: true
  22718. });
  22719. Object.defineProperty(Light.prototype, "intensityMode", {
  22720. /**
  22721. * Gets the photometric scale used to interpret the intensity.
  22722. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22723. */
  22724. get: function () {
  22725. return this._intensityMode;
  22726. },
  22727. /**
  22728. * Sets the photometric scale used to interpret the intensity.
  22729. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22730. */
  22731. set: function (value) {
  22732. this._intensityMode = value;
  22733. this._computePhotometricScale();
  22734. },
  22735. enumerable: true,
  22736. configurable: true
  22737. });
  22738. Object.defineProperty(Light.prototype, "radius", {
  22739. /**
  22740. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22741. */
  22742. get: function () {
  22743. return this._radius;
  22744. },
  22745. /**
  22746. * sets the light radius used by PBR Materials to simulate soft area lights.
  22747. */
  22748. set: function (value) {
  22749. this._radius = value;
  22750. this._computePhotometricScale();
  22751. },
  22752. enumerable: true,
  22753. configurable: true
  22754. });
  22755. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22756. /**
  22757. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22758. * the current shadow generator.
  22759. */
  22760. get: function () {
  22761. return this._shadowEnabled;
  22762. },
  22763. /**
  22764. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22765. * the current shadow generator.
  22766. */
  22767. set: function (value) {
  22768. if (this._shadowEnabled === value) {
  22769. return;
  22770. }
  22771. this._shadowEnabled = value;
  22772. this._markMeshesAsLightDirty();
  22773. },
  22774. enumerable: true,
  22775. configurable: true
  22776. });
  22777. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22778. /**
  22779. * Gets the only meshes impacted by this light.
  22780. */
  22781. get: function () {
  22782. return this._includedOnlyMeshes;
  22783. },
  22784. /**
  22785. * Sets the only meshes impacted by this light.
  22786. */
  22787. set: function (value) {
  22788. this._includedOnlyMeshes = value;
  22789. this._hookArrayForIncludedOnly(value);
  22790. },
  22791. enumerable: true,
  22792. configurable: true
  22793. });
  22794. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22795. /**
  22796. * Gets the meshes not impacted by this light.
  22797. */
  22798. get: function () {
  22799. return this._excludedMeshes;
  22800. },
  22801. /**
  22802. * Sets the meshes not impacted by this light.
  22803. */
  22804. set: function (value) {
  22805. this._excludedMeshes = value;
  22806. this._hookArrayForExcluded(value);
  22807. },
  22808. enumerable: true,
  22809. configurable: true
  22810. });
  22811. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22812. /**
  22813. * Gets the layer id use to find what meshes are not impacted by the light.
  22814. * Inactive if 0
  22815. */
  22816. get: function () {
  22817. return this._excludeWithLayerMask;
  22818. },
  22819. /**
  22820. * Sets the layer id use to find what meshes are not impacted by the light.
  22821. * Inactive if 0
  22822. */
  22823. set: function (value) {
  22824. this._excludeWithLayerMask = value;
  22825. this._resyncMeshes();
  22826. },
  22827. enumerable: true,
  22828. configurable: true
  22829. });
  22830. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22831. /**
  22832. * Gets the layer id use to find what meshes are impacted by the light.
  22833. * Inactive if 0
  22834. */
  22835. get: function () {
  22836. return this._includeOnlyWithLayerMask;
  22837. },
  22838. /**
  22839. * Sets the layer id use to find what meshes are impacted by the light.
  22840. * Inactive if 0
  22841. */
  22842. set: function (value) {
  22843. this._includeOnlyWithLayerMask = value;
  22844. this._resyncMeshes();
  22845. },
  22846. enumerable: true,
  22847. configurable: true
  22848. });
  22849. Object.defineProperty(Light.prototype, "lightmapMode", {
  22850. /**
  22851. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22852. */
  22853. get: function () {
  22854. return this._lightmapMode;
  22855. },
  22856. /**
  22857. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22858. */
  22859. set: function (value) {
  22860. if (this._lightmapMode === value) {
  22861. return;
  22862. }
  22863. this._lightmapMode = value;
  22864. this._markMeshesAsLightDirty();
  22865. },
  22866. enumerable: true,
  22867. configurable: true
  22868. });
  22869. /**
  22870. * Returns the string "Light".
  22871. * @returns the class name
  22872. */
  22873. Light.prototype.getClassName = function () {
  22874. return "Light";
  22875. };
  22876. /**
  22877. * Converts the light information to a readable string for debug purpose.
  22878. * @param fullDetails Supports for multiple levels of logging within scene loading
  22879. * @returns the human readable light info
  22880. */
  22881. Light.prototype.toString = function (fullDetails) {
  22882. var ret = "Name: " + this.name;
  22883. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22884. if (this.animations) {
  22885. for (var i = 0; i < this.animations.length; i++) {
  22886. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22887. }
  22888. }
  22889. if (fullDetails) {
  22890. }
  22891. return ret;
  22892. };
  22893. /** @hidden */
  22894. Light.prototype._syncParentEnabledState = function () {
  22895. _super.prototype._syncParentEnabledState.call(this);
  22896. this._resyncMeshes();
  22897. };
  22898. /**
  22899. * Set the enabled state of this node.
  22900. * @param value - the new enabled state
  22901. */
  22902. Light.prototype.setEnabled = function (value) {
  22903. _super.prototype.setEnabled.call(this, value);
  22904. this._resyncMeshes();
  22905. };
  22906. /**
  22907. * Returns the Light associated shadow generator if any.
  22908. * @return the associated shadow generator.
  22909. */
  22910. Light.prototype.getShadowGenerator = function () {
  22911. return this._shadowGenerator;
  22912. };
  22913. /**
  22914. * Returns a Vector3, the absolute light position in the World.
  22915. * @returns the world space position of the light
  22916. */
  22917. Light.prototype.getAbsolutePosition = function () {
  22918. return BABYLON.Vector3.Zero();
  22919. };
  22920. /**
  22921. * Specifies if the light will affect the passed mesh.
  22922. * @param mesh The mesh to test against the light
  22923. * @return true the mesh is affected otherwise, false.
  22924. */
  22925. Light.prototype.canAffectMesh = function (mesh) {
  22926. if (!mesh) {
  22927. return true;
  22928. }
  22929. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22930. return false;
  22931. }
  22932. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22933. return false;
  22934. }
  22935. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22936. return false;
  22937. }
  22938. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22939. return false;
  22940. }
  22941. return true;
  22942. };
  22943. /**
  22944. * Sort function to order lights for rendering.
  22945. * @param a First Light object to compare to second.
  22946. * @param b Second Light object to compare first.
  22947. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22948. */
  22949. Light.CompareLightsPriority = function (a, b) {
  22950. //shadow-casting lights have priority over non-shadow-casting lights
  22951. //the renderPrioirty is a secondary sort criterion
  22952. if (a.shadowEnabled !== b.shadowEnabled) {
  22953. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22954. }
  22955. return b.renderPriority - a.renderPriority;
  22956. };
  22957. /**
  22958. * Releases resources associated with this node.
  22959. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22960. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22961. */
  22962. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22963. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22964. if (this._shadowGenerator) {
  22965. this._shadowGenerator.dispose();
  22966. this._shadowGenerator = null;
  22967. }
  22968. // Animations
  22969. this.getScene().stopAnimation(this);
  22970. // Remove from meshes
  22971. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22972. var mesh = _a[_i];
  22973. mesh._removeLightSource(this);
  22974. }
  22975. this._uniformBuffer.dispose();
  22976. // Remove from scene
  22977. this.getScene().removeLight(this);
  22978. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22979. };
  22980. /**
  22981. * Returns the light type ID (integer).
  22982. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22983. */
  22984. Light.prototype.getTypeID = function () {
  22985. return 0;
  22986. };
  22987. /**
  22988. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22989. * @returns the scaled intensity in intensity mode unit
  22990. */
  22991. Light.prototype.getScaledIntensity = function () {
  22992. return this._photometricScale * this.intensity;
  22993. };
  22994. /**
  22995. * Returns a new Light object, named "name", from the current one.
  22996. * @param name The name of the cloned light
  22997. * @returns the new created light
  22998. */
  22999. Light.prototype.clone = function (name) {
  23000. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  23001. if (!constructor) {
  23002. return null;
  23003. }
  23004. return BABYLON.SerializationHelper.Clone(constructor, this);
  23005. };
  23006. /**
  23007. * Serializes the current light into a Serialization object.
  23008. * @returns the serialized object.
  23009. */
  23010. Light.prototype.serialize = function () {
  23011. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23012. // Type
  23013. serializationObject.type = this.getTypeID();
  23014. // Parent
  23015. if (this.parent) {
  23016. serializationObject.parentId = this.parent.id;
  23017. }
  23018. // Inclusion / exclusions
  23019. if (this.excludedMeshes.length > 0) {
  23020. serializationObject.excludedMeshesIds = [];
  23021. this.excludedMeshes.forEach(function (mesh) {
  23022. serializationObject.excludedMeshesIds.push(mesh.id);
  23023. });
  23024. }
  23025. if (this.includedOnlyMeshes.length > 0) {
  23026. serializationObject.includedOnlyMeshesIds = [];
  23027. this.includedOnlyMeshes.forEach(function (mesh) {
  23028. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  23029. });
  23030. }
  23031. // Animations
  23032. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23033. serializationObject.ranges = this.serializeAnimationRanges();
  23034. return serializationObject;
  23035. };
  23036. /**
  23037. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  23038. * This new light is named "name" and added to the passed scene.
  23039. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  23040. * @param name The friendly name of the light
  23041. * @param scene The scene the new light will belong to
  23042. * @returns the constructor function
  23043. */
  23044. Light.GetConstructorFromName = function (type, name, scene) {
  23045. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  23046. if (constructorFunc) {
  23047. return constructorFunc;
  23048. }
  23049. // Default to no light for none present once.
  23050. return null;
  23051. };
  23052. /**
  23053. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  23054. * @param parsedLight The JSON representation of the light
  23055. * @param scene The scene to create the parsed light in
  23056. * @returns the created light after parsing
  23057. */
  23058. Light.Parse = function (parsedLight, scene) {
  23059. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  23060. if (!constructor) {
  23061. return null;
  23062. }
  23063. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  23064. // Inclusion / exclusions
  23065. if (parsedLight.excludedMeshesIds) {
  23066. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  23067. }
  23068. if (parsedLight.includedOnlyMeshesIds) {
  23069. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  23070. }
  23071. // Parent
  23072. if (parsedLight.parentId) {
  23073. light._waitingParentId = parsedLight.parentId;
  23074. }
  23075. // Animations
  23076. if (parsedLight.animations) {
  23077. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  23078. var parsedAnimation = parsedLight.animations[animationIndex];
  23079. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23080. }
  23081. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  23082. }
  23083. if (parsedLight.autoAnimate) {
  23084. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  23085. }
  23086. return light;
  23087. };
  23088. Light.prototype._hookArrayForExcluded = function (array) {
  23089. var _this = this;
  23090. var oldPush = array.push;
  23091. array.push = function () {
  23092. var items = [];
  23093. for (var _i = 0; _i < arguments.length; _i++) {
  23094. items[_i] = arguments[_i];
  23095. }
  23096. var result = oldPush.apply(array, items);
  23097. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  23098. var item = items_1[_a];
  23099. item._resyncLighSource(_this);
  23100. }
  23101. return result;
  23102. };
  23103. var oldSplice = array.splice;
  23104. array.splice = function (index, deleteCount) {
  23105. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23106. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  23107. var item = deleted_1[_i];
  23108. item._resyncLighSource(_this);
  23109. }
  23110. return deleted;
  23111. };
  23112. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  23113. var item = array_1[_i];
  23114. item._resyncLighSource(this);
  23115. }
  23116. };
  23117. Light.prototype._hookArrayForIncludedOnly = function (array) {
  23118. var _this = this;
  23119. var oldPush = array.push;
  23120. array.push = function () {
  23121. var items = [];
  23122. for (var _i = 0; _i < arguments.length; _i++) {
  23123. items[_i] = arguments[_i];
  23124. }
  23125. var result = oldPush.apply(array, items);
  23126. _this._resyncMeshes();
  23127. return result;
  23128. };
  23129. var oldSplice = array.splice;
  23130. array.splice = function (index, deleteCount) {
  23131. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23132. _this._resyncMeshes();
  23133. return deleted;
  23134. };
  23135. this._resyncMeshes();
  23136. };
  23137. Light.prototype._resyncMeshes = function () {
  23138. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23139. var mesh = _a[_i];
  23140. mesh._resyncLighSource(this);
  23141. }
  23142. };
  23143. /**
  23144. * Forces the meshes to update their light related information in their rendering used effects
  23145. * @hidden Internal Use Only
  23146. */
  23147. Light.prototype._markMeshesAsLightDirty = function () {
  23148. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23149. var mesh = _a[_i];
  23150. if (mesh._lightSources.indexOf(this) !== -1) {
  23151. mesh._markSubMeshesAsLightDirty();
  23152. }
  23153. }
  23154. };
  23155. /**
  23156. * Recomputes the cached photometric scale if needed.
  23157. */
  23158. Light.prototype._computePhotometricScale = function () {
  23159. this._photometricScale = this._getPhotometricScale();
  23160. this.getScene().resetCachedMaterial();
  23161. };
  23162. /**
  23163. * Returns the Photometric Scale according to the light type and intensity mode.
  23164. */
  23165. Light.prototype._getPhotometricScale = function () {
  23166. var photometricScale = 0.0;
  23167. var lightTypeID = this.getTypeID();
  23168. //get photometric mode
  23169. var photometricMode = this.intensityMode;
  23170. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23171. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23172. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23173. }
  23174. else {
  23175. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23176. }
  23177. }
  23178. //compute photometric scale
  23179. switch (lightTypeID) {
  23180. case Light.LIGHTTYPEID_POINTLIGHT:
  23181. case Light.LIGHTTYPEID_SPOTLIGHT:
  23182. switch (photometricMode) {
  23183. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23184. photometricScale = 1.0 / (4.0 * Math.PI);
  23185. break;
  23186. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23187. photometricScale = 1.0;
  23188. break;
  23189. case Light.INTENSITYMODE_LUMINANCE:
  23190. photometricScale = this.radius * this.radius;
  23191. break;
  23192. }
  23193. break;
  23194. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23195. switch (photometricMode) {
  23196. case Light.INTENSITYMODE_ILLUMINANCE:
  23197. photometricScale = 1.0;
  23198. break;
  23199. case Light.INTENSITYMODE_LUMINANCE:
  23200. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23201. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23202. var apexAngleRadians = this.radius;
  23203. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23204. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23205. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23206. photometricScale = solidAngle;
  23207. break;
  23208. }
  23209. break;
  23210. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23211. // No fall off in hemisperic light.
  23212. photometricScale = 1.0;
  23213. break;
  23214. }
  23215. return photometricScale;
  23216. };
  23217. /**
  23218. * Reorder the light in the scene according to their defined priority.
  23219. * @hidden Internal Use Only
  23220. */
  23221. Light.prototype._reorderLightsInScene = function () {
  23222. var scene = this.getScene();
  23223. if (this._renderPriority != 0) {
  23224. scene.requireLightSorting = true;
  23225. }
  23226. this.getScene().sortLightsByPriority();
  23227. };
  23228. /**
  23229. * Falloff Default: light is falling off following the material specification:
  23230. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23231. */
  23232. Light.FALLOFF_DEFAULT = 0;
  23233. /**
  23234. * Falloff Physical: light is falling off following the inverse squared distance law.
  23235. */
  23236. Light.FALLOFF_PHYSICAL = 1;
  23237. /**
  23238. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23239. * to enhance interoperability with other engines.
  23240. */
  23241. Light.FALLOFF_GLTF = 2;
  23242. /**
  23243. * Falloff Standard: light is falling off like in the standard material
  23244. * to enhance interoperability with other materials.
  23245. */
  23246. Light.FALLOFF_STANDARD = 3;
  23247. //lightmapMode Consts
  23248. /**
  23249. * If every light affecting the material is in this lightmapMode,
  23250. * material.lightmapTexture adds or multiplies
  23251. * (depends on material.useLightmapAsShadowmap)
  23252. * after every other light calculations.
  23253. */
  23254. Light.LIGHTMAP_DEFAULT = 0;
  23255. /**
  23256. * material.lightmapTexture as only diffuse lighting from this light
  23257. * adds only specular lighting from this light
  23258. * adds dynamic shadows
  23259. */
  23260. Light.LIGHTMAP_SPECULAR = 1;
  23261. /**
  23262. * material.lightmapTexture as only lighting
  23263. * no light calculation from this light
  23264. * only adds dynamic shadows from this light
  23265. */
  23266. Light.LIGHTMAP_SHADOWSONLY = 2;
  23267. // Intensity Mode Consts
  23268. /**
  23269. * Each light type uses the default quantity according to its type:
  23270. * point/spot lights use luminous intensity
  23271. * directional lights use illuminance
  23272. */
  23273. Light.INTENSITYMODE_AUTOMATIC = 0;
  23274. /**
  23275. * lumen (lm)
  23276. */
  23277. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23278. /**
  23279. * candela (lm/sr)
  23280. */
  23281. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23282. /**
  23283. * lux (lm/m^2)
  23284. */
  23285. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23286. /**
  23287. * nit (cd/m^2)
  23288. */
  23289. Light.INTENSITYMODE_LUMINANCE = 4;
  23290. // Light types ids const.
  23291. /**
  23292. * Light type const id of the point light.
  23293. */
  23294. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23295. /**
  23296. * Light type const id of the directional light.
  23297. */
  23298. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23299. /**
  23300. * Light type const id of the spot light.
  23301. */
  23302. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23303. /**
  23304. * Light type const id of the hemispheric light.
  23305. */
  23306. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23307. __decorate([
  23308. BABYLON.serializeAsColor3()
  23309. ], Light.prototype, "diffuse", void 0);
  23310. __decorate([
  23311. BABYLON.serializeAsColor3()
  23312. ], Light.prototype, "specular", void 0);
  23313. __decorate([
  23314. BABYLON.serialize()
  23315. ], Light.prototype, "falloffType", void 0);
  23316. __decorate([
  23317. BABYLON.serialize()
  23318. ], Light.prototype, "intensity", void 0);
  23319. __decorate([
  23320. BABYLON.serialize()
  23321. ], Light.prototype, "range", null);
  23322. __decorate([
  23323. BABYLON.serialize()
  23324. ], Light.prototype, "intensityMode", null);
  23325. __decorate([
  23326. BABYLON.serialize()
  23327. ], Light.prototype, "radius", null);
  23328. __decorate([
  23329. BABYLON.serialize()
  23330. ], Light.prototype, "_renderPriority", void 0);
  23331. __decorate([
  23332. BABYLON.expandToProperty("_reorderLightsInScene")
  23333. ], Light.prototype, "renderPriority", void 0);
  23334. __decorate([
  23335. BABYLON.serialize("shadowEnabled")
  23336. ], Light.prototype, "_shadowEnabled", void 0);
  23337. __decorate([
  23338. BABYLON.serialize("excludeWithLayerMask")
  23339. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23340. __decorate([
  23341. BABYLON.serialize("includeOnlyWithLayerMask")
  23342. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23343. __decorate([
  23344. BABYLON.serialize("lightmapMode")
  23345. ], Light.prototype, "_lightmapMode", void 0);
  23346. return Light;
  23347. }(BABYLON.Node));
  23348. BABYLON.Light = Light;
  23349. })(BABYLON || (BABYLON = {}));
  23350. //# sourceMappingURL=babylon.light.js.map
  23351. var BABYLON;
  23352. (function (BABYLON) {
  23353. /**
  23354. * This is the base class of all the camera used in the application.
  23355. * @see http://doc.babylonjs.com/features/cameras
  23356. */
  23357. var Camera = /** @class */ (function (_super) {
  23358. __extends(Camera, _super);
  23359. /**
  23360. * Instantiates a new camera object.
  23361. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23362. * @see http://doc.babylonjs.com/features/cameras
  23363. * @param name Defines the name of the camera in the scene
  23364. * @param position Defines the position of the camera
  23365. * @param scene Defines the scene the camera belongs too
  23366. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23367. */
  23368. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23369. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23370. var _this = _super.call(this, name, scene) || this;
  23371. /**
  23372. * The vector the camera should consider as up.
  23373. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23374. */
  23375. _this.upVector = BABYLON.Vector3.Up();
  23376. /**
  23377. * Define the current limit on the left side for an orthographic camera
  23378. * In scene unit
  23379. */
  23380. _this.orthoLeft = null;
  23381. /**
  23382. * Define the current limit on the right side for an orthographic camera
  23383. * In scene unit
  23384. */
  23385. _this.orthoRight = null;
  23386. /**
  23387. * Define the current limit on the bottom side for an orthographic camera
  23388. * In scene unit
  23389. */
  23390. _this.orthoBottom = null;
  23391. /**
  23392. * Define the current limit on the top side for an orthographic camera
  23393. * In scene unit
  23394. */
  23395. _this.orthoTop = null;
  23396. /**
  23397. * Field Of View is set in Radians. (default is 0.8)
  23398. */
  23399. _this.fov = 0.8;
  23400. /**
  23401. * Define the minimum distance the camera can see from.
  23402. * This is important to note that the depth buffer are not infinite and the closer it starts
  23403. * the more your scene might encounter depth fighting issue.
  23404. */
  23405. _this.minZ = 1;
  23406. /**
  23407. * Define the maximum distance the camera can see to.
  23408. * This is important to note that the depth buffer are not infinite and the further it end
  23409. * the more your scene might encounter depth fighting issue.
  23410. */
  23411. _this.maxZ = 10000.0;
  23412. /**
  23413. * Define the default inertia of the camera.
  23414. * This helps giving a smooth feeling to the camera movement.
  23415. */
  23416. _this.inertia = 0.9;
  23417. /**
  23418. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23419. */
  23420. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23421. /**
  23422. * Define wether the camera is intermediate.
  23423. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23424. */
  23425. _this.isIntermediate = false;
  23426. /**
  23427. * Define the viewport of the camera.
  23428. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23429. */
  23430. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23431. /**
  23432. * Restricts the camera to viewing objects with the same layerMask.
  23433. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23434. */
  23435. _this.layerMask = 0x0FFFFFFF;
  23436. /**
  23437. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23438. */
  23439. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23440. /**
  23441. * Rig mode of the camera.
  23442. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23443. * This is normally controlled byt the camera themselves as internal use.
  23444. */
  23445. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23446. /**
  23447. * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
  23448. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23449. * else in the scene.
  23450. */
  23451. _this.customRenderTargets = new Array();
  23452. /**
  23453. * When set, the camera will render to this render target instead of the default canvas
  23454. */
  23455. _this.outputRenderTarget = null;
  23456. /**
  23457. * Observable triggered when the camera view matrix has changed.
  23458. */
  23459. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23460. /**
  23461. * Observable triggered when the camera Projection matrix has changed.
  23462. */
  23463. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23464. /**
  23465. * Observable triggered when the inputs have been processed.
  23466. */
  23467. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23468. /**
  23469. * Observable triggered when reset has been called and applied to the camera.
  23470. */
  23471. _this.onRestoreStateObservable = new BABYLON.Observable();
  23472. /** @hidden */
  23473. _this._rigCameras = new Array();
  23474. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23475. /** @hidden */
  23476. _this._skipRendering = false;
  23477. /** @hidden */
  23478. _this._projectionMatrix = new BABYLON.Matrix();
  23479. /** @hidden */
  23480. _this._postProcesses = new Array();
  23481. /** @hidden */
  23482. _this._activeMeshes = new BABYLON.SmartArray(256);
  23483. _this._globalPosition = BABYLON.Vector3.Zero();
  23484. /** hidden */
  23485. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23486. _this._doNotComputeProjectionMatrix = false;
  23487. _this._transformMatrix = BABYLON.Matrix.Zero();
  23488. _this._refreshFrustumPlanes = true;
  23489. _this.getScene().addCamera(_this);
  23490. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23491. _this.getScene().activeCamera = _this;
  23492. }
  23493. _this.position = position;
  23494. return _this;
  23495. }
  23496. /**
  23497. * Store current camera state (fov, position, etc..)
  23498. * @returns the camera
  23499. */
  23500. Camera.prototype.storeState = function () {
  23501. this._stateStored = true;
  23502. this._storedFov = this.fov;
  23503. return this;
  23504. };
  23505. /**
  23506. * Restores the camera state values if it has been stored. You must call storeState() first
  23507. */
  23508. Camera.prototype._restoreStateValues = function () {
  23509. if (!this._stateStored) {
  23510. return false;
  23511. }
  23512. this.fov = this._storedFov;
  23513. return true;
  23514. };
  23515. /**
  23516. * Restored camera state. You must call storeState() first.
  23517. * @returns true if restored and false otherwise
  23518. */
  23519. Camera.prototype.restoreState = function () {
  23520. if (this._restoreStateValues()) {
  23521. this.onRestoreStateObservable.notifyObservers(this);
  23522. return true;
  23523. }
  23524. return false;
  23525. };
  23526. /**
  23527. * Gets the class name of the camera.
  23528. * @returns the class name
  23529. */
  23530. Camera.prototype.getClassName = function () {
  23531. return "Camera";
  23532. };
  23533. /**
  23534. * Gets a string representation of the camera usefull for debug purpose.
  23535. * @param fullDetails Defines that a more verboe level of logging is required
  23536. * @returns the string representation
  23537. */
  23538. Camera.prototype.toString = function (fullDetails) {
  23539. var ret = "Name: " + this.name;
  23540. ret += ", type: " + this.getClassName();
  23541. if (this.animations) {
  23542. for (var i = 0; i < this.animations.length; i++) {
  23543. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23544. }
  23545. }
  23546. if (fullDetails) {
  23547. }
  23548. return ret;
  23549. };
  23550. Object.defineProperty(Camera.prototype, "globalPosition", {
  23551. /**
  23552. * Gets the current world space position of the camera.
  23553. */
  23554. get: function () {
  23555. return this._globalPosition;
  23556. },
  23557. enumerable: true,
  23558. configurable: true
  23559. });
  23560. /**
  23561. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23562. * @returns the active meshe list
  23563. */
  23564. Camera.prototype.getActiveMeshes = function () {
  23565. return this._activeMeshes;
  23566. };
  23567. /**
  23568. * Check wether a mesh is part of the current active mesh list of the camera
  23569. * @param mesh Defines the mesh to check
  23570. * @returns true if active, false otherwise
  23571. */
  23572. Camera.prototype.isActiveMesh = function (mesh) {
  23573. return (this._activeMeshes.indexOf(mesh) !== -1);
  23574. };
  23575. /**
  23576. * Is this camera ready to be used/rendered
  23577. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23578. * @return true if the camera is ready
  23579. */
  23580. Camera.prototype.isReady = function (completeCheck) {
  23581. if (completeCheck === void 0) { completeCheck = false; }
  23582. if (completeCheck) {
  23583. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23584. var pp = _a[_i];
  23585. if (pp && !pp.isReady()) {
  23586. return false;
  23587. }
  23588. }
  23589. }
  23590. return _super.prototype.isReady.call(this, completeCheck);
  23591. };
  23592. /** @hidden */
  23593. Camera.prototype._initCache = function () {
  23594. _super.prototype._initCache.call(this);
  23595. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23596. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23597. this._cache.mode = undefined;
  23598. this._cache.minZ = undefined;
  23599. this._cache.maxZ = undefined;
  23600. this._cache.fov = undefined;
  23601. this._cache.fovMode = undefined;
  23602. this._cache.aspectRatio = undefined;
  23603. this._cache.orthoLeft = undefined;
  23604. this._cache.orthoRight = undefined;
  23605. this._cache.orthoBottom = undefined;
  23606. this._cache.orthoTop = undefined;
  23607. this._cache.renderWidth = undefined;
  23608. this._cache.renderHeight = undefined;
  23609. };
  23610. /** @hidden */
  23611. Camera.prototype._updateCache = function (ignoreParentClass) {
  23612. if (!ignoreParentClass) {
  23613. _super.prototype._updateCache.call(this);
  23614. }
  23615. this._cache.position.copyFrom(this.position);
  23616. this._cache.upVector.copyFrom(this.upVector);
  23617. };
  23618. /** @hidden */
  23619. Camera.prototype._isSynchronized = function () {
  23620. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23621. };
  23622. /** @hidden */
  23623. Camera.prototype._isSynchronizedViewMatrix = function () {
  23624. if (!_super.prototype._isSynchronized.call(this)) {
  23625. return false;
  23626. }
  23627. return this._cache.position.equals(this.position)
  23628. && this._cache.upVector.equals(this.upVector)
  23629. && this.isSynchronizedWithParent();
  23630. };
  23631. /** @hidden */
  23632. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23633. var check = this._cache.mode === this.mode
  23634. && this._cache.minZ === this.minZ
  23635. && this._cache.maxZ === this.maxZ;
  23636. if (!check) {
  23637. return false;
  23638. }
  23639. var engine = this.getEngine();
  23640. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23641. check = this._cache.fov === this.fov
  23642. && this._cache.fovMode === this.fovMode
  23643. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23644. }
  23645. else {
  23646. check = this._cache.orthoLeft === this.orthoLeft
  23647. && this._cache.orthoRight === this.orthoRight
  23648. && this._cache.orthoBottom === this.orthoBottom
  23649. && this._cache.orthoTop === this.orthoTop
  23650. && this._cache.renderWidth === engine.getRenderWidth()
  23651. && this._cache.renderHeight === engine.getRenderHeight();
  23652. }
  23653. return check;
  23654. };
  23655. /**
  23656. * Attach the input controls to a specific dom element to get the input from.
  23657. * @param element Defines the element the controls should be listened from
  23658. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23659. */
  23660. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23661. };
  23662. /**
  23663. * Detach the current controls from the specified dom element.
  23664. * @param element Defines the element to stop listening the inputs from
  23665. */
  23666. Camera.prototype.detachControl = function (element) {
  23667. };
  23668. /**
  23669. * Update the camera state according to the different inputs gathered during the frame.
  23670. */
  23671. Camera.prototype.update = function () {
  23672. this._checkInputs();
  23673. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23674. this._updateRigCameras();
  23675. }
  23676. };
  23677. /** @hidden */
  23678. Camera.prototype._checkInputs = function () {
  23679. this.onAfterCheckInputsObservable.notifyObservers(this);
  23680. };
  23681. Object.defineProperty(Camera.prototype, "rigCameras", {
  23682. /** @hidden */
  23683. get: function () {
  23684. return this._rigCameras;
  23685. },
  23686. enumerable: true,
  23687. configurable: true
  23688. });
  23689. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23690. /**
  23691. * Gets the post process used by the rig cameras
  23692. */
  23693. get: function () {
  23694. return this._rigPostProcess;
  23695. },
  23696. enumerable: true,
  23697. configurable: true
  23698. });
  23699. /**
  23700. * Internal, gets the first post proces.
  23701. * @returns the first post process to be run on this camera.
  23702. */
  23703. Camera.prototype._getFirstPostProcess = function () {
  23704. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23705. if (this._postProcesses[ppIndex] !== null) {
  23706. return this._postProcesses[ppIndex];
  23707. }
  23708. }
  23709. return null;
  23710. };
  23711. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23712. // invalidate framebuffer
  23713. var firstPostProcess = this._getFirstPostProcess();
  23714. if (firstPostProcess) {
  23715. firstPostProcess.markTextureDirty();
  23716. }
  23717. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23718. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23719. var cam = this._rigCameras[i];
  23720. var rigPostProcess = cam._rigPostProcess;
  23721. // for VR rig, there does not have to be a post process
  23722. if (rigPostProcess) {
  23723. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23724. if (isPass) {
  23725. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23726. cam.isIntermediate = this._postProcesses.length === 0;
  23727. }
  23728. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23729. rigPostProcess.markTextureDirty();
  23730. }
  23731. else {
  23732. cam._postProcesses = this._postProcesses.slice(0);
  23733. }
  23734. }
  23735. };
  23736. /**
  23737. * Attach a post process to the camera.
  23738. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23739. * @param postProcess The post process to attach to the camera
  23740. * @param insertAt The position of the post process in case several of them are in use in the scene
  23741. * @returns the position the post process has been inserted at
  23742. */
  23743. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23744. if (insertAt === void 0) { insertAt = null; }
  23745. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23746. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23747. return 0;
  23748. }
  23749. if (insertAt == null || insertAt < 0) {
  23750. this._postProcesses.push(postProcess);
  23751. }
  23752. else if (this._postProcesses[insertAt] === null) {
  23753. this._postProcesses[insertAt] = postProcess;
  23754. }
  23755. else {
  23756. this._postProcesses.splice(insertAt, 0, postProcess);
  23757. }
  23758. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23759. return this._postProcesses.indexOf(postProcess);
  23760. };
  23761. /**
  23762. * Detach a post process to the camera.
  23763. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23764. * @param postProcess The post process to detach from the camera
  23765. */
  23766. Camera.prototype.detachPostProcess = function (postProcess) {
  23767. var idx = this._postProcesses.indexOf(postProcess);
  23768. if (idx !== -1) {
  23769. this._postProcesses[idx] = null;
  23770. }
  23771. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23772. };
  23773. /**
  23774. * Gets the current world matrix of the camera
  23775. */
  23776. Camera.prototype.getWorldMatrix = function () {
  23777. if (this._isSynchronizedViewMatrix()) {
  23778. return this._worldMatrix;
  23779. }
  23780. // Getting the the view matrix will also compute the world matrix.
  23781. this.getViewMatrix();
  23782. return this._worldMatrix;
  23783. };
  23784. /** @hidden */
  23785. Camera.prototype._getViewMatrix = function () {
  23786. return BABYLON.Matrix.Identity();
  23787. };
  23788. /**
  23789. * Gets the current view matrix of the camera.
  23790. * @param force forces the camera to recompute the matrix without looking at the cached state
  23791. * @returns the view matrix
  23792. */
  23793. Camera.prototype.getViewMatrix = function (force) {
  23794. if (!force && this._isSynchronizedViewMatrix()) {
  23795. return this._computedViewMatrix;
  23796. }
  23797. this.updateCache();
  23798. this._computedViewMatrix = this._getViewMatrix();
  23799. this._currentRenderId = this.getScene().getRenderId();
  23800. this._childRenderId = this._currentRenderId;
  23801. this._refreshFrustumPlanes = true;
  23802. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23803. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23804. }
  23805. this.onViewMatrixChangedObservable.notifyObservers(this);
  23806. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23807. return this._computedViewMatrix;
  23808. };
  23809. /**
  23810. * Freeze the projection matrix.
  23811. * It will prevent the cache check of the camera projection compute and can speed up perf
  23812. * if no parameter of the camera are meant to change
  23813. * @param projection Defines manually a projection if necessary
  23814. */
  23815. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23816. this._doNotComputeProjectionMatrix = true;
  23817. if (projection !== undefined) {
  23818. this._projectionMatrix = projection;
  23819. }
  23820. };
  23821. /**
  23822. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23823. */
  23824. Camera.prototype.unfreezeProjectionMatrix = function () {
  23825. this._doNotComputeProjectionMatrix = false;
  23826. };
  23827. /**
  23828. * Gets the current projection matrix of the camera.
  23829. * @param force forces the camera to recompute the matrix without looking at the cached state
  23830. * @returns the projection matrix
  23831. */
  23832. Camera.prototype.getProjectionMatrix = function (force) {
  23833. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23834. return this._projectionMatrix;
  23835. }
  23836. // Cache
  23837. this._cache.mode = this.mode;
  23838. this._cache.minZ = this.minZ;
  23839. this._cache.maxZ = this.maxZ;
  23840. // Matrix
  23841. this._refreshFrustumPlanes = true;
  23842. var engine = this.getEngine();
  23843. var scene = this.getScene();
  23844. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23845. this._cache.fov = this.fov;
  23846. this._cache.fovMode = this.fovMode;
  23847. this._cache.aspectRatio = engine.getAspectRatio(this);
  23848. if (this.minZ <= 0) {
  23849. this.minZ = 0.1;
  23850. }
  23851. if (scene.useRightHandedSystem) {
  23852. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23853. }
  23854. else {
  23855. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23856. }
  23857. }
  23858. else {
  23859. var halfWidth = engine.getRenderWidth() / 2.0;
  23860. var halfHeight = engine.getRenderHeight() / 2.0;
  23861. if (scene.useRightHandedSystem) {
  23862. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23863. }
  23864. else {
  23865. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23866. }
  23867. this._cache.orthoLeft = this.orthoLeft;
  23868. this._cache.orthoRight = this.orthoRight;
  23869. this._cache.orthoBottom = this.orthoBottom;
  23870. this._cache.orthoTop = this.orthoTop;
  23871. this._cache.renderWidth = engine.getRenderWidth();
  23872. this._cache.renderHeight = engine.getRenderHeight();
  23873. }
  23874. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23875. return this._projectionMatrix;
  23876. };
  23877. /**
  23878. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23879. * @returns a Matrix
  23880. */
  23881. Camera.prototype.getTransformationMatrix = function () {
  23882. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23883. return this._transformMatrix;
  23884. };
  23885. Camera.prototype._updateFrustumPlanes = function () {
  23886. if (!this._refreshFrustumPlanes) {
  23887. return;
  23888. }
  23889. this.getTransformationMatrix();
  23890. if (!this._frustumPlanes) {
  23891. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23892. }
  23893. else {
  23894. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23895. }
  23896. this._refreshFrustumPlanes = false;
  23897. };
  23898. /**
  23899. * Checks if a cullable object (mesh...) is in the camera frustum
  23900. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23901. * @param target The object to check
  23902. * @returns true if the object is in frustum otherwise false
  23903. */
  23904. Camera.prototype.isInFrustum = function (target) {
  23905. this._updateFrustumPlanes();
  23906. return target.isInFrustum(this._frustumPlanes);
  23907. };
  23908. /**
  23909. * Checks if a cullable object (mesh...) is in the camera frustum
  23910. * Unlike isInFrustum this cheks the full bounding box
  23911. * @param target The object to check
  23912. * @returns true if the object is in frustum otherwise false
  23913. */
  23914. Camera.prototype.isCompletelyInFrustum = function (target) {
  23915. this._updateFrustumPlanes();
  23916. return target.isCompletelyInFrustum(this._frustumPlanes);
  23917. };
  23918. /**
  23919. * Gets a ray in the forward direction from the camera.
  23920. * @param length Defines the length of the ray to create
  23921. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23922. * @param origin Defines the start point of the ray which defaults to the camera position
  23923. * @returns the forward ray
  23924. */
  23925. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23926. if (length === void 0) { length = 100; }
  23927. if (!transform) {
  23928. transform = this.getWorldMatrix();
  23929. }
  23930. if (!origin) {
  23931. origin = this.position;
  23932. }
  23933. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23934. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23935. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23936. return new BABYLON.Ray(origin, direction, length);
  23937. };
  23938. /**
  23939. * Releases resources associated with this node.
  23940. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23941. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23942. */
  23943. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23944. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23945. // Observables
  23946. this.onViewMatrixChangedObservable.clear();
  23947. this.onProjectionMatrixChangedObservable.clear();
  23948. this.onAfterCheckInputsObservable.clear();
  23949. this.onRestoreStateObservable.clear();
  23950. // Inputs
  23951. if (this.inputs) {
  23952. this.inputs.clear();
  23953. }
  23954. // Animations
  23955. this.getScene().stopAnimation(this);
  23956. // Remove from scene
  23957. this.getScene().removeCamera(this);
  23958. while (this._rigCameras.length > 0) {
  23959. var camera = this._rigCameras.pop();
  23960. if (camera) {
  23961. camera.dispose();
  23962. }
  23963. }
  23964. // Postprocesses
  23965. if (this._rigPostProcess) {
  23966. this._rigPostProcess.dispose(this);
  23967. this._rigPostProcess = null;
  23968. this._postProcesses = [];
  23969. }
  23970. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23971. this._rigPostProcess = null;
  23972. this._postProcesses = [];
  23973. }
  23974. else {
  23975. var i = this._postProcesses.length;
  23976. while (--i >= 0) {
  23977. var postProcess = this._postProcesses[i];
  23978. if (postProcess) {
  23979. postProcess.dispose(this);
  23980. }
  23981. }
  23982. }
  23983. // Render targets
  23984. var i = this.customRenderTargets.length;
  23985. while (--i >= 0) {
  23986. this.customRenderTargets[i].dispose();
  23987. }
  23988. this.customRenderTargets = [];
  23989. // Active Meshes
  23990. this._activeMeshes.dispose();
  23991. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23992. };
  23993. Object.defineProperty(Camera.prototype, "leftCamera", {
  23994. /**
  23995. * Gets the left camera of a rig setup in case of Rigged Camera
  23996. */
  23997. get: function () {
  23998. if (this._rigCameras.length < 1) {
  23999. return null;
  24000. }
  24001. return this._rigCameras[0];
  24002. },
  24003. enumerable: true,
  24004. configurable: true
  24005. });
  24006. Object.defineProperty(Camera.prototype, "rightCamera", {
  24007. /**
  24008. * Gets the right camera of a rig setup in case of Rigged Camera
  24009. */
  24010. get: function () {
  24011. if (this._rigCameras.length < 2) {
  24012. return null;
  24013. }
  24014. return this._rigCameras[1];
  24015. },
  24016. enumerable: true,
  24017. configurable: true
  24018. });
  24019. /**
  24020. * Gets the left camera target of a rig setup in case of Rigged Camera
  24021. * @returns the target position
  24022. */
  24023. Camera.prototype.getLeftTarget = function () {
  24024. if (this._rigCameras.length < 1) {
  24025. return null;
  24026. }
  24027. return this._rigCameras[0].getTarget();
  24028. };
  24029. /**
  24030. * Gets the right camera target of a rig setup in case of Rigged Camera
  24031. * @returns the target position
  24032. */
  24033. Camera.prototype.getRightTarget = function () {
  24034. if (this._rigCameras.length < 2) {
  24035. return null;
  24036. }
  24037. return this._rigCameras[1].getTarget();
  24038. };
  24039. /**
  24040. * @hidden
  24041. */
  24042. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  24043. if (this.cameraRigMode === mode) {
  24044. return;
  24045. }
  24046. while (this._rigCameras.length > 0) {
  24047. var camera = this._rigCameras.pop();
  24048. if (camera) {
  24049. camera.dispose();
  24050. }
  24051. }
  24052. this.cameraRigMode = mode;
  24053. this._cameraRigParams = {};
  24054. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  24055. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  24056. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  24057. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  24058. // create the rig cameras, unless none
  24059. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24060. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  24061. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  24062. if (leftCamera && rightCamera) {
  24063. this._rigCameras.push(leftCamera);
  24064. this._rigCameras.push(rightCamera);
  24065. }
  24066. }
  24067. switch (this.cameraRigMode) {
  24068. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  24069. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24070. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  24071. break;
  24072. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  24073. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  24074. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  24075. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  24076. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24077. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  24078. break;
  24079. case Camera.RIG_MODE_VR:
  24080. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  24081. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  24082. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24083. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24084. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  24085. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  24086. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  24087. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  24088. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24089. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24090. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  24091. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  24092. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  24093. if (metrics.compensateDistortion) {
  24094. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  24095. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  24096. }
  24097. break;
  24098. case Camera.RIG_MODE_WEBVR:
  24099. if (rigParams.vrDisplay) {
  24100. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  24101. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  24102. //Left eye
  24103. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24104. this._rigCameras[0].setCameraRigParameter("left", true);
  24105. //leaving this for future reference
  24106. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  24107. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  24108. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  24109. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24110. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24111. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24112. this._rigCameras[0].parent = this;
  24113. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  24114. //Right eye
  24115. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24116. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  24117. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  24118. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  24119. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24120. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24121. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24122. this._rigCameras[1].parent = this;
  24123. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  24124. if (Camera.UseAlternateWebVRRendering) {
  24125. this._rigCameras[1]._skipRendering = true;
  24126. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  24127. }
  24128. }
  24129. break;
  24130. }
  24131. this._cascadePostProcessesToRigCams();
  24132. this.update();
  24133. };
  24134. Camera.prototype._getVRProjectionMatrix = function () {
  24135. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  24136. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  24137. return this._projectionMatrix;
  24138. };
  24139. Camera.prototype._updateCameraRotationMatrix = function () {
  24140. //Here for WebVR
  24141. };
  24142. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24143. //Here for WebVR
  24144. };
  24145. /**
  24146. * This function MUST be overwritten by the different WebVR cameras available.
  24147. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24148. */
  24149. Camera.prototype._getWebVRProjectionMatrix = function () {
  24150. return BABYLON.Matrix.Identity();
  24151. };
  24152. /**
  24153. * This function MUST be overwritten by the different WebVR cameras available.
  24154. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24155. */
  24156. Camera.prototype._getWebVRViewMatrix = function () {
  24157. return BABYLON.Matrix.Identity();
  24158. };
  24159. /** @hidden */
  24160. Camera.prototype.setCameraRigParameter = function (name, value) {
  24161. if (!this._cameraRigParams) {
  24162. this._cameraRigParams = {};
  24163. }
  24164. this._cameraRigParams[name] = value;
  24165. //provisionnally:
  24166. if (name === "interaxialDistance") {
  24167. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24168. }
  24169. };
  24170. /**
  24171. * needs to be overridden by children so sub has required properties to be copied
  24172. * @hidden
  24173. */
  24174. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24175. return null;
  24176. };
  24177. /**
  24178. * May need to be overridden by children
  24179. * @hidden
  24180. */
  24181. Camera.prototype._updateRigCameras = function () {
  24182. for (var i = 0; i < this._rigCameras.length; i++) {
  24183. this._rigCameras[i].minZ = this.minZ;
  24184. this._rigCameras[i].maxZ = this.maxZ;
  24185. this._rigCameras[i].fov = this.fov;
  24186. }
  24187. // only update viewport when ANAGLYPH
  24188. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24189. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24190. }
  24191. };
  24192. /** @hidden */
  24193. Camera.prototype._setupInputs = function () {
  24194. };
  24195. /**
  24196. * Serialiaze the camera setup to a json represention
  24197. * @returns the JSON representation
  24198. */
  24199. Camera.prototype.serialize = function () {
  24200. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24201. // Type
  24202. serializationObject.type = this.getClassName();
  24203. // Parent
  24204. if (this.parent) {
  24205. serializationObject.parentId = this.parent.id;
  24206. }
  24207. if (this.inputs) {
  24208. this.inputs.serialize(serializationObject);
  24209. }
  24210. // Animations
  24211. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24212. serializationObject.ranges = this.serializeAnimationRanges();
  24213. return serializationObject;
  24214. };
  24215. /**
  24216. * Clones the current camera.
  24217. * @param name The cloned camera name
  24218. * @returns the cloned camera
  24219. */
  24220. Camera.prototype.clone = function (name) {
  24221. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24222. };
  24223. /**
  24224. * Gets the direction of the camera relative to a given local axis.
  24225. * @param localAxis Defines the reference axis to provide a relative direction.
  24226. * @return the direction
  24227. */
  24228. Camera.prototype.getDirection = function (localAxis) {
  24229. var result = BABYLON.Vector3.Zero();
  24230. this.getDirectionToRef(localAxis, result);
  24231. return result;
  24232. };
  24233. /**
  24234. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24235. * @param localAxis Defines the reference axis to provide a relative direction.
  24236. * @param result Defines the vector to store the result in
  24237. */
  24238. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24239. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24240. };
  24241. /**
  24242. * Gets a camera constructor for a given camera type
  24243. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24244. * @param name The name of the camera the result will be able to instantiate
  24245. * @param scene The scene the result will construct the camera in
  24246. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24247. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24248. * @returns a factory method to construc the camera
  24249. */
  24250. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24251. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24252. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24253. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24254. interaxial_distance: interaxial_distance,
  24255. isStereoscopicSideBySide: isStereoscopicSideBySide
  24256. });
  24257. if (constructorFunc) {
  24258. return constructorFunc;
  24259. }
  24260. // Default to universal camera
  24261. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24262. };
  24263. /**
  24264. * Compute the world matrix of the camera.
  24265. * @returns the camera workd matrix
  24266. */
  24267. Camera.prototype.computeWorldMatrix = function () {
  24268. return this.getWorldMatrix();
  24269. };
  24270. /**
  24271. * Parse a JSON and creates the camera from the parsed information
  24272. * @param parsedCamera The JSON to parse
  24273. * @param scene The scene to instantiate the camera in
  24274. * @returns the newly constructed camera
  24275. */
  24276. Camera.Parse = function (parsedCamera, scene) {
  24277. var type = parsedCamera.type;
  24278. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24279. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24280. // Parent
  24281. if (parsedCamera.parentId) {
  24282. camera._waitingParentId = parsedCamera.parentId;
  24283. }
  24284. //If camera has an input manager, let it parse inputs settings
  24285. if (camera.inputs) {
  24286. camera.inputs.parse(parsedCamera);
  24287. camera._setupInputs();
  24288. }
  24289. if (camera.setPosition) { // need to force position
  24290. camera.position.copyFromFloats(0, 0, 0);
  24291. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24292. }
  24293. // Target
  24294. if (parsedCamera.target) {
  24295. if (camera.setTarget) {
  24296. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24297. }
  24298. }
  24299. // Apply 3d rig, when found
  24300. if (parsedCamera.cameraRigMode) {
  24301. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24302. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24303. }
  24304. // Animations
  24305. if (parsedCamera.animations) {
  24306. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24307. var parsedAnimation = parsedCamera.animations[animationIndex];
  24308. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24309. }
  24310. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24311. }
  24312. if (parsedCamera.autoAnimate) {
  24313. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24314. }
  24315. return camera;
  24316. };
  24317. /**
  24318. * This is the default projection mode used by the cameras.
  24319. * It helps recreating a feeling of perspective and better appreciate depth.
  24320. * This is the best way to simulate real life cameras.
  24321. */
  24322. Camera.PERSPECTIVE_CAMERA = 0;
  24323. /**
  24324. * This helps creating camera with an orthographic mode.
  24325. * 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.
  24326. */
  24327. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24328. /**
  24329. * This is the default FOV mode for perspective cameras.
  24330. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24331. */
  24332. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24333. /**
  24334. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24335. */
  24336. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24337. /**
  24338. * This specifies ther is no need for a camera rig.
  24339. * Basically only one eye is rendered corresponding to the camera.
  24340. */
  24341. Camera.RIG_MODE_NONE = 0;
  24342. /**
  24343. * Simulates a camera Rig with one blue eye and one red eye.
  24344. * This can be use with 3d blue and red glasses.
  24345. */
  24346. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24347. /**
  24348. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24349. */
  24350. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24351. /**
  24352. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24353. */
  24354. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24355. /**
  24356. * Defines that both eyes of the camera will be rendered over under each other.
  24357. */
  24358. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24359. /**
  24360. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24361. */
  24362. Camera.RIG_MODE_VR = 20;
  24363. /**
  24364. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24365. */
  24366. Camera.RIG_MODE_WEBVR = 21;
  24367. /**
  24368. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  24369. */
  24370. Camera.RIG_MODE_CUSTOM = 22;
  24371. /**
  24372. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24373. */
  24374. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24375. /**
  24376. * @hidden
  24377. * Might be removed once multiview will be a thing
  24378. */
  24379. Camera.UseAlternateWebVRRendering = false;
  24380. __decorate([
  24381. BABYLON.serializeAsVector3()
  24382. ], Camera.prototype, "position", void 0);
  24383. __decorate([
  24384. BABYLON.serializeAsVector3()
  24385. ], Camera.prototype, "upVector", void 0);
  24386. __decorate([
  24387. BABYLON.serialize()
  24388. ], Camera.prototype, "orthoLeft", void 0);
  24389. __decorate([
  24390. BABYLON.serialize()
  24391. ], Camera.prototype, "orthoRight", void 0);
  24392. __decorate([
  24393. BABYLON.serialize()
  24394. ], Camera.prototype, "orthoBottom", void 0);
  24395. __decorate([
  24396. BABYLON.serialize()
  24397. ], Camera.prototype, "orthoTop", void 0);
  24398. __decorate([
  24399. BABYLON.serialize()
  24400. ], Camera.prototype, "fov", void 0);
  24401. __decorate([
  24402. BABYLON.serialize()
  24403. ], Camera.prototype, "minZ", void 0);
  24404. __decorate([
  24405. BABYLON.serialize()
  24406. ], Camera.prototype, "maxZ", void 0);
  24407. __decorate([
  24408. BABYLON.serialize()
  24409. ], Camera.prototype, "inertia", void 0);
  24410. __decorate([
  24411. BABYLON.serialize()
  24412. ], Camera.prototype, "mode", void 0);
  24413. __decorate([
  24414. BABYLON.serialize()
  24415. ], Camera.prototype, "layerMask", void 0);
  24416. __decorate([
  24417. BABYLON.serialize()
  24418. ], Camera.prototype, "fovMode", void 0);
  24419. __decorate([
  24420. BABYLON.serialize()
  24421. ], Camera.prototype, "cameraRigMode", void 0);
  24422. __decorate([
  24423. BABYLON.serialize()
  24424. ], Camera.prototype, "interaxialDistance", void 0);
  24425. __decorate([
  24426. BABYLON.serialize()
  24427. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24428. return Camera;
  24429. }(BABYLON.Node));
  24430. BABYLON.Camera = Camera;
  24431. })(BABYLON || (BABYLON = {}));
  24432. //# sourceMappingURL=babylon.camera.js.map
  24433. var BABYLON;
  24434. (function (BABYLON) {
  24435. /**
  24436. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24437. * It is enable to manage the different groups as well as the different necessary sort functions.
  24438. * This should not be used directly aside of the few static configurations
  24439. */
  24440. var RenderingManager = /** @class */ (function () {
  24441. /**
  24442. * Instantiates a new rendering group for a particular scene
  24443. * @param scene Defines the scene the groups belongs to
  24444. */
  24445. function RenderingManager(scene) {
  24446. /**
  24447. * @hidden
  24448. */
  24449. this._useSceneAutoClearSetup = false;
  24450. this._renderingGroups = new Array();
  24451. this._autoClearDepthStencil = {};
  24452. this._customOpaqueSortCompareFn = {};
  24453. this._customAlphaTestSortCompareFn = {};
  24454. this._customTransparentSortCompareFn = {};
  24455. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24456. this._scene = scene;
  24457. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24458. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24459. }
  24460. }
  24461. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24462. if (depth === void 0) { depth = true; }
  24463. if (stencil === void 0) { stencil = true; }
  24464. if (this._depthStencilBufferAlreadyCleaned) {
  24465. return;
  24466. }
  24467. this._scene.getEngine().clear(null, false, depth, stencil);
  24468. this._depthStencilBufferAlreadyCleaned = true;
  24469. };
  24470. /**
  24471. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24472. * @hidden
  24473. */
  24474. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24475. // Update the observable context (not null as it only goes away on dispose)
  24476. var info = this._renderingGroupInfo;
  24477. info.scene = this._scene;
  24478. info.camera = this._scene.activeCamera;
  24479. // Dispatch sprites
  24480. if (this._scene.spriteManagers && renderSprites) {
  24481. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24482. var manager = this._scene.spriteManagers[index];
  24483. this.dispatchSprites(manager);
  24484. }
  24485. }
  24486. // Render
  24487. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24488. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24489. var renderingGroup = this._renderingGroups[index];
  24490. if (!renderingGroup) {
  24491. continue;
  24492. }
  24493. var renderingGroupMask = Math.pow(2, index);
  24494. info.renderingGroupId = index;
  24495. // Before Observable
  24496. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24497. // Clear depth/stencil if needed
  24498. if (RenderingManager.AUTOCLEAR) {
  24499. var autoClear = this._useSceneAutoClearSetup ?
  24500. this._scene.getAutoClearDepthStencilSetup(index) :
  24501. this._autoClearDepthStencil[index];
  24502. if (autoClear && autoClear.autoClear) {
  24503. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24504. }
  24505. }
  24506. // Render
  24507. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24508. var step = _a[_i];
  24509. step.action(index);
  24510. }
  24511. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24512. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24513. var step = _c[_b];
  24514. step.action(index);
  24515. }
  24516. // After Observable
  24517. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24518. }
  24519. };
  24520. /**
  24521. * Resets the different information of the group to prepare a new frame
  24522. * @hidden
  24523. */
  24524. RenderingManager.prototype.reset = function () {
  24525. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24526. var renderingGroup = this._renderingGroups[index];
  24527. if (renderingGroup) {
  24528. renderingGroup.prepare();
  24529. }
  24530. }
  24531. };
  24532. /**
  24533. * Dispose and release the group and its associated resources.
  24534. * @hidden
  24535. */
  24536. RenderingManager.prototype.dispose = function () {
  24537. this.freeRenderingGroups();
  24538. this._renderingGroups.length = 0;
  24539. this._renderingGroupInfo = null;
  24540. };
  24541. /**
  24542. * Clear the info related to rendering groups preventing retention points during dispose.
  24543. */
  24544. RenderingManager.prototype.freeRenderingGroups = function () {
  24545. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24546. var renderingGroup = this._renderingGroups[index];
  24547. if (renderingGroup) {
  24548. renderingGroup.dispose();
  24549. }
  24550. }
  24551. };
  24552. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24553. if (this._renderingGroups[renderingGroupId] === undefined) {
  24554. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24555. }
  24556. };
  24557. /**
  24558. * Add a sprite manager to the rendering manager in order to render it this frame.
  24559. * @param spriteManager Define the sprite manager to render
  24560. */
  24561. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24562. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24563. this._prepareRenderingGroup(renderingGroupId);
  24564. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24565. };
  24566. /**
  24567. * Add a particle system to the rendering manager in order to render it this frame.
  24568. * @param particleSystem Define the particle system to render
  24569. */
  24570. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24571. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24572. this._prepareRenderingGroup(renderingGroupId);
  24573. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24574. };
  24575. /**
  24576. * Add a submesh to the manager in order to render it this frame
  24577. * @param subMesh The submesh to dispatch
  24578. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24579. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24580. */
  24581. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24582. if (mesh === undefined) {
  24583. mesh = subMesh.getMesh();
  24584. }
  24585. var renderingGroupId = mesh.renderingGroupId || 0;
  24586. this._prepareRenderingGroup(renderingGroupId);
  24587. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24588. };
  24589. /**
  24590. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24591. * This allowed control for front to back rendering or reversly depending of the special needs.
  24592. *
  24593. * @param renderingGroupId The rendering group id corresponding to its index
  24594. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24595. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24596. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24597. */
  24598. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24599. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24600. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24601. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24602. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24603. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24604. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24605. if (this._renderingGroups[renderingGroupId]) {
  24606. var group = this._renderingGroups[renderingGroupId];
  24607. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24608. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24609. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24610. }
  24611. };
  24612. /**
  24613. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24614. *
  24615. * @param renderingGroupId The rendering group id corresponding to its index
  24616. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24617. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24618. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24619. */
  24620. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24621. if (depth === void 0) { depth = true; }
  24622. if (stencil === void 0) { stencil = true; }
  24623. this._autoClearDepthStencil[renderingGroupId] = {
  24624. autoClear: autoClearDepthStencil,
  24625. depth: depth,
  24626. stencil: stencil
  24627. };
  24628. };
  24629. /**
  24630. * Gets the current auto clear configuration for one rendering group of the rendering
  24631. * manager.
  24632. * @param index the rendering group index to get the information for
  24633. * @returns The auto clear setup for the requested rendering group
  24634. */
  24635. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24636. return this._autoClearDepthStencil[index];
  24637. };
  24638. /**
  24639. * The max id used for rendering groups (not included)
  24640. */
  24641. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24642. /**
  24643. * The min id used for rendering groups (included)
  24644. */
  24645. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24646. /**
  24647. * Used to globally prevent autoclearing scenes.
  24648. */
  24649. RenderingManager.AUTOCLEAR = true;
  24650. return RenderingManager;
  24651. }());
  24652. BABYLON.RenderingManager = RenderingManager;
  24653. })(BABYLON || (BABYLON = {}));
  24654. //# sourceMappingURL=babylon.renderingManager.js.map
  24655. var BABYLON;
  24656. (function (BABYLON) {
  24657. /**
  24658. * This represents the object necessary to create a rendering group.
  24659. * This is exclusively used and created by the rendering manager.
  24660. * To modify the behavior, you use the available helpers in your scene or meshes.
  24661. * @hidden
  24662. */
  24663. var RenderingGroup = /** @class */ (function () {
  24664. /**
  24665. * Creates a new rendering group.
  24666. * @param index The rendering group index
  24667. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24668. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24669. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24670. */
  24671. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24672. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24673. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24674. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24675. this.index = index;
  24676. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24677. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24678. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24679. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24680. this._particleSystems = new BABYLON.SmartArray(256);
  24681. this._spriteManagers = new BABYLON.SmartArray(256);
  24682. this._edgesRenderers = new BABYLON.SmartArray(16);
  24683. this._scene = scene;
  24684. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24685. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24686. this.transparentSortCompareFn = transparentSortCompareFn;
  24687. }
  24688. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24689. /**
  24690. * Set the opaque sort comparison function.
  24691. * If null the sub meshes will be render in the order they were created
  24692. */
  24693. set: function (value) {
  24694. this._opaqueSortCompareFn = value;
  24695. if (value) {
  24696. this._renderOpaque = this.renderOpaqueSorted;
  24697. }
  24698. else {
  24699. this._renderOpaque = RenderingGroup.renderUnsorted;
  24700. }
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24706. /**
  24707. * Set the alpha test sort comparison function.
  24708. * If null the sub meshes will be render in the order they were created
  24709. */
  24710. set: function (value) {
  24711. this._alphaTestSortCompareFn = value;
  24712. if (value) {
  24713. this._renderAlphaTest = this.renderAlphaTestSorted;
  24714. }
  24715. else {
  24716. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24717. }
  24718. },
  24719. enumerable: true,
  24720. configurable: true
  24721. });
  24722. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24723. /**
  24724. * Set the transparent sort comparison function.
  24725. * If null the sub meshes will be render in the order they were created
  24726. */
  24727. set: function (value) {
  24728. if (value) {
  24729. this._transparentSortCompareFn = value;
  24730. }
  24731. else {
  24732. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24733. }
  24734. this._renderTransparent = this.renderTransparentSorted;
  24735. },
  24736. enumerable: true,
  24737. configurable: true
  24738. });
  24739. /**
  24740. * Render all the sub meshes contained in the group.
  24741. * @param customRenderFunction Used to override the default render behaviour of the group.
  24742. * @returns true if rendered some submeshes.
  24743. */
  24744. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24745. if (customRenderFunction) {
  24746. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24747. return;
  24748. }
  24749. var engine = this._scene.getEngine();
  24750. // Depth only
  24751. if (this._depthOnlySubMeshes.length !== 0) {
  24752. engine.setColorWrite(false);
  24753. this._renderAlphaTest(this._depthOnlySubMeshes);
  24754. engine.setColorWrite(true);
  24755. }
  24756. // Opaque
  24757. if (this._opaqueSubMeshes.length !== 0) {
  24758. this._renderOpaque(this._opaqueSubMeshes);
  24759. }
  24760. // Alpha test
  24761. if (this._alphaTestSubMeshes.length !== 0) {
  24762. this._renderAlphaTest(this._alphaTestSubMeshes);
  24763. }
  24764. var stencilState = engine.getStencilBuffer();
  24765. engine.setStencilBuffer(false);
  24766. // Sprites
  24767. if (renderSprites) {
  24768. this._renderSprites();
  24769. }
  24770. // Particles
  24771. if (renderParticles) {
  24772. this._renderParticles(activeMeshes);
  24773. }
  24774. if (this.onBeforeTransparentRendering) {
  24775. this.onBeforeTransparentRendering();
  24776. }
  24777. // Transparent
  24778. if (this._transparentSubMeshes.length !== 0) {
  24779. this._renderTransparent(this._transparentSubMeshes);
  24780. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24781. }
  24782. // Set back stencil to false in case it changes before the edge renderer.
  24783. engine.setStencilBuffer(false);
  24784. // Edges
  24785. if (this._edgesRenderers.length) {
  24786. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24787. this._edgesRenderers.data[edgesRendererIndex].render();
  24788. }
  24789. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24790. }
  24791. // Restore Stencil state.
  24792. engine.setStencilBuffer(stencilState);
  24793. };
  24794. /**
  24795. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24796. * @param subMeshes The submeshes to render
  24797. */
  24798. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24799. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24800. };
  24801. /**
  24802. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24803. * @param subMeshes The submeshes to render
  24804. */
  24805. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24806. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24807. };
  24808. /**
  24809. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24810. * @param subMeshes The submeshes to render
  24811. */
  24812. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24813. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24814. };
  24815. /**
  24816. * Renders the submeshes in a specified order.
  24817. * @param subMeshes The submeshes to sort before render
  24818. * @param sortCompareFn The comparison function use to sort
  24819. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24820. * @param transparent Specifies to activate blending if true
  24821. */
  24822. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24823. var subIndex = 0;
  24824. var subMesh;
  24825. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24826. for (; subIndex < subMeshes.length; subIndex++) {
  24827. subMesh = subMeshes.data[subIndex];
  24828. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24829. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24830. }
  24831. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24832. if (sortCompareFn) {
  24833. sortedArray.sort(sortCompareFn);
  24834. }
  24835. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24836. subMesh = sortedArray[subIndex];
  24837. if (transparent) {
  24838. var material = subMesh.getMaterial();
  24839. if (material && material.needDepthPrePass) {
  24840. var engine = material.getScene().getEngine();
  24841. engine.setColorWrite(false);
  24842. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24843. subMesh.render(false);
  24844. engine.setColorWrite(true);
  24845. }
  24846. }
  24847. subMesh.render(transparent);
  24848. }
  24849. };
  24850. /**
  24851. * Renders the submeshes in the order they were dispatched (no sort applied).
  24852. * @param subMeshes The submeshes to render
  24853. */
  24854. RenderingGroup.renderUnsorted = function (subMeshes) {
  24855. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24856. var submesh = subMeshes.data[subIndex];
  24857. submesh.render(false);
  24858. }
  24859. };
  24860. /**
  24861. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24862. * are rendered back to front if in the same alpha index.
  24863. *
  24864. * @param a The first submesh
  24865. * @param b The second submesh
  24866. * @returns The result of the comparison
  24867. */
  24868. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24869. // Alpha index first
  24870. if (a._alphaIndex > b._alphaIndex) {
  24871. return 1;
  24872. }
  24873. if (a._alphaIndex < b._alphaIndex) {
  24874. return -1;
  24875. }
  24876. // Then distance to camera
  24877. return RenderingGroup.backToFrontSortCompare(a, b);
  24878. };
  24879. /**
  24880. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24881. * are rendered back to front.
  24882. *
  24883. * @param a The first submesh
  24884. * @param b The second submesh
  24885. * @returns The result of the comparison
  24886. */
  24887. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24888. // Then distance to camera
  24889. if (a._distanceToCamera < b._distanceToCamera) {
  24890. return 1;
  24891. }
  24892. if (a._distanceToCamera > b._distanceToCamera) {
  24893. return -1;
  24894. }
  24895. return 0;
  24896. };
  24897. /**
  24898. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24899. * are rendered front to back (prevent overdraw).
  24900. *
  24901. * @param a The first submesh
  24902. * @param b The second submesh
  24903. * @returns The result of the comparison
  24904. */
  24905. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24906. // Then distance to camera
  24907. if (a._distanceToCamera < b._distanceToCamera) {
  24908. return -1;
  24909. }
  24910. if (a._distanceToCamera > b._distanceToCamera) {
  24911. return 1;
  24912. }
  24913. return 0;
  24914. };
  24915. /**
  24916. * Resets the different lists of submeshes to prepare a new frame.
  24917. */
  24918. RenderingGroup.prototype.prepare = function () {
  24919. this._opaqueSubMeshes.reset();
  24920. this._transparentSubMeshes.reset();
  24921. this._alphaTestSubMeshes.reset();
  24922. this._depthOnlySubMeshes.reset();
  24923. this._particleSystems.reset();
  24924. this._spriteManagers.reset();
  24925. this._edgesRenderers.reset();
  24926. };
  24927. RenderingGroup.prototype.dispose = function () {
  24928. this._opaqueSubMeshes.dispose();
  24929. this._transparentSubMeshes.dispose();
  24930. this._alphaTestSubMeshes.dispose();
  24931. this._depthOnlySubMeshes.dispose();
  24932. this._particleSystems.dispose();
  24933. this._spriteManagers.dispose();
  24934. this._edgesRenderers.dispose();
  24935. };
  24936. /**
  24937. * Inserts the submesh in its correct queue depending on its material.
  24938. * @param subMesh The submesh to dispatch
  24939. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24940. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24941. */
  24942. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24943. // Get mesh and materials if not provided
  24944. if (mesh === undefined) {
  24945. mesh = subMesh.getMesh();
  24946. }
  24947. if (material === undefined) {
  24948. material = subMesh.getMaterial();
  24949. }
  24950. if (material === null || material === undefined) {
  24951. return;
  24952. }
  24953. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24954. this._transparentSubMeshes.push(subMesh);
  24955. }
  24956. else if (material.needAlphaTesting()) { // Alpha test
  24957. if (material.needDepthPrePass) {
  24958. this._depthOnlySubMeshes.push(subMesh);
  24959. }
  24960. this._alphaTestSubMeshes.push(subMesh);
  24961. }
  24962. else {
  24963. if (material.needDepthPrePass) {
  24964. this._depthOnlySubMeshes.push(subMesh);
  24965. }
  24966. this._opaqueSubMeshes.push(subMesh); // Opaque
  24967. }
  24968. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24969. this._edgesRenderers.push(mesh._edgesRenderer);
  24970. }
  24971. };
  24972. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24973. this._spriteManagers.push(spriteManager);
  24974. };
  24975. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24976. this._particleSystems.push(particleSystem);
  24977. };
  24978. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24979. if (this._particleSystems.length === 0) {
  24980. return;
  24981. }
  24982. // Particles
  24983. var activeCamera = this._scene.activeCamera;
  24984. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24985. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24986. var particleSystem = this._particleSystems.data[particleIndex];
  24987. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24988. continue;
  24989. }
  24990. var emitter = particleSystem.emitter;
  24991. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24992. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24993. }
  24994. }
  24995. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24996. };
  24997. RenderingGroup.prototype._renderSprites = function () {
  24998. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24999. return;
  25000. }
  25001. // Sprites
  25002. var activeCamera = this._scene.activeCamera;
  25003. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  25004. for (var id = 0; id < this._spriteManagers.length; id++) {
  25005. var spriteManager = this._spriteManagers.data[id];
  25006. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  25007. spriteManager.render();
  25008. }
  25009. }
  25010. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  25011. };
  25012. return RenderingGroup;
  25013. }());
  25014. BABYLON.RenderingGroup = RenderingGroup;
  25015. })(BABYLON || (BABYLON = {}));
  25016. //# sourceMappingURL=babylon.renderingGroup.js.map
  25017. var BABYLON;
  25018. (function (BABYLON) {
  25019. /**
  25020. * Groups all the scene component constants in one place to ease maintenance.
  25021. * @hidden
  25022. */
  25023. var SceneComponentConstants = /** @class */ (function () {
  25024. function SceneComponentConstants() {
  25025. }
  25026. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  25027. SceneComponentConstants.NAME_LAYER = "Layer";
  25028. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  25029. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  25030. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  25031. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  25032. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  25033. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  25034. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  25035. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  25036. SceneComponentConstants.NAME_SPRITE = "Sprite";
  25037. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  25038. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  25039. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  25040. SceneComponentConstants.NAME_OCTREE = "Octree";
  25041. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  25042. SceneComponentConstants.NAME_AUDIO = "Audio";
  25043. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  25044. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25045. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  25046. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25047. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  25048. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  25049. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  25050. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  25051. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  25052. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  25053. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  25054. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  25055. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  25056. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  25057. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  25058. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  25059. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  25060. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  25061. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  25062. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  25063. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  25064. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  25065. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  25066. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  25067. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  25068. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  25069. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  25070. return SceneComponentConstants;
  25071. }());
  25072. BABYLON.SceneComponentConstants = SceneComponentConstants;
  25073. /**
  25074. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  25075. * @hidden
  25076. */
  25077. var Stage = /** @class */ (function (_super) {
  25078. __extends(Stage, _super);
  25079. /**
  25080. * Hide ctor from the rest of the world.
  25081. * @param items The items to add.
  25082. */
  25083. function Stage(items) {
  25084. return _super.apply(this, items) || this;
  25085. }
  25086. /**
  25087. * Creates a new Stage.
  25088. * @returns A new instance of a Stage
  25089. */
  25090. Stage.Create = function () {
  25091. return Object.create(Stage.prototype);
  25092. };
  25093. /**
  25094. * Registers a step in an ordered way in the targeted stage.
  25095. * @param index Defines the position to register the step in
  25096. * @param component Defines the component attached to the step
  25097. * @param action Defines the action to launch during the step
  25098. */
  25099. Stage.prototype.registerStep = function (index, component, action) {
  25100. var i = 0;
  25101. var maxIndex = Number.MAX_VALUE;
  25102. for (; i < this.length; i++) {
  25103. var step = this[i];
  25104. maxIndex = step.index;
  25105. if (index < maxIndex) {
  25106. break;
  25107. }
  25108. }
  25109. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  25110. };
  25111. /**
  25112. * Clears all the steps from the stage.
  25113. */
  25114. Stage.prototype.clear = function () {
  25115. this.length = 0;
  25116. };
  25117. return Stage;
  25118. }(Array));
  25119. BABYLON.Stage = Stage;
  25120. })(BABYLON || (BABYLON = {}));
  25121. //# sourceMappingURL=babylon.sceneComponent.js.map
  25122. var BABYLON;
  25123. (function (BABYLON) {
  25124. /**
  25125. * Base class of the scene acting as a container for the different elements composing a scene.
  25126. * This class is dynamically extended by the different components of the scene increasing
  25127. * flexibility and reducing coupling
  25128. */
  25129. var AbstractScene = /** @class */ (function () {
  25130. function AbstractScene() {
  25131. /**
  25132. * Gets the list of root nodes (ie. nodes with no parent)
  25133. */
  25134. this.rootNodes = new Array();
  25135. /** All of the cameras added to this scene
  25136. * @see http://doc.babylonjs.com/babylon101/cameras
  25137. */
  25138. this.cameras = new Array();
  25139. /**
  25140. * All of the lights added to this scene
  25141. * @see http://doc.babylonjs.com/babylon101/lights
  25142. */
  25143. this.lights = new Array();
  25144. /**
  25145. * All of the (abstract) meshes added to this scene
  25146. */
  25147. this.meshes = new Array();
  25148. /**
  25149. * The list of skeletons added to the scene
  25150. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25151. */
  25152. this.skeletons = new Array();
  25153. /**
  25154. * All of the particle systems added to this scene
  25155. * @see http://doc.babylonjs.com/babylon101/particles
  25156. */
  25157. this.particleSystems = new Array();
  25158. /**
  25159. * Gets a list of Animations associated with the scene
  25160. */
  25161. this.animations = [];
  25162. /**
  25163. * All of the animation groups added to this scene
  25164. * @see http://doc.babylonjs.com/how_to/group
  25165. */
  25166. this.animationGroups = new Array();
  25167. /**
  25168. * All of the multi-materials added to this scene
  25169. * @see http://doc.babylonjs.com/how_to/multi_materials
  25170. */
  25171. this.multiMaterials = new Array();
  25172. /**
  25173. * All of the materials added to this scene
  25174. * In the context of a Scene, it is not supposed to be modified manually.
  25175. * Any addition or removal should be done using the addMaterial and removeMAterial Scene methods.
  25176. * Note also that the order of the Material wihin the array is not significant and might change.
  25177. * @see http://doc.babylonjs.com/babylon101/materials
  25178. */
  25179. this.materials = new Array();
  25180. /**
  25181. * The list of morph target managers added to the scene
  25182. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25183. */
  25184. this.morphTargetManagers = new Array();
  25185. /**
  25186. * The list of geometries used in the scene.
  25187. */
  25188. this.geometries = new Array();
  25189. /**
  25190. * All of the tranform nodes added to this scene
  25191. * In the context of a Scene, it is not supposed to be modified manually.
  25192. * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
  25193. * Note also that the order of the TransformNode wihin the array is not significant and might change.
  25194. * @see http://doc.babylonjs.com/how_to/transformnode
  25195. */
  25196. this.transformNodes = new Array();
  25197. /**
  25198. * ActionManagers available on the scene.
  25199. */
  25200. this.actionManagers = new Array();
  25201. /**
  25202. * Textures to keep.
  25203. */
  25204. this.textures = new Array();
  25205. }
  25206. /**
  25207. * Adds a parser in the list of available ones
  25208. * @param name Defines the name of the parser
  25209. * @param parser Defines the parser to add
  25210. */
  25211. AbstractScene.AddParser = function (name, parser) {
  25212. this._BabylonFileParsers[name] = parser;
  25213. };
  25214. /**
  25215. * Gets a general parser from the list of avaialble ones
  25216. * @param name Defines the name of the parser
  25217. * @returns the requested parser or null
  25218. */
  25219. AbstractScene.GetParser = function (name) {
  25220. if (this._BabylonFileParsers[name]) {
  25221. return this._BabylonFileParsers[name];
  25222. }
  25223. return null;
  25224. };
  25225. /**
  25226. * Adds n individual parser in the list of available ones
  25227. * @param name Defines the name of the parser
  25228. * @param parser Defines the parser to add
  25229. */
  25230. AbstractScene.AddIndividualParser = function (name, parser) {
  25231. this._IndividualBabylonFileParsers[name] = parser;
  25232. };
  25233. /**
  25234. * Gets an individual parser from the list of avaialble ones
  25235. * @param name Defines the name of the parser
  25236. * @returns the requested parser or null
  25237. */
  25238. AbstractScene.GetIndividualParser = function (name) {
  25239. if (this._IndividualBabylonFileParsers[name]) {
  25240. return this._IndividualBabylonFileParsers[name];
  25241. }
  25242. return null;
  25243. };
  25244. /**
  25245. * Parser json data and populate both a scene and its associated container object
  25246. * @param jsonData Defines the data to parse
  25247. * @param scene Defines the scene to parse the data for
  25248. * @param container Defines the container attached to the parsing sequence
  25249. * @param rootUrl Defines the root url of the data
  25250. */
  25251. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25252. for (var parserName in this._BabylonFileParsers) {
  25253. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25254. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25255. }
  25256. }
  25257. };
  25258. /**
  25259. * Stores the list of available parsers in the application.
  25260. */
  25261. AbstractScene._BabylonFileParsers = {};
  25262. /**
  25263. * Stores the list of available individual parsers in the application.
  25264. */
  25265. AbstractScene._IndividualBabylonFileParsers = {};
  25266. return AbstractScene;
  25267. }());
  25268. BABYLON.AbstractScene = AbstractScene;
  25269. })(BABYLON || (BABYLON = {}));
  25270. //# sourceMappingURL=babylon.abstractScene.js.map
  25271. var BABYLON;
  25272. (function (BABYLON) {
  25273. /** @hidden */
  25274. var ClickInfo = /** @class */ (function () {
  25275. function ClickInfo() {
  25276. this._singleClick = false;
  25277. this._doubleClick = false;
  25278. this._hasSwiped = false;
  25279. this._ignore = false;
  25280. }
  25281. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25282. get: function () {
  25283. return this._singleClick;
  25284. },
  25285. set: function (b) {
  25286. this._singleClick = b;
  25287. },
  25288. enumerable: true,
  25289. configurable: true
  25290. });
  25291. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25292. get: function () {
  25293. return this._doubleClick;
  25294. },
  25295. set: function (b) {
  25296. this._doubleClick = b;
  25297. },
  25298. enumerable: true,
  25299. configurable: true
  25300. });
  25301. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25302. get: function () {
  25303. return this._hasSwiped;
  25304. },
  25305. set: function (b) {
  25306. this._hasSwiped = b;
  25307. },
  25308. enumerable: true,
  25309. configurable: true
  25310. });
  25311. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25312. get: function () {
  25313. return this._ignore;
  25314. },
  25315. set: function (b) {
  25316. this._ignore = b;
  25317. },
  25318. enumerable: true,
  25319. configurable: true
  25320. });
  25321. return ClickInfo;
  25322. }());
  25323. /**
  25324. * This class is used by the onRenderingGroupObservable
  25325. */
  25326. var RenderingGroupInfo = /** @class */ (function () {
  25327. function RenderingGroupInfo() {
  25328. }
  25329. return RenderingGroupInfo;
  25330. }());
  25331. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25332. /**
  25333. * Represents a scene to be rendered by the engine.
  25334. * @see http://doc.babylonjs.com/features/scene
  25335. */
  25336. var Scene = /** @class */ (function (_super) {
  25337. __extends(Scene, _super);
  25338. /**
  25339. * Creates a new Scene
  25340. * @param engine defines the engine to use to render this scene
  25341. */
  25342. function Scene(engine, options) {
  25343. var _this = _super.call(this) || this;
  25344. // Members
  25345. /**
  25346. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25347. */
  25348. _this.autoClear = true;
  25349. /**
  25350. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25351. */
  25352. _this.autoClearDepthAndStencil = true;
  25353. /**
  25354. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25355. */
  25356. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25357. /**
  25358. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25359. */
  25360. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25361. _this._forceWireframe = false;
  25362. _this._forcePointsCloud = false;
  25363. /**
  25364. * Gets or sets a boolean indicating if animations are enabled
  25365. */
  25366. _this.animationsEnabled = true;
  25367. _this._animationPropertiesOverride = null;
  25368. /**
  25369. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25370. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25371. */
  25372. _this.useConstantAnimationDeltaTime = false;
  25373. /**
  25374. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25375. * Please note that it requires to run a ray cast through the scene on every frame
  25376. */
  25377. _this.constantlyUpdateMeshUnderPointer = false;
  25378. /**
  25379. * Defines the HTML cursor to use when hovering over interactive elements
  25380. */
  25381. _this.hoverCursor = "pointer";
  25382. /**
  25383. * Defines the HTML default cursor to use (empty by default)
  25384. */
  25385. _this.defaultCursor = "";
  25386. /**
  25387. * This is used to call preventDefault() on pointer down
  25388. * in order to block unwanted artifacts like system double clicks
  25389. */
  25390. _this.preventDefaultOnPointerDown = true;
  25391. /**
  25392. * This is used to call preventDefault() on pointer up
  25393. * in order to block unwanted artifacts like system double clicks
  25394. */
  25395. _this.preventDefaultOnPointerUp = true;
  25396. // Metadata
  25397. /**
  25398. * Gets or sets user defined metadata
  25399. */
  25400. _this.metadata = null;
  25401. /**
  25402. * Use this array to add regular expressions used to disable offline support for specific urls
  25403. */
  25404. _this.disableOfflineSupportExceptionRules = new Array();
  25405. /**
  25406. * An event triggered when the scene is disposed.
  25407. */
  25408. _this.onDisposeObservable = new BABYLON.Observable();
  25409. _this._onDisposeObserver = null;
  25410. /**
  25411. * An event triggered before rendering the scene (right after animations and physics)
  25412. */
  25413. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25414. _this._onBeforeRenderObserver = null;
  25415. /**
  25416. * An event triggered after rendering the scene
  25417. */
  25418. _this.onAfterRenderObservable = new BABYLON.Observable();
  25419. _this._onAfterRenderObserver = null;
  25420. /**
  25421. * An event triggered before animating the scene
  25422. */
  25423. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25424. /**
  25425. * An event triggered after animations processing
  25426. */
  25427. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25428. /**
  25429. * An event triggered before draw calls are ready to be sent
  25430. */
  25431. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25432. /**
  25433. * An event triggered after draw calls have been sent
  25434. */
  25435. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25436. /**
  25437. * An event triggered when the scene is ready
  25438. */
  25439. _this.onReadyObservable = new BABYLON.Observable();
  25440. /**
  25441. * An event triggered before rendering a camera
  25442. */
  25443. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25444. _this._onBeforeCameraRenderObserver = null;
  25445. /**
  25446. * An event triggered after rendering a camera
  25447. */
  25448. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25449. _this._onAfterCameraRenderObserver = null;
  25450. /**
  25451. * An event triggered when active meshes evaluation is about to start
  25452. */
  25453. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25454. /**
  25455. * An event triggered when active meshes evaluation is done
  25456. */
  25457. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25458. /**
  25459. * An event triggered when particles rendering is about to start
  25460. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25461. */
  25462. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25463. /**
  25464. * An event triggered when particles rendering is done
  25465. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25466. */
  25467. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25468. /**
  25469. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25470. */
  25471. _this.onDataLoadedObservable = new BABYLON.Observable();
  25472. /**
  25473. * An event triggered when a camera is created
  25474. */
  25475. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25476. /**
  25477. * An event triggered when a camera is removed
  25478. */
  25479. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25480. /**
  25481. * An event triggered when a light is created
  25482. */
  25483. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25484. /**
  25485. * An event triggered when a light is removed
  25486. */
  25487. _this.onLightRemovedObservable = new BABYLON.Observable();
  25488. /**
  25489. * An event triggered when a geometry is created
  25490. */
  25491. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25492. /**
  25493. * An event triggered when a geometry is removed
  25494. */
  25495. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25496. /**
  25497. * An event triggered when a transform node is created
  25498. */
  25499. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25500. /**
  25501. * An event triggered when a transform node is removed
  25502. */
  25503. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25504. /**
  25505. * An event triggered when a mesh is created
  25506. */
  25507. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25508. /**
  25509. * An event triggered when a mesh is removed
  25510. */
  25511. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25512. /**
  25513. * An event triggered when a material is created
  25514. */
  25515. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25516. /**
  25517. * An event triggered when a material is removed
  25518. */
  25519. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25520. /**
  25521. * An event triggered when a texture is created
  25522. */
  25523. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25524. /**
  25525. * An event triggered when a texture is removed
  25526. */
  25527. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25528. /**
  25529. * An event triggered when render targets are about to be rendered
  25530. * Can happen multiple times per frame.
  25531. */
  25532. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25533. /**
  25534. * An event triggered when render targets were rendered.
  25535. * Can happen multiple times per frame.
  25536. */
  25537. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25538. /**
  25539. * An event triggered before calculating deterministic simulation step
  25540. */
  25541. _this.onBeforeStepObservable = new BABYLON.Observable();
  25542. /**
  25543. * An event triggered after calculating deterministic simulation step
  25544. */
  25545. _this.onAfterStepObservable = new BABYLON.Observable();
  25546. /**
  25547. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25548. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25549. * 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)
  25550. */
  25551. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25552. /**
  25553. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25554. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25555. * 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)
  25556. */
  25557. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25558. /**
  25559. * This Observable will when a mesh has been imported into the scene.
  25560. */
  25561. _this.onMeshImportedObservable = new BABYLON.Observable();
  25562. // Animations
  25563. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25564. /**
  25565. * 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).
  25566. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25567. */
  25568. _this.onPrePointerObservable = new BABYLON.Observable();
  25569. /**
  25570. * Observable event triggered each time an input event is received from the rendering canvas
  25571. */
  25572. _this.onPointerObservable = new BABYLON.Observable();
  25573. _this._meshPickProceed = false;
  25574. _this._currentPickResult = null;
  25575. _this._previousPickResult = null;
  25576. _this._totalPointersPressed = 0;
  25577. _this._doubleClickOccured = false;
  25578. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25579. _this.cameraToUseForPointers = null;
  25580. _this._pointerX = 0;
  25581. _this._pointerY = 0;
  25582. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25583. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25584. _this._startingPointerTime = 0;
  25585. _this._previousStartingPointerTime = 0;
  25586. _this._pointerCaptures = {};
  25587. // Deterministic lockstep
  25588. _this._timeAccumulator = 0;
  25589. _this._currentStepId = 0;
  25590. _this._currentInternalStep = 0;
  25591. // Keyboard
  25592. /**
  25593. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25594. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25595. */
  25596. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25597. /**
  25598. * Observable event triggered each time an keyboard event is received from the hosting window
  25599. */
  25600. _this.onKeyboardObservable = new BABYLON.Observable();
  25601. // Coordinates system
  25602. _this._useRightHandedSystem = false;
  25603. // Fog
  25604. _this._fogEnabled = true;
  25605. _this._fogMode = Scene.FOGMODE_NONE;
  25606. /**
  25607. * Gets or sets the fog color to use
  25608. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25609. * (Default is Color3(0.2, 0.2, 0.3))
  25610. */
  25611. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25612. /**
  25613. * Gets or sets the fog density to use
  25614. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25615. * (Default is 0.1)
  25616. */
  25617. _this.fogDensity = 0.1;
  25618. /**
  25619. * Gets or sets the fog start distance to use
  25620. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25621. * (Default is 0)
  25622. */
  25623. _this.fogStart = 0;
  25624. /**
  25625. * Gets or sets the fog end distance to use
  25626. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25627. * (Default is 1000)
  25628. */
  25629. _this.fogEnd = 1000.0;
  25630. // Lights
  25631. _this._shadowsEnabled = true;
  25632. _this._lightsEnabled = true;
  25633. /** All of the active cameras added to this scene. */
  25634. _this.activeCameras = new Array();
  25635. // Textures
  25636. _this._texturesEnabled = true;
  25637. // Particles
  25638. /**
  25639. * Gets or sets a boolean indicating if particles are enabled on this scene
  25640. */
  25641. _this.particlesEnabled = true;
  25642. // Sprites
  25643. /**
  25644. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25645. */
  25646. _this.spritesEnabled = true;
  25647. // Skeletons
  25648. _this._skeletonsEnabled = true;
  25649. // Lens flares
  25650. /**
  25651. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25652. */
  25653. _this.lensFlaresEnabled = true;
  25654. // Collisions
  25655. /**
  25656. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25657. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25658. */
  25659. _this.collisionsEnabled = true;
  25660. /**
  25661. * Defines the gravity applied to this scene (used only for collisions)
  25662. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25663. */
  25664. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25665. // Postprocesses
  25666. /**
  25667. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25668. */
  25669. _this.postProcessesEnabled = true;
  25670. /**
  25671. * The list of postprocesses added to the scene
  25672. */
  25673. _this.postProcesses = new Array();
  25674. // Customs render targets
  25675. /**
  25676. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25677. */
  25678. _this.renderTargetsEnabled = true;
  25679. /**
  25680. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25681. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25682. */
  25683. _this.dumpNextRenderTargets = false;
  25684. /**
  25685. * The list of user defined render targets added to the scene
  25686. */
  25687. _this.customRenderTargets = new Array();
  25688. /**
  25689. * Gets the list of meshes imported to the scene through SceneLoader
  25690. */
  25691. _this.importedMeshesFiles = new Array();
  25692. // Probes
  25693. /**
  25694. * Gets or sets a boolean indicating if probes are enabled on this scene
  25695. */
  25696. _this.probesEnabled = true;
  25697. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25698. // Procedural textures
  25699. /**
  25700. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25701. */
  25702. _this.proceduralTexturesEnabled = true;
  25703. // Performance counters
  25704. _this._totalVertices = new BABYLON.PerfCounter();
  25705. /** @hidden */
  25706. _this._activeIndices = new BABYLON.PerfCounter();
  25707. /** @hidden */
  25708. _this._activeParticles = new BABYLON.PerfCounter();
  25709. /** @hidden */
  25710. _this._activeBones = new BABYLON.PerfCounter();
  25711. _this._animationTime = 0;
  25712. /**
  25713. * Gets or sets a general scale for animation speed
  25714. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25715. */
  25716. _this.animationTimeScale = 1;
  25717. _this._renderId = 0;
  25718. _this._frameId = 0;
  25719. _this._executeWhenReadyTimeoutId = -1;
  25720. _this._intermediateRendering = false;
  25721. _this._viewUpdateFlag = -1;
  25722. _this._projectionUpdateFlag = -1;
  25723. _this._alternateViewUpdateFlag = -1;
  25724. _this._alternateProjectionUpdateFlag = -1;
  25725. /** @hidden */
  25726. _this._toBeDisposed = new Array(256);
  25727. _this._activeRequests = new Array();
  25728. _this._pendingData = new Array();
  25729. _this._isDisposed = false;
  25730. /**
  25731. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25732. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25733. */
  25734. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25735. _this._activeMeshes = new BABYLON.SmartArray(256);
  25736. _this._processedMaterials = new BABYLON.SmartArray(256);
  25737. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25738. /** @hidden */
  25739. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25740. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25741. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25742. /** @hidden */
  25743. _this._activeAnimatables = new Array();
  25744. _this._transformMatrix = BABYLON.Matrix.Zero();
  25745. _this._useAlternateCameraConfiguration = false;
  25746. _this._alternateRendering = false;
  25747. _this._wheelEventName = "";
  25748. /**
  25749. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25750. * This is useful if there are more lights that the maximum simulteanous authorized
  25751. */
  25752. _this.requireLightSorting = false;
  25753. /**
  25754. * @hidden
  25755. * Backing store of defined scene components.
  25756. */
  25757. _this._components = [];
  25758. /**
  25759. * @hidden
  25760. * Backing store of defined scene components.
  25761. */
  25762. _this._serializableComponents = [];
  25763. /**
  25764. * List of components to register on the next registration step.
  25765. */
  25766. _this._transientComponents = [];
  25767. /**
  25768. * @hidden
  25769. * Defines the actions happening before camera updates.
  25770. */
  25771. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25772. /**
  25773. * @hidden
  25774. * Defines the actions happening before clear the canvas.
  25775. */
  25776. _this._beforeClearStage = BABYLON.Stage.Create();
  25777. /**
  25778. * @hidden
  25779. * Defines the actions when collecting render targets for the frame.
  25780. */
  25781. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25782. /**
  25783. * @hidden
  25784. * Defines the actions happening for one camera in the frame.
  25785. */
  25786. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25787. /**
  25788. * @hidden
  25789. * Defines the actions happening during the per mesh ready checks.
  25790. */
  25791. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25792. /**
  25793. * @hidden
  25794. * Defines the actions happening before evaluate active mesh checks.
  25795. */
  25796. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25797. /**
  25798. * @hidden
  25799. * Defines the actions happening during the evaluate sub mesh checks.
  25800. */
  25801. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25802. /**
  25803. * @hidden
  25804. * Defines the actions happening during the active mesh stage.
  25805. */
  25806. _this._activeMeshStage = BABYLON.Stage.Create();
  25807. /**
  25808. * @hidden
  25809. * Defines the actions happening during the per camera render target step.
  25810. */
  25811. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25812. /**
  25813. * @hidden
  25814. * Defines the actions happening just before the active camera is drawing.
  25815. */
  25816. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25817. /**
  25818. * @hidden
  25819. * Defines the actions happening just before a rendering group is drawing.
  25820. */
  25821. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25822. /**
  25823. * @hidden
  25824. * Defines the actions happening just before a mesh is drawing.
  25825. */
  25826. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25827. /**
  25828. * @hidden
  25829. * Defines the actions happening just after a mesh has been drawn.
  25830. */
  25831. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25832. /**
  25833. * @hidden
  25834. * Defines the actions happening just after a rendering group has been drawn.
  25835. */
  25836. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25837. /**
  25838. * @hidden
  25839. * Defines the actions happening just after the active camera has been drawn.
  25840. */
  25841. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25842. /**
  25843. * @hidden
  25844. * Defines the actions happening just after rendering all cameras and computing intersections.
  25845. */
  25846. _this._afterRenderStage = BABYLON.Stage.Create();
  25847. /**
  25848. * @hidden
  25849. * Defines the actions happening when a pointer move event happens.
  25850. */
  25851. _this._pointerMoveStage = BABYLON.Stage.Create();
  25852. /**
  25853. * @hidden
  25854. * Defines the actions happening when a pointer down event happens.
  25855. */
  25856. _this._pointerDownStage = BABYLON.Stage.Create();
  25857. /**
  25858. * @hidden
  25859. * Defines the actions happening when a pointer up event happens.
  25860. */
  25861. _this._pointerUpStage = BABYLON.Stage.Create();
  25862. /**
  25863. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  25864. */
  25865. _this.geometriesById = null;
  25866. _this._defaultMeshCandidates = {
  25867. data: [],
  25868. length: 0
  25869. };
  25870. _this._defaultSubMeshCandidates = {
  25871. data: [],
  25872. length: 0
  25873. };
  25874. _this._preventFreeActiveMeshesAndRenderingGroups = false;
  25875. _this._activeMeshesFrozen = false;
  25876. /** @hidden */
  25877. _this._allowPostProcessClearColor = true;
  25878. /**
  25879. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25880. */
  25881. _this.getDeterministicFrameTime = function () {
  25882. return 1000.0 / 60.0; // frame time in ms
  25883. };
  25884. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25885. _this._blockMaterialDirtyMechanism = false;
  25886. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25887. _this._engine.scenes.push(_this);
  25888. _this._uid = null;
  25889. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25890. if (BABYLON.PostProcessManager) {
  25891. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25892. }
  25893. if (BABYLON.Tools.IsWindowObjectExist()) {
  25894. _this.attachControl();
  25895. }
  25896. //collision coordinator initialization. For now legacy per default.
  25897. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25898. // Uniform Buffer
  25899. _this._createUbo();
  25900. // Default Image processing definition
  25901. if (BABYLON.ImageProcessingConfiguration) {
  25902. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25903. }
  25904. _this.setDefaultCandidateProviders();
  25905. if (options && options.useGeometryIdsMap === true) {
  25906. _this.geometriesById = {};
  25907. }
  25908. _this.useMaterialMeshMap = options && options.useGeometryIdsMap || false;
  25909. _this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  25910. return _this;
  25911. }
  25912. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25913. /**
  25914. * Texture used in all pbr material as the reflection texture.
  25915. * As in the majority of the scene they are the same (exception for multi room and so on),
  25916. * this is easier to reference from here than from all the materials.
  25917. */
  25918. get: function () {
  25919. return this._environmentTexture;
  25920. },
  25921. /**
  25922. * Texture used in all pbr material as the reflection texture.
  25923. * As in the majority of the scene they are the same (exception for multi room and so on),
  25924. * this is easier to set here than in all the materials.
  25925. */
  25926. set: function (value) {
  25927. if (this._environmentTexture === value) {
  25928. return;
  25929. }
  25930. this._environmentTexture = value;
  25931. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25937. /**
  25938. * Default image processing configuration used either in the rendering
  25939. * Forward main pass or through the imageProcessingPostProcess if present.
  25940. * As in the majority of the scene they are the same (exception for multi camera),
  25941. * this is easier to reference from here than from all the materials and post process.
  25942. *
  25943. * No setter as we it is a shared configuration, you can set the values instead.
  25944. */
  25945. get: function () {
  25946. return this._imageProcessingConfiguration;
  25947. },
  25948. enumerable: true,
  25949. configurable: true
  25950. });
  25951. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25952. get: function () {
  25953. return this._forceWireframe;
  25954. },
  25955. /**
  25956. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25957. */
  25958. set: function (value) {
  25959. if (this._forceWireframe === value) {
  25960. return;
  25961. }
  25962. this._forceWireframe = value;
  25963. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25964. },
  25965. enumerable: true,
  25966. configurable: true
  25967. });
  25968. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25969. get: function () {
  25970. return this._forcePointsCloud;
  25971. },
  25972. /**
  25973. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25974. */
  25975. set: function (value) {
  25976. if (this._forcePointsCloud === value) {
  25977. return;
  25978. }
  25979. this._forcePointsCloud = value;
  25980. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25981. },
  25982. enumerable: true,
  25983. configurable: true
  25984. });
  25985. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25986. /**
  25987. * Gets or sets the animation properties override
  25988. */
  25989. get: function () {
  25990. return this._animationPropertiesOverride;
  25991. },
  25992. set: function (value) {
  25993. this._animationPropertiesOverride = value;
  25994. },
  25995. enumerable: true,
  25996. configurable: true
  25997. });
  25998. Object.defineProperty(Scene.prototype, "onDispose", {
  25999. /** Sets a function to be executed when this scene is disposed. */
  26000. set: function (callback) {
  26001. if (this._onDisposeObserver) {
  26002. this.onDisposeObservable.remove(this._onDisposeObserver);
  26003. }
  26004. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. Object.defineProperty(Scene.prototype, "beforeRender", {
  26010. /** Sets a function to be executed before rendering this scene */
  26011. set: function (callback) {
  26012. if (this._onBeforeRenderObserver) {
  26013. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26014. }
  26015. if (callback) {
  26016. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26017. }
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. Object.defineProperty(Scene.prototype, "afterRender", {
  26023. /** Sets a function to be executed after rendering this scene */
  26024. set: function (callback) {
  26025. if (this._onAfterRenderObserver) {
  26026. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26027. }
  26028. if (callback) {
  26029. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26030. }
  26031. },
  26032. enumerable: true,
  26033. configurable: true
  26034. });
  26035. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  26036. /** Sets a function to be executed before rendering a camera*/
  26037. set: function (callback) {
  26038. if (this._onBeforeCameraRenderObserver) {
  26039. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  26040. }
  26041. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  26042. },
  26043. enumerable: true,
  26044. configurable: true
  26045. });
  26046. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  26047. /** Sets a function to be executed after rendering a camera*/
  26048. set: function (callback) {
  26049. if (this._onAfterCameraRenderObserver) {
  26050. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  26051. }
  26052. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  26053. },
  26054. enumerable: true,
  26055. configurable: true
  26056. });
  26057. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  26058. /**
  26059. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  26060. */
  26061. get: function () {
  26062. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  26068. get: function () {
  26069. return this._useRightHandedSystem;
  26070. },
  26071. /**
  26072. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  26073. */
  26074. set: function (value) {
  26075. if (this._useRightHandedSystem === value) {
  26076. return;
  26077. }
  26078. this._useRightHandedSystem = value;
  26079. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26080. },
  26081. enumerable: true,
  26082. configurable: true
  26083. });
  26084. /**
  26085. * Sets the step Id used by deterministic lock step
  26086. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26087. * @param newStepId defines the step Id
  26088. */
  26089. Scene.prototype.setStepId = function (newStepId) {
  26090. this._currentStepId = newStepId;
  26091. };
  26092. /**
  26093. * Gets the step Id used by deterministic lock step
  26094. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26095. * @returns the step Id
  26096. */
  26097. Scene.prototype.getStepId = function () {
  26098. return this._currentStepId;
  26099. };
  26100. /**
  26101. * Gets the internal step used by deterministic lock step
  26102. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26103. * @returns the internal step
  26104. */
  26105. Scene.prototype.getInternalStep = function () {
  26106. return this._currentInternalStep;
  26107. };
  26108. Object.defineProperty(Scene.prototype, "fogEnabled", {
  26109. get: function () {
  26110. return this._fogEnabled;
  26111. },
  26112. /**
  26113. * Gets or sets a boolean indicating if fog is enabled on this scene
  26114. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26115. * (Default is true)
  26116. */
  26117. set: function (value) {
  26118. if (this._fogEnabled === value) {
  26119. return;
  26120. }
  26121. this._fogEnabled = value;
  26122. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26123. },
  26124. enumerable: true,
  26125. configurable: true
  26126. });
  26127. Object.defineProperty(Scene.prototype, "fogMode", {
  26128. get: function () {
  26129. return this._fogMode;
  26130. },
  26131. /**
  26132. * Gets or sets the fog mode to use
  26133. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26134. * | mode | value |
  26135. * | --- | --- |
  26136. * | FOGMODE_NONE | 0 |
  26137. * | FOGMODE_EXP | 1 |
  26138. * | FOGMODE_EXP2 | 2 |
  26139. * | FOGMODE_LINEAR | 3 |
  26140. */
  26141. set: function (value) {
  26142. if (this._fogMode === value) {
  26143. return;
  26144. }
  26145. this._fogMode = value;
  26146. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26147. },
  26148. enumerable: true,
  26149. configurable: true
  26150. });
  26151. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  26152. get: function () {
  26153. return this._shadowsEnabled;
  26154. },
  26155. /**
  26156. * Gets or sets a boolean indicating if shadows are enabled on this scene
  26157. */
  26158. set: function (value) {
  26159. if (this._shadowsEnabled === value) {
  26160. return;
  26161. }
  26162. this._shadowsEnabled = value;
  26163. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26164. },
  26165. enumerable: true,
  26166. configurable: true
  26167. });
  26168. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26169. get: function () {
  26170. return this._lightsEnabled;
  26171. },
  26172. /**
  26173. * Gets or sets a boolean indicating if lights are enabled on this scene
  26174. */
  26175. set: function (value) {
  26176. if (this._lightsEnabled === value) {
  26177. return;
  26178. }
  26179. this._lightsEnabled = value;
  26180. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26181. },
  26182. enumerable: true,
  26183. configurable: true
  26184. });
  26185. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26186. /** The default material used on meshes when no material is affected */
  26187. get: function () {
  26188. if (!this._defaultMaterial) {
  26189. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26190. }
  26191. return this._defaultMaterial;
  26192. },
  26193. /** The default material used on meshes when no material is affected */
  26194. set: function (value) {
  26195. this._defaultMaterial = value;
  26196. },
  26197. enumerable: true,
  26198. configurable: true
  26199. });
  26200. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26201. get: function () {
  26202. return this._texturesEnabled;
  26203. },
  26204. /**
  26205. * Gets or sets a boolean indicating if textures are enabled on this scene
  26206. */
  26207. set: function (value) {
  26208. if (this._texturesEnabled === value) {
  26209. return;
  26210. }
  26211. this._texturesEnabled = value;
  26212. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26213. },
  26214. enumerable: true,
  26215. configurable: true
  26216. });
  26217. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26218. get: function () {
  26219. return this._skeletonsEnabled;
  26220. },
  26221. /**
  26222. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26223. */
  26224. set: function (value) {
  26225. if (this._skeletonsEnabled === value) {
  26226. return;
  26227. }
  26228. this._skeletonsEnabled = value;
  26229. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26230. },
  26231. enumerable: true,
  26232. configurable: true
  26233. });
  26234. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26235. /** @hidden */
  26236. get: function () {
  26237. return this._alternateRendering;
  26238. },
  26239. enumerable: true,
  26240. configurable: true
  26241. });
  26242. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26243. /**
  26244. * Gets the list of frustum planes (built from the active camera)
  26245. */
  26246. get: function () {
  26247. return this._frustumPlanes;
  26248. },
  26249. enumerable: true,
  26250. configurable: true
  26251. });
  26252. /**
  26253. * Registers the transient components if needed.
  26254. */
  26255. Scene.prototype._registerTransientComponents = function () {
  26256. // Register components that have been associated lately to the scene.
  26257. if (this._transientComponents.length > 0) {
  26258. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26259. var component = _a[_i];
  26260. component.register();
  26261. }
  26262. this._transientComponents = [];
  26263. }
  26264. };
  26265. /**
  26266. * @hidden
  26267. * Add a component to the scene.
  26268. * Note that the ccomponent could be registered on th next frame if this is called after
  26269. * the register component stage.
  26270. * @param component Defines the component to add to the scene
  26271. */
  26272. Scene.prototype._addComponent = function (component) {
  26273. this._components.push(component);
  26274. this._transientComponents.push(component);
  26275. var serializableComponent = component;
  26276. if (serializableComponent.addFromContainer) {
  26277. this._serializableComponents.push(serializableComponent);
  26278. }
  26279. };
  26280. /**
  26281. * @hidden
  26282. * Gets a component from the scene.
  26283. * @param name defines the name of the component to retrieve
  26284. * @returns the component or null if not present
  26285. */
  26286. Scene.prototype._getComponent = function (name) {
  26287. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26288. var component = _a[_i];
  26289. if (component.name === name) {
  26290. return component;
  26291. }
  26292. }
  26293. return null;
  26294. };
  26295. /**
  26296. * @hidden
  26297. */
  26298. Scene.prototype._getDefaultMeshCandidates = function () {
  26299. this._defaultMeshCandidates.data = this.meshes;
  26300. this._defaultMeshCandidates.length = this.meshes.length;
  26301. return this._defaultMeshCandidates;
  26302. };
  26303. /**
  26304. * @hidden
  26305. */
  26306. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26307. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26308. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26309. return this._defaultSubMeshCandidates;
  26310. };
  26311. /**
  26312. * Sets the default candidate providers for the scene.
  26313. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26314. * and getCollidingSubMeshCandidates to their default function
  26315. */
  26316. Scene.prototype.setDefaultCandidateProviders = function () {
  26317. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26318. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26319. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26320. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26321. };
  26322. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26323. /**
  26324. * Gets a boolean indicating if collisions are processed on a web worker
  26325. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26326. */
  26327. get: function () {
  26328. return this._workerCollisions;
  26329. },
  26330. set: function (enabled) {
  26331. if (!BABYLON.CollisionCoordinatorLegacy) {
  26332. return;
  26333. }
  26334. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26335. this._workerCollisions = enabled;
  26336. if (this.collisionCoordinator) {
  26337. this.collisionCoordinator.destroy();
  26338. }
  26339. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26340. this.collisionCoordinator.init(this);
  26341. },
  26342. enumerable: true,
  26343. configurable: true
  26344. });
  26345. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26346. /**
  26347. * Gets the mesh that is currently under the pointer
  26348. */
  26349. get: function () {
  26350. return this._pointerOverMesh;
  26351. },
  26352. enumerable: true,
  26353. configurable: true
  26354. });
  26355. Object.defineProperty(Scene.prototype, "pointerX", {
  26356. /**
  26357. * Gets the current on-screen X position of the pointer
  26358. */
  26359. get: function () {
  26360. return this._pointerX;
  26361. },
  26362. enumerable: true,
  26363. configurable: true
  26364. });
  26365. Object.defineProperty(Scene.prototype, "pointerY", {
  26366. /**
  26367. * Gets the current on-screen Y position of the pointer
  26368. */
  26369. get: function () {
  26370. return this._pointerY;
  26371. },
  26372. enumerable: true,
  26373. configurable: true
  26374. });
  26375. /**
  26376. * Gets the cached material (ie. the latest rendered one)
  26377. * @returns the cached material
  26378. */
  26379. Scene.prototype.getCachedMaterial = function () {
  26380. return this._cachedMaterial;
  26381. };
  26382. /**
  26383. * Gets the cached effect (ie. the latest rendered one)
  26384. * @returns the cached effect
  26385. */
  26386. Scene.prototype.getCachedEffect = function () {
  26387. return this._cachedEffect;
  26388. };
  26389. /**
  26390. * Gets the cached visibility state (ie. the latest rendered one)
  26391. * @returns the cached visibility state
  26392. */
  26393. Scene.prototype.getCachedVisibility = function () {
  26394. return this._cachedVisibility;
  26395. };
  26396. /**
  26397. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26398. * @param material defines the current material
  26399. * @param effect defines the current effect
  26400. * @param visibility defines the current visibility state
  26401. * @returns true if one parameter is not cached
  26402. */
  26403. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26404. if (visibility === void 0) { visibility = 1; }
  26405. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26406. };
  26407. /**
  26408. * Gets the engine associated with the scene
  26409. * @returns an Engine
  26410. */
  26411. Scene.prototype.getEngine = function () {
  26412. return this._engine;
  26413. };
  26414. /**
  26415. * Gets the total number of vertices rendered per frame
  26416. * @returns the total number of vertices rendered per frame
  26417. */
  26418. Scene.prototype.getTotalVertices = function () {
  26419. return this._totalVertices.current;
  26420. };
  26421. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26422. /**
  26423. * Gets the performance counter for total vertices
  26424. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26425. */
  26426. get: function () {
  26427. return this._totalVertices;
  26428. },
  26429. enumerable: true,
  26430. configurable: true
  26431. });
  26432. /**
  26433. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26434. * @returns the total number of active indices rendered per frame
  26435. */
  26436. Scene.prototype.getActiveIndices = function () {
  26437. return this._activeIndices.current;
  26438. };
  26439. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26440. /**
  26441. * Gets the performance counter for active indices
  26442. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26443. */
  26444. get: function () {
  26445. return this._activeIndices;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. /**
  26451. * Gets the total number of active particles rendered per frame
  26452. * @returns the total number of active particles rendered per frame
  26453. */
  26454. Scene.prototype.getActiveParticles = function () {
  26455. return this._activeParticles.current;
  26456. };
  26457. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26458. /**
  26459. * Gets the performance counter for active particles
  26460. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26461. */
  26462. get: function () {
  26463. return this._activeParticles;
  26464. },
  26465. enumerable: true,
  26466. configurable: true
  26467. });
  26468. /**
  26469. * Gets the total number of active bones rendered per frame
  26470. * @returns the total number of active bones rendered per frame
  26471. */
  26472. Scene.prototype.getActiveBones = function () {
  26473. return this._activeBones.current;
  26474. };
  26475. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26476. /**
  26477. * Gets the performance counter for active bones
  26478. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26479. */
  26480. get: function () {
  26481. return this._activeBones;
  26482. },
  26483. enumerable: true,
  26484. configurable: true
  26485. });
  26486. /** @hidden */
  26487. Scene.prototype.getInterFramePerfCounter = function () {
  26488. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26489. return 0;
  26490. };
  26491. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26492. /** @hidden */
  26493. get: function () {
  26494. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26495. return null;
  26496. },
  26497. enumerable: true,
  26498. configurable: true
  26499. });
  26500. /** @hidden */
  26501. Scene.prototype.getLastFrameDuration = function () {
  26502. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26503. return 0;
  26504. };
  26505. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26506. /** @hidden */
  26507. get: function () {
  26508. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26509. return null;
  26510. },
  26511. enumerable: true,
  26512. configurable: true
  26513. });
  26514. /** @hidden */
  26515. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26516. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26517. return 0;
  26518. };
  26519. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26520. /** @hidden */
  26521. get: function () {
  26522. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26523. return null;
  26524. },
  26525. enumerable: true,
  26526. configurable: true
  26527. });
  26528. /**
  26529. * Gets the array of active meshes
  26530. * @returns an array of AbstractMesh
  26531. */
  26532. Scene.prototype.getActiveMeshes = function () {
  26533. return this._activeMeshes;
  26534. };
  26535. /** @hidden */
  26536. Scene.prototype.getRenderTargetsDuration = function () {
  26537. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26538. return 0;
  26539. };
  26540. /** @hidden */
  26541. Scene.prototype.getRenderDuration = function () {
  26542. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26543. return 0;
  26544. };
  26545. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26546. /** @hidden */
  26547. get: function () {
  26548. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26549. return null;
  26550. },
  26551. enumerable: true,
  26552. configurable: true
  26553. });
  26554. /** @hidden */
  26555. Scene.prototype.getParticlesDuration = function () {
  26556. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26557. return 0;
  26558. };
  26559. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26560. /** @hidden */
  26561. get: function () {
  26562. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26563. return null;
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. /** @hidden */
  26569. Scene.prototype.getSpritesDuration = function () {
  26570. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26571. return 0;
  26572. };
  26573. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26574. /** @hidden */
  26575. get: function () {
  26576. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26577. return null;
  26578. },
  26579. enumerable: true,
  26580. configurable: true
  26581. });
  26582. /**
  26583. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26584. * @returns a number
  26585. */
  26586. Scene.prototype.getAnimationRatio = function () {
  26587. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26588. };
  26589. /**
  26590. * Gets an unique Id for the current render phase
  26591. * @returns a number
  26592. */
  26593. Scene.prototype.getRenderId = function () {
  26594. return this._renderId;
  26595. };
  26596. /**
  26597. * Gets an unique Id for the current frame
  26598. * @returns a number
  26599. */
  26600. Scene.prototype.getFrameId = function () {
  26601. return this._frameId;
  26602. };
  26603. /** Call this function if you want to manually increment the render Id*/
  26604. Scene.prototype.incrementRenderId = function () {
  26605. this._renderId++;
  26606. };
  26607. Scene.prototype._updatePointerPosition = function (evt) {
  26608. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26609. if (!canvasRect) {
  26610. return;
  26611. }
  26612. this._pointerX = evt.clientX - canvasRect.left;
  26613. this._pointerY = evt.clientY - canvasRect.top;
  26614. this._unTranslatedPointerX = this._pointerX;
  26615. this._unTranslatedPointerY = this._pointerY;
  26616. };
  26617. Scene.prototype._createUbo = function () {
  26618. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26619. this._sceneUbo.addUniform("viewProjection", 16);
  26620. this._sceneUbo.addUniform("view", 16);
  26621. };
  26622. Scene.prototype._createAlternateUbo = function () {
  26623. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26624. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26625. this._alternateSceneUbo.addUniform("view", 16);
  26626. };
  26627. // Pointers handling
  26628. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26629. if (pointerInfo.pickInfo) {
  26630. if (!pointerInfo.pickInfo.ray) {
  26631. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26632. }
  26633. }
  26634. };
  26635. /**
  26636. * Use this method to simulate a pointer move on a mesh
  26637. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26638. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26639. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26640. * @returns the current scene
  26641. */
  26642. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26643. var evt = new PointerEvent("pointermove", pointerEventInit);
  26644. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26645. return this;
  26646. }
  26647. return this._processPointerMove(pickResult, evt);
  26648. };
  26649. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26650. var canvas = this._engine.getRenderingCanvas();
  26651. if (!canvas) {
  26652. return this;
  26653. }
  26654. // Restore pointer
  26655. canvas.style.cursor = this.defaultCursor;
  26656. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26657. if (isMeshPicked) {
  26658. this.setPointerOverMesh(pickResult.pickedMesh);
  26659. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26660. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26661. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26662. }
  26663. else {
  26664. canvas.style.cursor = this.hoverCursor;
  26665. }
  26666. }
  26667. }
  26668. else {
  26669. this.setPointerOverMesh(null);
  26670. }
  26671. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26672. var step = _a[_i];
  26673. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26674. }
  26675. if (pickResult) {
  26676. var type = evt.type === this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26677. if (this.onPointerMove) {
  26678. this.onPointerMove(evt, pickResult, type);
  26679. }
  26680. if (this.onPointerObservable.hasObservers()) {
  26681. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26682. this._setRayOnPointerInfo(pi);
  26683. this.onPointerObservable.notifyObservers(pi, type);
  26684. }
  26685. }
  26686. return this;
  26687. };
  26688. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26689. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26690. if (pickResult) {
  26691. pi.ray = pickResult.ray;
  26692. }
  26693. this.onPrePointerObservable.notifyObservers(pi, type);
  26694. if (pi.skipOnPointerObservable) {
  26695. return true;
  26696. }
  26697. else {
  26698. return false;
  26699. }
  26700. };
  26701. /**
  26702. * Use this method to simulate a pointer down on a mesh
  26703. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26704. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26705. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26706. * @returns the current scene
  26707. */
  26708. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26709. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26710. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26711. return this;
  26712. }
  26713. return this._processPointerDown(pickResult, evt);
  26714. };
  26715. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26716. var _this = this;
  26717. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26718. this._pickedDownMesh = pickResult.pickedMesh;
  26719. var actionManager = pickResult.pickedMesh.actionManager;
  26720. if (actionManager) {
  26721. if (actionManager.hasPickTriggers) {
  26722. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26723. switch (evt.button) {
  26724. case 0:
  26725. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26726. break;
  26727. case 1:
  26728. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26729. break;
  26730. case 2:
  26731. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26732. break;
  26733. }
  26734. }
  26735. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26736. window.setTimeout(function () {
  26737. 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);
  26738. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26739. if (_this._totalPointersPressed !== 0 &&
  26740. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26741. !_this._isPointerSwiping()) {
  26742. _this._startingPointerTime = 0;
  26743. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26744. }
  26745. }
  26746. }, Scene.LongPressDelay);
  26747. }
  26748. }
  26749. }
  26750. else {
  26751. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26752. var step = _a[_i];
  26753. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26754. }
  26755. }
  26756. if (pickResult) {
  26757. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26758. if (this.onPointerDown) {
  26759. this.onPointerDown(evt, pickResult, type);
  26760. }
  26761. if (this.onPointerObservable.hasObservers()) {
  26762. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26763. this._setRayOnPointerInfo(pi);
  26764. this.onPointerObservable.notifyObservers(pi, type);
  26765. }
  26766. }
  26767. return this;
  26768. };
  26769. /**
  26770. * Use this method to simulate a pointer up on a mesh
  26771. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26772. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26773. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26774. * @returns the current scene
  26775. */
  26776. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26777. var evt = new PointerEvent("pointerup", pointerEventInit);
  26778. var clickInfo = new ClickInfo();
  26779. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26780. return this;
  26781. }
  26782. return this._processPointerUp(pickResult, evt, clickInfo);
  26783. };
  26784. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26785. if (pickResult && pickResult && pickResult.pickedMesh) {
  26786. this._pickedUpMesh = pickResult.pickedMesh;
  26787. if (this._pickedDownMesh === this._pickedUpMesh) {
  26788. if (this.onPointerPick) {
  26789. this.onPointerPick(evt, pickResult);
  26790. }
  26791. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26792. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26793. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26794. this._setRayOnPointerInfo(pi);
  26795. this.onPointerObservable.notifyObservers(pi, type_1);
  26796. }
  26797. }
  26798. if (pickResult.pickedMesh.actionManager) {
  26799. if (clickInfo.ignore) {
  26800. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26801. }
  26802. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26803. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26804. }
  26805. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26806. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26807. }
  26808. }
  26809. }
  26810. else {
  26811. if (!clickInfo.ignore) {
  26812. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26813. var step = _a[_i];
  26814. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26815. }
  26816. }
  26817. }
  26818. if (this._pickedDownMesh &&
  26819. this._pickedDownMesh.actionManager &&
  26820. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26821. this._pickedDownMesh !== this._pickedUpMesh) {
  26822. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26823. }
  26824. var type = BABYLON.PointerEventTypes.POINTERUP;
  26825. if (this.onPointerObservable.hasObservers()) {
  26826. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  26827. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26828. type = BABYLON.PointerEventTypes.POINTERTAP;
  26829. }
  26830. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26831. type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26832. }
  26833. }
  26834. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26835. this._setRayOnPointerInfo(pi);
  26836. this.onPointerObservable.notifyObservers(pi, type);
  26837. }
  26838. if (this.onPointerUp && !clickInfo.ignore) {
  26839. this.onPointerUp(evt, pickResult, type);
  26840. }
  26841. return this;
  26842. };
  26843. /**
  26844. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26845. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26846. * @returns true if the pointer was captured
  26847. */
  26848. Scene.prototype.isPointerCaptured = function (pointerId) {
  26849. if (pointerId === void 0) { pointerId = 0; }
  26850. return this._pointerCaptures[pointerId];
  26851. };
  26852. /** @hidden */
  26853. Scene.prototype._isPointerSwiping = function () {
  26854. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26855. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26856. };
  26857. /**
  26858. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26859. * @param attachUp defines if you want to attach events to pointerup
  26860. * @param attachDown defines if you want to attach events to pointerdown
  26861. * @param attachMove defines if you want to attach events to pointermove
  26862. */
  26863. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26864. var _this = this;
  26865. if (attachUp === void 0) { attachUp = true; }
  26866. if (attachDown === void 0) { attachDown = true; }
  26867. if (attachMove === void 0) { attachMove = true; }
  26868. this._initActionManager = function (act, clickInfo) {
  26869. if (!_this._meshPickProceed) {
  26870. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26871. _this._currentPickResult = pickResult;
  26872. if (pickResult) {
  26873. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26874. }
  26875. _this._meshPickProceed = true;
  26876. }
  26877. return act;
  26878. };
  26879. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26880. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26881. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26882. btn !== _this._previousButtonPressed) {
  26883. _this._doubleClickOccured = false;
  26884. clickInfo.singleClick = true;
  26885. clickInfo.ignore = false;
  26886. cb(clickInfo, _this._currentPickResult);
  26887. }
  26888. };
  26889. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26890. var clickInfo = new ClickInfo();
  26891. _this._currentPickResult = null;
  26892. var act = null;
  26893. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26894. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26895. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26896. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26897. act = _this._initActionManager(act, clickInfo);
  26898. if (act) {
  26899. checkPicking = act.hasPickTriggers;
  26900. }
  26901. }
  26902. if (checkPicking) {
  26903. var btn = evt.button;
  26904. clickInfo.hasSwiped = _this._isPointerSwiping();
  26905. if (!clickInfo.hasSwiped) {
  26906. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26907. if (!checkSingleClickImmediately) {
  26908. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26909. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26910. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26911. act = _this._initActionManager(act, clickInfo);
  26912. if (act) {
  26913. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26914. }
  26915. }
  26916. }
  26917. if (checkSingleClickImmediately) {
  26918. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26919. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26920. btn !== _this._previousButtonPressed) {
  26921. clickInfo.singleClick = true;
  26922. cb(clickInfo, _this._currentPickResult);
  26923. }
  26924. }
  26925. // at least one double click is required to be check and exclusive double click is enabled
  26926. else {
  26927. // wait that no double click has been raised during the double click delay
  26928. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26929. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26930. }
  26931. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26932. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26933. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26934. act = _this._initActionManager(act, clickInfo);
  26935. if (act) {
  26936. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26937. }
  26938. }
  26939. if (checkDoubleClick) {
  26940. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26941. if (btn === _this._previousButtonPressed &&
  26942. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26943. !_this._doubleClickOccured) {
  26944. // pointer has not moved for 2 clicks, it's a double click
  26945. if (!clickInfo.hasSwiped &&
  26946. !_this._isPointerSwiping()) {
  26947. _this._previousStartingPointerTime = 0;
  26948. _this._doubleClickOccured = true;
  26949. clickInfo.doubleClick = true;
  26950. clickInfo.ignore = false;
  26951. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26952. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26953. }
  26954. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26955. cb(clickInfo, _this._currentPickResult);
  26956. }
  26957. // if the two successive clicks are too far, it's just two simple clicks
  26958. else {
  26959. _this._doubleClickOccured = false;
  26960. _this._previousStartingPointerTime = _this._startingPointerTime;
  26961. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26962. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26963. _this._previousButtonPressed = btn;
  26964. if (Scene.ExclusiveDoubleClickMode) {
  26965. if (_this._previousDelayedSimpleClickTimeout) {
  26966. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26967. }
  26968. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26969. cb(clickInfo, _this._previousPickResult);
  26970. }
  26971. else {
  26972. cb(clickInfo, _this._currentPickResult);
  26973. }
  26974. }
  26975. }
  26976. // just the first click of the double has been raised
  26977. else {
  26978. _this._doubleClickOccured = false;
  26979. _this._previousStartingPointerTime = _this._startingPointerTime;
  26980. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26981. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26982. _this._previousButtonPressed = btn;
  26983. }
  26984. }
  26985. }
  26986. }
  26987. clickInfo.ignore = true;
  26988. cb(clickInfo, _this._currentPickResult);
  26989. };
  26990. this._onPointerMove = function (evt) {
  26991. _this._updatePointerPosition(evt);
  26992. // PreObservable support
  26993. if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26994. return;
  26995. }
  26996. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26997. return;
  26998. }
  26999. if (!_this.pointerMovePredicate) {
  27000. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  27001. }
  27002. // Meshes
  27003. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  27004. _this._processPointerMove(pickResult, evt);
  27005. };
  27006. this._onPointerDown = function (evt) {
  27007. _this._totalPointersPressed++;
  27008. _this._pickedDownMesh = null;
  27009. _this._meshPickProceed = false;
  27010. _this._updatePointerPosition(evt);
  27011. if (_this.preventDefaultOnPointerDown && canvas) {
  27012. evt.preventDefault();
  27013. canvas.focus();
  27014. }
  27015. // PreObservable support
  27016. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  27017. return;
  27018. }
  27019. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27020. return;
  27021. }
  27022. _this._pointerCaptures[evt.pointerId] = true;
  27023. _this._startingPointerPosition.x = _this._pointerX;
  27024. _this._startingPointerPosition.y = _this._pointerY;
  27025. _this._startingPointerTime = Date.now();
  27026. if (!_this.pointerDownPredicate) {
  27027. _this.pointerDownPredicate = function (mesh) {
  27028. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27029. };
  27030. }
  27031. // Meshes
  27032. _this._pickedDownMesh = null;
  27033. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  27034. _this._processPointerDown(pickResult, evt);
  27035. };
  27036. this._onPointerUp = function (evt) {
  27037. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  27038. return; // So we need to test it the pointer down was pressed before.
  27039. }
  27040. _this._totalPointersPressed--;
  27041. _this._pickedUpMesh = null;
  27042. _this._meshPickProceed = false;
  27043. _this._updatePointerPosition(evt);
  27044. if (_this.preventDefaultOnPointerUp && canvas) {
  27045. evt.preventDefault();
  27046. canvas.focus();
  27047. }
  27048. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  27049. // PreObservable support
  27050. if (_this.onPrePointerObservable.hasObservers()) {
  27051. if (!clickInfo.ignore) {
  27052. if (!clickInfo.hasSwiped) {
  27053. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  27054. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  27055. return;
  27056. }
  27057. }
  27058. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27059. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27060. return;
  27061. }
  27062. }
  27063. }
  27064. }
  27065. else {
  27066. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  27067. return;
  27068. }
  27069. }
  27070. }
  27071. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27072. return;
  27073. }
  27074. _this._pointerCaptures[evt.pointerId] = false;
  27075. if (!_this.pointerUpPredicate) {
  27076. _this.pointerUpPredicate = function (mesh) {
  27077. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27078. };
  27079. }
  27080. // Meshes
  27081. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  27082. _this._initActionManager(null, clickInfo);
  27083. }
  27084. if (!pickResult) {
  27085. pickResult = _this._currentPickResult;
  27086. }
  27087. _this._processPointerUp(pickResult, evt, clickInfo);
  27088. _this._previousPickResult = _this._currentPickResult;
  27089. });
  27090. };
  27091. this._onKeyDown = function (evt) {
  27092. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  27093. if (_this.onPreKeyboardObservable.hasObservers()) {
  27094. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27095. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27096. if (pi.skipOnPointerObservable) {
  27097. return;
  27098. }
  27099. }
  27100. if (_this.onKeyboardObservable.hasObservers()) {
  27101. var pi = new BABYLON.KeyboardInfo(type, evt);
  27102. _this.onKeyboardObservable.notifyObservers(pi, type);
  27103. }
  27104. if (_this.actionManager) {
  27105. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27106. }
  27107. };
  27108. this._onKeyUp = function (evt) {
  27109. var type = BABYLON.KeyboardEventTypes.KEYUP;
  27110. if (_this.onPreKeyboardObservable.hasObservers()) {
  27111. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27112. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27113. if (pi.skipOnPointerObservable) {
  27114. return;
  27115. }
  27116. }
  27117. if (_this.onKeyboardObservable.hasObservers()) {
  27118. var pi = new BABYLON.KeyboardInfo(type, evt);
  27119. _this.onKeyboardObservable.notifyObservers(pi, type);
  27120. }
  27121. if (_this.actionManager) {
  27122. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27123. }
  27124. };
  27125. var engine = this.getEngine();
  27126. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  27127. if (!canvas) {
  27128. return;
  27129. }
  27130. canvas.addEventListener("keydown", _this._onKeyDown, false);
  27131. canvas.addEventListener("keyup", _this._onKeyUp, false);
  27132. });
  27133. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  27134. if (!canvas) {
  27135. return;
  27136. }
  27137. canvas.removeEventListener("keydown", _this._onKeyDown);
  27138. canvas.removeEventListener("keyup", _this._onKeyUp);
  27139. });
  27140. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27141. var canvas = this._engine.getRenderingCanvas();
  27142. if (!canvas) {
  27143. return;
  27144. }
  27145. if (attachMove) {
  27146. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  27147. // Wheel
  27148. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  27149. document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  27150. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  27151. canvas.addEventListener(this._wheelEventName, this._onPointerMove, false);
  27152. }
  27153. if (attachDown) {
  27154. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  27155. }
  27156. if (attachUp) {
  27157. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27158. }
  27159. canvas.tabIndex = 1;
  27160. };
  27161. /** Detaches all event handlers*/
  27162. Scene.prototype.detachControl = function () {
  27163. var engine = this.getEngine();
  27164. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27165. var canvas = engine.getRenderingCanvas();
  27166. if (!canvas) {
  27167. return;
  27168. }
  27169. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27170. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27171. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27172. if (this._onCanvasBlurObserver) {
  27173. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27174. }
  27175. if (this._onCanvasFocusObserver) {
  27176. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27177. }
  27178. // Wheel
  27179. canvas.removeEventListener(this._wheelEventName, this._onPointerMove);
  27180. // Keyboard
  27181. canvas.removeEventListener("keydown", this._onKeyDown);
  27182. canvas.removeEventListener("keyup", this._onKeyUp);
  27183. // Observables
  27184. this.onKeyboardObservable.clear();
  27185. this.onPreKeyboardObservable.clear();
  27186. this.onPointerObservable.clear();
  27187. this.onPrePointerObservable.clear();
  27188. };
  27189. /**
  27190. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27191. * Delay loaded resources are not taking in account
  27192. * @return true if all required resources are ready
  27193. */
  27194. Scene.prototype.isReady = function () {
  27195. if (this._isDisposed) {
  27196. return false;
  27197. }
  27198. var index;
  27199. var engine = this.getEngine();
  27200. // Effects
  27201. if (!engine.areAllEffectsReady()) {
  27202. return false;
  27203. }
  27204. // Pending data
  27205. if (this._pendingData.length > 0) {
  27206. return false;
  27207. }
  27208. // Meshes
  27209. for (index = 0; index < this.meshes.length; index++) {
  27210. var mesh = this.meshes[index];
  27211. if (!mesh.isEnabled()) {
  27212. continue;
  27213. }
  27214. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27215. continue;
  27216. }
  27217. if (!mesh.isReady(true)) {
  27218. return false;
  27219. }
  27220. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27221. // Is Ready For Mesh
  27222. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27223. var step = _a[_i];
  27224. if (!step.action(mesh, hardwareInstancedRendering)) {
  27225. return false;
  27226. }
  27227. }
  27228. }
  27229. // Geometries
  27230. for (index = 0; index < this.geometries.length; index++) {
  27231. var geometry = this.geometries[index];
  27232. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27233. return false;
  27234. }
  27235. }
  27236. // Post-processes
  27237. if (this.activeCameras && this.activeCameras.length > 0) {
  27238. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27239. var camera = _c[_b];
  27240. if (!camera.isReady(true)) {
  27241. return false;
  27242. }
  27243. }
  27244. }
  27245. else if (this.activeCamera) {
  27246. if (!this.activeCamera.isReady(true)) {
  27247. return false;
  27248. }
  27249. }
  27250. // Particles
  27251. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27252. var particleSystem = _e[_d];
  27253. if (!particleSystem.isReady()) {
  27254. return false;
  27255. }
  27256. }
  27257. return true;
  27258. };
  27259. /** Resets all cached information relative to material (including effect and visibility) */
  27260. Scene.prototype.resetCachedMaterial = function () {
  27261. this._cachedMaterial = null;
  27262. this._cachedEffect = null;
  27263. this._cachedVisibility = null;
  27264. };
  27265. /**
  27266. * Registers a function to be called before every frame render
  27267. * @param func defines the function to register
  27268. */
  27269. Scene.prototype.registerBeforeRender = function (func) {
  27270. this.onBeforeRenderObservable.add(func);
  27271. };
  27272. /**
  27273. * Unregisters a function called before every frame render
  27274. * @param func defines the function to unregister
  27275. */
  27276. Scene.prototype.unregisterBeforeRender = function (func) {
  27277. this.onBeforeRenderObservable.removeCallback(func);
  27278. };
  27279. /**
  27280. * Registers a function to be called after every frame render
  27281. * @param func defines the function to register
  27282. */
  27283. Scene.prototype.registerAfterRender = function (func) {
  27284. this.onAfterRenderObservable.add(func);
  27285. };
  27286. /**
  27287. * Unregisters a function called after every frame render
  27288. * @param func defines the function to unregister
  27289. */
  27290. Scene.prototype.unregisterAfterRender = function (func) {
  27291. this.onAfterRenderObservable.removeCallback(func);
  27292. };
  27293. Scene.prototype._executeOnceBeforeRender = function (func) {
  27294. var _this = this;
  27295. var execFunc = function () {
  27296. func();
  27297. setTimeout(function () {
  27298. _this.unregisterBeforeRender(execFunc);
  27299. });
  27300. };
  27301. this.registerBeforeRender(execFunc);
  27302. };
  27303. /**
  27304. * The provided function will run before render once and will be disposed afterwards.
  27305. * A timeout delay can be provided so that the function will be executed in N ms.
  27306. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27307. * @param func The function to be executed.
  27308. * @param timeout optional delay in ms
  27309. */
  27310. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27311. var _this = this;
  27312. if (timeout !== undefined) {
  27313. setTimeout(function () {
  27314. _this._executeOnceBeforeRender(func);
  27315. }, timeout);
  27316. }
  27317. else {
  27318. this._executeOnceBeforeRender(func);
  27319. }
  27320. };
  27321. /** @hidden */
  27322. Scene.prototype._addPendingData = function (data) {
  27323. this._pendingData.push(data);
  27324. };
  27325. /** @hidden */
  27326. Scene.prototype._removePendingData = function (data) {
  27327. var wasLoading = this.isLoading;
  27328. var index = this._pendingData.indexOf(data);
  27329. if (index !== -1) {
  27330. this._pendingData.splice(index, 1);
  27331. }
  27332. if (wasLoading && !this.isLoading) {
  27333. this.onDataLoadedObservable.notifyObservers(this);
  27334. }
  27335. };
  27336. /**
  27337. * Returns the number of items waiting to be loaded
  27338. * @returns the number of items waiting to be loaded
  27339. */
  27340. Scene.prototype.getWaitingItemsCount = function () {
  27341. return this._pendingData.length;
  27342. };
  27343. Object.defineProperty(Scene.prototype, "isLoading", {
  27344. /**
  27345. * Returns a boolean indicating if the scene is still loading data
  27346. */
  27347. get: function () {
  27348. return this._pendingData.length > 0;
  27349. },
  27350. enumerable: true,
  27351. configurable: true
  27352. });
  27353. /**
  27354. * Registers a function to be executed when the scene is ready
  27355. * @param {Function} func - the function to be executed
  27356. */
  27357. Scene.prototype.executeWhenReady = function (func) {
  27358. var _this = this;
  27359. this.onReadyObservable.add(func);
  27360. if (this._executeWhenReadyTimeoutId !== -1) {
  27361. return;
  27362. }
  27363. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27364. _this._checkIsReady();
  27365. }, 150);
  27366. };
  27367. /**
  27368. * Returns a promise that resolves when the scene is ready
  27369. * @returns A promise that resolves when the scene is ready
  27370. */
  27371. Scene.prototype.whenReadyAsync = function () {
  27372. var _this = this;
  27373. return new Promise(function (resolve) {
  27374. _this.executeWhenReady(function () {
  27375. resolve();
  27376. });
  27377. });
  27378. };
  27379. /** @hidden */
  27380. Scene.prototype._checkIsReady = function () {
  27381. var _this = this;
  27382. this._registerTransientComponents();
  27383. if (this.isReady()) {
  27384. this.onReadyObservable.notifyObservers(this);
  27385. this.onReadyObservable.clear();
  27386. this._executeWhenReadyTimeoutId = -1;
  27387. return;
  27388. }
  27389. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27390. _this._checkIsReady();
  27391. }, 150);
  27392. };
  27393. // Animations
  27394. /**
  27395. * Will start the animation sequence of a given target
  27396. * @param target defines the target
  27397. * @param from defines from which frame should animation start
  27398. * @param to defines until which frame should animation run.
  27399. * @param weight defines the weight to apply to the animation (1.0 by default)
  27400. * @param loop defines if the animation loops
  27401. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27402. * @param onAnimationEnd defines the function to be executed when the animation ends
  27403. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27404. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27405. * @returns the animatable object created for this animation
  27406. */
  27407. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27408. if (weight === void 0) { weight = 1.0; }
  27409. if (speedRatio === void 0) { speedRatio = 1.0; }
  27410. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27411. returnedAnimatable.weight = weight;
  27412. return returnedAnimatable;
  27413. };
  27414. /**
  27415. * Will start the animation sequence of a given target
  27416. * @param target defines the target
  27417. * @param from defines from which frame should animation start
  27418. * @param to defines until which frame should animation run.
  27419. * @param loop defines if the animation loops
  27420. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27421. * @param onAnimationEnd defines the function to be executed when the animation ends
  27422. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27423. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27424. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27425. * @returns the animatable object created for this animation
  27426. */
  27427. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27428. if (speedRatio === void 0) { speedRatio = 1.0; }
  27429. if (stopCurrent === void 0) { stopCurrent = true; }
  27430. if (from > to && speedRatio > 0) {
  27431. speedRatio *= -1;
  27432. }
  27433. if (stopCurrent) {
  27434. this.stopAnimation(target, undefined, targetMask);
  27435. }
  27436. if (!animatable) {
  27437. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27438. }
  27439. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27440. // Local animations
  27441. if (target.animations && shouldRunTargetAnimations) {
  27442. animatable.appendAnimations(target, target.animations);
  27443. }
  27444. // Children animations
  27445. if (target.getAnimatables) {
  27446. var animatables = target.getAnimatables();
  27447. for (var index = 0; index < animatables.length; index++) {
  27448. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27449. }
  27450. }
  27451. animatable.reset();
  27452. return animatable;
  27453. };
  27454. /**
  27455. * Begin a new animation on a given node
  27456. * @param target defines the target where the animation will take place
  27457. * @param animations defines the list of animations to start
  27458. * @param from defines the initial value
  27459. * @param to defines the final value
  27460. * @param loop defines if you want animation to loop (off by default)
  27461. * @param speedRatio defines the speed ratio to apply to all animations
  27462. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27463. * @returns the list of created animatables
  27464. */
  27465. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27466. if (speedRatio === undefined) {
  27467. speedRatio = 1.0;
  27468. }
  27469. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27470. return animatable;
  27471. };
  27472. /**
  27473. * Begin a new animation on a given node and its hierarchy
  27474. * @param target defines the root node where the animation will take place
  27475. * @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.
  27476. * @param animations defines the list of animations to start
  27477. * @param from defines the initial value
  27478. * @param to defines the final value
  27479. * @param loop defines if you want animation to loop (off by default)
  27480. * @param speedRatio defines the speed ratio to apply to all animations
  27481. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27482. * @returns the list of animatables created for all nodes
  27483. */
  27484. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27485. var children = target.getDescendants(directDescendantsOnly);
  27486. var result = [];
  27487. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27488. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27489. var child = children_1[_i];
  27490. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27491. }
  27492. return result;
  27493. };
  27494. /**
  27495. * Gets the animatable associated with a specific target
  27496. * @param target defines the target of the animatable
  27497. * @returns the required animatable if found
  27498. */
  27499. Scene.prototype.getAnimatableByTarget = function (target) {
  27500. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27501. if (this._activeAnimatables[index].target === target) {
  27502. return this._activeAnimatables[index];
  27503. }
  27504. }
  27505. return null;
  27506. };
  27507. /**
  27508. * Gets all animatables associated with a given target
  27509. * @param target defines the target to look animatables for
  27510. * @returns an array of Animatables
  27511. */
  27512. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27513. var result = [];
  27514. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27515. if (this._activeAnimatables[index].target === target) {
  27516. result.push(this._activeAnimatables[index]);
  27517. }
  27518. }
  27519. return result;
  27520. };
  27521. Object.defineProperty(Scene.prototype, "animatables", {
  27522. /**
  27523. * Gets all animatable attached to the scene
  27524. */
  27525. get: function () {
  27526. return this._activeAnimatables;
  27527. },
  27528. enumerable: true,
  27529. configurable: true
  27530. });
  27531. /**
  27532. * Will stop the animation of the given target
  27533. * @param target - the target
  27534. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27535. * @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)
  27536. */
  27537. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27538. var animatables = this.getAllAnimatablesByTarget(target);
  27539. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27540. var animatable = animatables_1[_i];
  27541. animatable.stop(animationName, targetMask);
  27542. }
  27543. };
  27544. /**
  27545. * Stops and removes all animations that have been applied to the scene
  27546. */
  27547. Scene.prototype.stopAllAnimations = function () {
  27548. if (this._activeAnimatables) {
  27549. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27550. this._activeAnimatables[i].stop();
  27551. }
  27552. this._activeAnimatables = [];
  27553. }
  27554. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27555. var group = _a[_i];
  27556. group.stop();
  27557. }
  27558. };
  27559. Scene.prototype._animate = function () {
  27560. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27561. return;
  27562. }
  27563. // Getting time
  27564. var now = BABYLON.Tools.Now;
  27565. if (!this._animationTimeLast) {
  27566. if (this._pendingData.length > 0) {
  27567. return;
  27568. }
  27569. this._animationTimeLast = now;
  27570. }
  27571. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27572. this._animationTime += deltaTime;
  27573. this._animationTimeLast = now;
  27574. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27575. this._activeAnimatables[index]._animate(this._animationTime);
  27576. }
  27577. // Late animation bindings
  27578. this._processLateAnimationBindings();
  27579. };
  27580. /** @hidden */
  27581. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27582. var target = runtimeAnimation.target;
  27583. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27584. if (!target._lateAnimationHolders) {
  27585. target._lateAnimationHolders = {};
  27586. }
  27587. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27588. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27589. totalWeight: 0,
  27590. animations: [],
  27591. originalValue: originalValue
  27592. };
  27593. }
  27594. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27595. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27596. };
  27597. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27598. var normalizer = 1.0;
  27599. var finalPosition = BABYLON.Tmp.Vector3[0];
  27600. var finalScaling = BABYLON.Tmp.Vector3[1];
  27601. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27602. var startIndex = 0;
  27603. var originalAnimation = holder.animations[0];
  27604. var originalValue = holder.originalValue;
  27605. var scale = 1;
  27606. if (holder.totalWeight < 1.0) {
  27607. // We need to mix the original value in
  27608. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27609. scale = 1.0 - holder.totalWeight;
  27610. }
  27611. else {
  27612. startIndex = 1;
  27613. // We need to normalize the weights
  27614. normalizer = holder.totalWeight;
  27615. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27616. scale = originalAnimation.weight / normalizer;
  27617. if (scale == 1) {
  27618. return originalAnimation.currentValue;
  27619. }
  27620. }
  27621. finalScaling.scaleInPlace(scale);
  27622. finalPosition.scaleInPlace(scale);
  27623. finalQuaternion.scaleInPlace(scale);
  27624. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27625. var runtimeAnimation = holder.animations[animIndex];
  27626. var scale = runtimeAnimation.weight / normalizer;
  27627. var currentPosition = BABYLON.Tmp.Vector3[2];
  27628. var currentScaling = BABYLON.Tmp.Vector3[3];
  27629. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27630. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27631. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27632. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27633. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27634. }
  27635. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27636. return originalAnimation._workValue;
  27637. };
  27638. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27639. var originalAnimation = holder.animations[0];
  27640. var originalValue = holder.originalValue;
  27641. if (holder.animations.length === 1) {
  27642. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27643. return refQuaternion;
  27644. }
  27645. var normalizer = 1.0;
  27646. var quaternions;
  27647. var weights;
  27648. if (holder.totalWeight < 1.0) {
  27649. var scale = 1.0 - holder.totalWeight;
  27650. quaternions = [];
  27651. weights = [];
  27652. quaternions.push(originalValue);
  27653. weights.push(scale);
  27654. }
  27655. else {
  27656. if (holder.animations.length === 2) { // Slerp as soon as we can
  27657. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27658. return refQuaternion;
  27659. }
  27660. quaternions = [];
  27661. weights = [];
  27662. normalizer = holder.totalWeight;
  27663. }
  27664. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27665. var runtimeAnimation = holder.animations[animIndex];
  27666. quaternions.push(runtimeAnimation.currentValue);
  27667. weights.push(runtimeAnimation.weight / normalizer);
  27668. }
  27669. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27670. var cumulativeAmount = 0;
  27671. var cumulativeQuaternion = null;
  27672. for (var index = 0; index < quaternions.length;) {
  27673. if (!cumulativeQuaternion) {
  27674. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27675. cumulativeQuaternion = refQuaternion;
  27676. cumulativeAmount = weights[index] + weights[index + 1];
  27677. index += 2;
  27678. continue;
  27679. }
  27680. cumulativeAmount += weights[index];
  27681. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27682. index++;
  27683. }
  27684. return cumulativeQuaternion;
  27685. };
  27686. Scene.prototype._processLateAnimationBindings = function () {
  27687. if (!this._registeredForLateAnimationBindings.length) {
  27688. return;
  27689. }
  27690. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27691. var target = this._registeredForLateAnimationBindings.data[index];
  27692. for (var path in target._lateAnimationHolders) {
  27693. var holder = target._lateAnimationHolders[path];
  27694. var originalAnimation = holder.animations[0];
  27695. var originalValue = holder.originalValue;
  27696. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27697. var finalValue = target[path];
  27698. if (matrixDecomposeMode) {
  27699. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27700. }
  27701. else {
  27702. var quaternionMode = originalValue.w !== undefined;
  27703. if (quaternionMode) {
  27704. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27705. }
  27706. else {
  27707. var startIndex = 0;
  27708. var normalizer = 1.0;
  27709. if (holder.totalWeight < 1.0) {
  27710. // We need to mix the original value in
  27711. if (originalValue.scale) {
  27712. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27713. }
  27714. else {
  27715. finalValue = originalValue * (1.0 - holder.totalWeight);
  27716. }
  27717. }
  27718. else {
  27719. // We need to normalize the weights
  27720. normalizer = holder.totalWeight;
  27721. var scale_1 = originalAnimation.weight / normalizer;
  27722. if (scale_1 !== 1) {
  27723. if (originalAnimation.currentValue.scale) {
  27724. finalValue = originalAnimation.currentValue.scale(scale_1);
  27725. }
  27726. else {
  27727. finalValue = originalAnimation.currentValue * scale_1;
  27728. }
  27729. }
  27730. else {
  27731. finalValue = originalAnimation.currentValue;
  27732. }
  27733. startIndex = 1;
  27734. }
  27735. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27736. var runtimeAnimation = holder.animations[animIndex];
  27737. var scale = runtimeAnimation.weight / normalizer;
  27738. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27739. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27740. }
  27741. else {
  27742. finalValue += runtimeAnimation.currentValue * scale;
  27743. }
  27744. }
  27745. }
  27746. }
  27747. target[path] = finalValue;
  27748. }
  27749. target._lateAnimationHolders = {};
  27750. }
  27751. this._registeredForLateAnimationBindings.reset();
  27752. };
  27753. // Matrix
  27754. /** @hidden */
  27755. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27756. this._useAlternateCameraConfiguration = active;
  27757. };
  27758. /**
  27759. * Gets the current view matrix
  27760. * @returns a Matrix
  27761. */
  27762. Scene.prototype.getViewMatrix = function () {
  27763. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27764. };
  27765. /**
  27766. * Gets the current projection matrix
  27767. * @returns a Matrix
  27768. */
  27769. Scene.prototype.getProjectionMatrix = function () {
  27770. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27771. };
  27772. /**
  27773. * Gets the current transform matrix
  27774. * @returns a Matrix made of View * Projection
  27775. */
  27776. Scene.prototype.getTransformMatrix = function () {
  27777. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27778. };
  27779. /**
  27780. * Sets the current transform matrix
  27781. * @param view defines the View matrix to use
  27782. * @param projection defines the Projection matrix to use
  27783. */
  27784. Scene.prototype.setTransformMatrix = function (view, projection) {
  27785. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27786. return;
  27787. }
  27788. this._viewUpdateFlag = view.updateFlag;
  27789. this._projectionUpdateFlag = projection.updateFlag;
  27790. this._viewMatrix = view;
  27791. this._projectionMatrix = projection;
  27792. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27793. // Update frustum
  27794. if (!this._frustumPlanes) {
  27795. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27796. }
  27797. else {
  27798. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27799. }
  27800. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27801. var otherCamera = this.activeCamera._alternateCamera;
  27802. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27803. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27804. }
  27805. if (this._sceneUbo.useUbo) {
  27806. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27807. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27808. this._sceneUbo.update();
  27809. }
  27810. };
  27811. /** @hidden */
  27812. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27813. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27814. return;
  27815. }
  27816. this._alternateViewUpdateFlag = view.updateFlag;
  27817. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27818. this._alternateViewMatrix = view;
  27819. this._alternateProjectionMatrix = projection;
  27820. if (!this._alternateTransformMatrix) {
  27821. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27822. }
  27823. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27824. if (!this._alternateSceneUbo) {
  27825. this._createAlternateUbo();
  27826. }
  27827. if (this._alternateSceneUbo.useUbo) {
  27828. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27829. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27830. this._alternateSceneUbo.update();
  27831. }
  27832. };
  27833. /**
  27834. * Gets the uniform buffer used to store scene data
  27835. * @returns a UniformBuffer
  27836. */
  27837. Scene.prototype.getSceneUniformBuffer = function () {
  27838. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27839. };
  27840. /**
  27841. * Gets an unique (relatively to the current scene) Id
  27842. * @returns an unique number for the scene
  27843. */
  27844. Scene.prototype.getUniqueId = function () {
  27845. var result = Scene._uniqueIdCounter;
  27846. Scene._uniqueIdCounter++;
  27847. return result;
  27848. };
  27849. /**
  27850. * Add a mesh to the list of scene's meshes
  27851. * @param newMesh defines the mesh to add
  27852. * @param recursive if all child meshes should also be added to the scene
  27853. */
  27854. Scene.prototype.addMesh = function (newMesh, recursive) {
  27855. var _this = this;
  27856. if (recursive === void 0) { recursive = false; }
  27857. this.meshes.push(newMesh);
  27858. //notify the collision coordinator
  27859. if (this.collisionCoordinator) {
  27860. this.collisionCoordinator.onMeshAdded(newMesh);
  27861. }
  27862. newMesh._resyncLightSources();
  27863. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27864. if (recursive) {
  27865. newMesh.getChildMeshes().forEach(function (m) {
  27866. _this.addMesh(m);
  27867. });
  27868. }
  27869. };
  27870. /**
  27871. * Remove a mesh for the list of scene's meshes
  27872. * @param toRemove defines the mesh to remove
  27873. * @param recursive if all child meshes should also be removed from the scene
  27874. * @returns the index where the mesh was in the mesh list
  27875. */
  27876. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27877. var _this = this;
  27878. if (recursive === void 0) { recursive = false; }
  27879. var index = this.meshes.indexOf(toRemove);
  27880. if (index !== -1) {
  27881. // Remove from the scene if mesh found
  27882. this.meshes[index] = this.meshes[this.meshes.length - 1];
  27883. this.meshes.pop();
  27884. }
  27885. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27886. if (recursive) {
  27887. toRemove.getChildMeshes().forEach(function (m) {
  27888. _this.removeMesh(m);
  27889. });
  27890. }
  27891. return index;
  27892. };
  27893. /**
  27894. * Add a transform node to the list of scene's transform nodes
  27895. * @param newTransformNode defines the transform node to add
  27896. */
  27897. Scene.prototype.addTransformNode = function (newTransformNode) {
  27898. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  27899. this.transformNodes.push(newTransformNode);
  27900. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27901. };
  27902. /**
  27903. * Remove a transform node for the list of scene's transform nodes
  27904. * @param toRemove defines the transform node to remove
  27905. * @returns the index where the transform node was in the transform node list
  27906. */
  27907. Scene.prototype.removeTransformNode = function (toRemove) {
  27908. var index = toRemove._indexInSceneTransformNodesArray;
  27909. if (index !== -1) {
  27910. if (index !== this.transformNodes.length - 1) {
  27911. var lastNode = this.transformNodes[this.transformNodes.length - 1];
  27912. this.transformNodes[index] = lastNode;
  27913. lastNode._indexInSceneTransformNodesArray = index;
  27914. }
  27915. toRemove._indexInSceneTransformNodesArray = -1;
  27916. this.transformNodes.pop();
  27917. }
  27918. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27919. return index;
  27920. };
  27921. /**
  27922. * Remove a skeleton for the list of scene's skeletons
  27923. * @param toRemove defines the skeleton to remove
  27924. * @returns the index where the skeleton was in the skeleton list
  27925. */
  27926. Scene.prototype.removeSkeleton = function (toRemove) {
  27927. var index = this.skeletons.indexOf(toRemove);
  27928. if (index !== -1) {
  27929. // Remove from the scene if found
  27930. this.skeletons.splice(index, 1);
  27931. }
  27932. return index;
  27933. };
  27934. /**
  27935. * Remove a morph target for the list of scene's morph targets
  27936. * @param toRemove defines the morph target to remove
  27937. * @returns the index where the morph target was in the morph target list
  27938. */
  27939. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27940. var index = this.morphTargetManagers.indexOf(toRemove);
  27941. if (index !== -1) {
  27942. // Remove from the scene if found
  27943. this.morphTargetManagers.splice(index, 1);
  27944. }
  27945. return index;
  27946. };
  27947. /**
  27948. * Remove a light for the list of scene's lights
  27949. * @param toRemove defines the light to remove
  27950. * @returns the index where the light was in the light list
  27951. */
  27952. Scene.prototype.removeLight = function (toRemove) {
  27953. var index = this.lights.indexOf(toRemove);
  27954. if (index !== -1) {
  27955. // Remove from meshes
  27956. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27957. var mesh = _a[_i];
  27958. mesh._removeLightSource(toRemove);
  27959. }
  27960. // Remove from the scene if mesh found
  27961. this.lights.splice(index, 1);
  27962. this.sortLightsByPriority();
  27963. }
  27964. this.onLightRemovedObservable.notifyObservers(toRemove);
  27965. return index;
  27966. };
  27967. /**
  27968. * Remove a camera for the list of scene's cameras
  27969. * @param toRemove defines the camera to remove
  27970. * @returns the index where the camera was in the camera list
  27971. */
  27972. Scene.prototype.removeCamera = function (toRemove) {
  27973. var index = this.cameras.indexOf(toRemove);
  27974. if (index !== -1) {
  27975. // Remove from the scene if mesh found
  27976. this.cameras.splice(index, 1);
  27977. }
  27978. // Remove from activeCameras
  27979. var index2 = this.activeCameras.indexOf(toRemove);
  27980. if (index2 !== -1) {
  27981. // Remove from the scene if mesh found
  27982. this.activeCameras.splice(index2, 1);
  27983. }
  27984. // Reset the activeCamera
  27985. if (this.activeCamera === toRemove) {
  27986. if (this.cameras.length > 0) {
  27987. this.activeCamera = this.cameras[0];
  27988. }
  27989. else {
  27990. this.activeCamera = null;
  27991. }
  27992. }
  27993. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27994. return index;
  27995. };
  27996. /**
  27997. * Remove a particle system for the list of scene's particle systems
  27998. * @param toRemove defines the particle system to remove
  27999. * @returns the index where the particle system was in the particle system list
  28000. */
  28001. Scene.prototype.removeParticleSystem = function (toRemove) {
  28002. var index = this.particleSystems.indexOf(toRemove);
  28003. if (index !== -1) {
  28004. this.particleSystems.splice(index, 1);
  28005. }
  28006. return index;
  28007. };
  28008. /**
  28009. * Remove a animation for the list of scene's animations
  28010. * @param toRemove defines the animation to remove
  28011. * @returns the index where the animation was in the animation list
  28012. */
  28013. Scene.prototype.removeAnimation = function (toRemove) {
  28014. var index = this.animations.indexOf(toRemove);
  28015. if (index !== -1) {
  28016. this.animations.splice(index, 1);
  28017. }
  28018. return index;
  28019. };
  28020. /**
  28021. * Removes the given animation group from this scene.
  28022. * @param toRemove The animation group to remove
  28023. * @returns The index of the removed animation group
  28024. */
  28025. Scene.prototype.removeAnimationGroup = function (toRemove) {
  28026. var index = this.animationGroups.indexOf(toRemove);
  28027. if (index !== -1) {
  28028. this.animationGroups.splice(index, 1);
  28029. }
  28030. return index;
  28031. };
  28032. /**
  28033. * Removes the given multi-material from this scene.
  28034. * @param toRemove The multi-material to remove
  28035. * @returns The index of the removed multi-material
  28036. */
  28037. Scene.prototype.removeMultiMaterial = function (toRemove) {
  28038. var index = this.multiMaterials.indexOf(toRemove);
  28039. if (index !== -1) {
  28040. this.multiMaterials.splice(index, 1);
  28041. }
  28042. return index;
  28043. };
  28044. /**
  28045. * Removes the given material from this scene.
  28046. * @param toRemove The material to remove
  28047. * @returns The index of the removed material
  28048. */
  28049. Scene.prototype.removeMaterial = function (toRemove) {
  28050. var index = toRemove._indexInSceneMaterialArray;
  28051. if (index !== -1) {
  28052. if (index !== this.materials.length - 1) {
  28053. var lastMaterial = this.materials[this.materials.length - 1];
  28054. this.materials[index] = lastMaterial;
  28055. lastMaterial._indexInSceneMaterialArray = index;
  28056. }
  28057. toRemove._indexInSceneMaterialArray = -1;
  28058. this.materials.pop();
  28059. }
  28060. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  28061. return index;
  28062. };
  28063. /**
  28064. * Removes the given action manager from this scene.
  28065. * @param toRemove The action manager to remove
  28066. * @returns The index of the removed action manager
  28067. */
  28068. Scene.prototype.removeActionManager = function (toRemove) {
  28069. var index = this.actionManagers.indexOf(toRemove);
  28070. if (index !== -1) {
  28071. this.actionManagers.splice(index, 1);
  28072. }
  28073. return index;
  28074. };
  28075. /**
  28076. * Removes the given texture from this scene.
  28077. * @param toRemove The texture to remove
  28078. * @returns The index of the removed texture
  28079. */
  28080. Scene.prototype.removeTexture = function (toRemove) {
  28081. var index = this.textures.indexOf(toRemove);
  28082. if (index !== -1) {
  28083. this.textures.splice(index, 1);
  28084. }
  28085. this.onTextureRemovedObservable.notifyObservers(toRemove);
  28086. return index;
  28087. };
  28088. /**
  28089. * Adds the given light to this scene
  28090. * @param newLight The light to add
  28091. */
  28092. Scene.prototype.addLight = function (newLight) {
  28093. this.lights.push(newLight);
  28094. this.sortLightsByPriority();
  28095. // Add light to all meshes (To support if the light is removed and then readded)
  28096. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28097. var mesh = _a[_i];
  28098. if (mesh._lightSources.indexOf(newLight) === -1) {
  28099. mesh._lightSources.push(newLight);
  28100. mesh._resyncLightSources();
  28101. }
  28102. }
  28103. this.onNewLightAddedObservable.notifyObservers(newLight);
  28104. };
  28105. /**
  28106. * Sorts the list list based on light priorities
  28107. */
  28108. Scene.prototype.sortLightsByPriority = function () {
  28109. if (this.requireLightSorting) {
  28110. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  28111. }
  28112. };
  28113. /**
  28114. * Adds the given camera to this scene
  28115. * @param newCamera The camera to add
  28116. */
  28117. Scene.prototype.addCamera = function (newCamera) {
  28118. this.cameras.push(newCamera);
  28119. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  28120. };
  28121. /**
  28122. * Adds the given skeleton to this scene
  28123. * @param newSkeleton The skeleton to add
  28124. */
  28125. Scene.prototype.addSkeleton = function (newSkeleton) {
  28126. this.skeletons.push(newSkeleton);
  28127. };
  28128. /**
  28129. * Adds the given particle system to this scene
  28130. * @param newParticleSystem The particle system to add
  28131. */
  28132. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  28133. this.particleSystems.push(newParticleSystem);
  28134. };
  28135. /**
  28136. * Adds the given animation to this scene
  28137. * @param newAnimation The animation to add
  28138. */
  28139. Scene.prototype.addAnimation = function (newAnimation) {
  28140. this.animations.push(newAnimation);
  28141. };
  28142. /**
  28143. * Adds the given animation group to this scene.
  28144. * @param newAnimationGroup The animation group to add
  28145. */
  28146. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  28147. this.animationGroups.push(newAnimationGroup);
  28148. };
  28149. /**
  28150. * Adds the given multi-material to this scene
  28151. * @param newMultiMaterial The multi-material to add
  28152. */
  28153. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  28154. this.multiMaterials.push(newMultiMaterial);
  28155. };
  28156. /**
  28157. * Adds the given material to this scene
  28158. * @param newMaterial The material to add
  28159. */
  28160. Scene.prototype.addMaterial = function (newMaterial) {
  28161. newMaterial._indexInSceneMaterialArray = this.materials.length;
  28162. this.materials.push(newMaterial);
  28163. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  28164. };
  28165. /**
  28166. * Adds the given morph target to this scene
  28167. * @param newMorphTargetManager The morph target to add
  28168. */
  28169. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  28170. this.morphTargetManagers.push(newMorphTargetManager);
  28171. };
  28172. /**
  28173. * Adds the given geometry to this scene
  28174. * @param newGeometry The geometry to add
  28175. */
  28176. Scene.prototype.addGeometry = function (newGeometry) {
  28177. if (this.geometriesById) {
  28178. this.geometriesById[newGeometry.id] = this.geometries.length;
  28179. }
  28180. this.geometries.push(newGeometry);
  28181. };
  28182. /**
  28183. * Adds the given action manager to this scene
  28184. * @param newActionManager The action manager to add
  28185. */
  28186. Scene.prototype.addActionManager = function (newActionManager) {
  28187. this.actionManagers.push(newActionManager);
  28188. };
  28189. /**
  28190. * Adds the given texture to this scene.
  28191. * @param newTexture The texture to add
  28192. */
  28193. Scene.prototype.addTexture = function (newTexture) {
  28194. this.textures.push(newTexture);
  28195. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28196. };
  28197. /**
  28198. * Switch active camera
  28199. * @param newCamera defines the new active camera
  28200. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28201. */
  28202. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28203. if (attachControl === void 0) { attachControl = true; }
  28204. var canvas = this._engine.getRenderingCanvas();
  28205. if (!canvas) {
  28206. return;
  28207. }
  28208. if (this.activeCamera) {
  28209. this.activeCamera.detachControl(canvas);
  28210. }
  28211. this.activeCamera = newCamera;
  28212. if (attachControl) {
  28213. newCamera.attachControl(canvas);
  28214. }
  28215. };
  28216. /**
  28217. * sets the active camera of the scene using its ID
  28218. * @param id defines the camera's ID
  28219. * @return the new active camera or null if none found.
  28220. */
  28221. Scene.prototype.setActiveCameraByID = function (id) {
  28222. var camera = this.getCameraByID(id);
  28223. if (camera) {
  28224. this.activeCamera = camera;
  28225. return camera;
  28226. }
  28227. return null;
  28228. };
  28229. /**
  28230. * sets the active camera of the scene using its name
  28231. * @param name defines the camera's name
  28232. * @returns the new active camera or null if none found.
  28233. */
  28234. Scene.prototype.setActiveCameraByName = function (name) {
  28235. var camera = this.getCameraByName(name);
  28236. if (camera) {
  28237. this.activeCamera = camera;
  28238. return camera;
  28239. }
  28240. return null;
  28241. };
  28242. /**
  28243. * get an animation group using its name
  28244. * @param name defines the material's name
  28245. * @return the animation group or null if none found.
  28246. */
  28247. Scene.prototype.getAnimationGroupByName = function (name) {
  28248. for (var index = 0; index < this.animationGroups.length; index++) {
  28249. if (this.animationGroups[index].name === name) {
  28250. return this.animationGroups[index];
  28251. }
  28252. }
  28253. return null;
  28254. };
  28255. /**
  28256. * get a material using its id
  28257. * @param id defines the material's ID
  28258. * @return the material or null if none found.
  28259. */
  28260. Scene.prototype.getMaterialByID = function (id) {
  28261. for (var index = 0; index < this.materials.length; index++) {
  28262. if (this.materials[index].id === id) {
  28263. return this.materials[index];
  28264. }
  28265. }
  28266. return null;
  28267. };
  28268. /**
  28269. * Gets a material using its name
  28270. * @param name defines the material's name
  28271. * @return the material or null if none found.
  28272. */
  28273. Scene.prototype.getMaterialByName = function (name) {
  28274. for (var index = 0; index < this.materials.length; index++) {
  28275. if (this.materials[index].name === name) {
  28276. return this.materials[index];
  28277. }
  28278. }
  28279. return null;
  28280. };
  28281. /**
  28282. * Gets a camera using its id
  28283. * @param id defines the id to look for
  28284. * @returns the camera or null if not found
  28285. */
  28286. Scene.prototype.getCameraByID = function (id) {
  28287. for (var index = 0; index < this.cameras.length; index++) {
  28288. if (this.cameras[index].id === id) {
  28289. return this.cameras[index];
  28290. }
  28291. }
  28292. return null;
  28293. };
  28294. /**
  28295. * Gets a camera using its unique id
  28296. * @param uniqueId defines the unique id to look for
  28297. * @returns the camera or null if not found
  28298. */
  28299. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28300. for (var index = 0; index < this.cameras.length; index++) {
  28301. if (this.cameras[index].uniqueId === uniqueId) {
  28302. return this.cameras[index];
  28303. }
  28304. }
  28305. return null;
  28306. };
  28307. /**
  28308. * Gets a camera using its name
  28309. * @param name defines the camera's name
  28310. * @return the camera or null if none found.
  28311. */
  28312. Scene.prototype.getCameraByName = function (name) {
  28313. for (var index = 0; index < this.cameras.length; index++) {
  28314. if (this.cameras[index].name === name) {
  28315. return this.cameras[index];
  28316. }
  28317. }
  28318. return null;
  28319. };
  28320. /**
  28321. * Gets a bone using its id
  28322. * @param id defines the bone's id
  28323. * @return the bone or null if not found
  28324. */
  28325. Scene.prototype.getBoneByID = function (id) {
  28326. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28327. var skeleton = this.skeletons[skeletonIndex];
  28328. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28329. if (skeleton.bones[boneIndex].id === id) {
  28330. return skeleton.bones[boneIndex];
  28331. }
  28332. }
  28333. }
  28334. return null;
  28335. };
  28336. /**
  28337. * Gets a bone using its id
  28338. * @param name defines the bone's name
  28339. * @return the bone or null if not found
  28340. */
  28341. Scene.prototype.getBoneByName = function (name) {
  28342. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28343. var skeleton = this.skeletons[skeletonIndex];
  28344. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28345. if (skeleton.bones[boneIndex].name === name) {
  28346. return skeleton.bones[boneIndex];
  28347. }
  28348. }
  28349. }
  28350. return null;
  28351. };
  28352. /**
  28353. * Gets a light node using its name
  28354. * @param name defines the the light's name
  28355. * @return the light or null if none found.
  28356. */
  28357. Scene.prototype.getLightByName = function (name) {
  28358. for (var index = 0; index < this.lights.length; index++) {
  28359. if (this.lights[index].name === name) {
  28360. return this.lights[index];
  28361. }
  28362. }
  28363. return null;
  28364. };
  28365. /**
  28366. * Gets a light node using its id
  28367. * @param id defines the light's id
  28368. * @return the light or null if none found.
  28369. */
  28370. Scene.prototype.getLightByID = function (id) {
  28371. for (var index = 0; index < this.lights.length; index++) {
  28372. if (this.lights[index].id === id) {
  28373. return this.lights[index];
  28374. }
  28375. }
  28376. return null;
  28377. };
  28378. /**
  28379. * Gets a light node using its scene-generated unique ID
  28380. * @param uniqueId defines the light's unique id
  28381. * @return the light or null if none found.
  28382. */
  28383. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28384. for (var index = 0; index < this.lights.length; index++) {
  28385. if (this.lights[index].uniqueId === uniqueId) {
  28386. return this.lights[index];
  28387. }
  28388. }
  28389. return null;
  28390. };
  28391. /**
  28392. * Gets a particle system by id
  28393. * @param id defines the particle system id
  28394. * @return the corresponding system or null if none found
  28395. */
  28396. Scene.prototype.getParticleSystemByID = function (id) {
  28397. for (var index = 0; index < this.particleSystems.length; index++) {
  28398. if (this.particleSystems[index].id === id) {
  28399. return this.particleSystems[index];
  28400. }
  28401. }
  28402. return null;
  28403. };
  28404. /**
  28405. * Gets a geometry using its ID
  28406. * @param id defines the geometry's id
  28407. * @return the geometry or null if none found.
  28408. */
  28409. Scene.prototype.getGeometryByID = function (id) {
  28410. if (this.geometriesById) {
  28411. var index_1 = this.geometriesById[id];
  28412. if (index_1 !== undefined) {
  28413. return this.geometries[index_1];
  28414. }
  28415. }
  28416. else {
  28417. for (var index = 0; index < this.geometries.length; index++) {
  28418. if (this.geometries[index].id === id) {
  28419. return this.geometries[index];
  28420. }
  28421. }
  28422. }
  28423. return null;
  28424. };
  28425. /**
  28426. * Add a new geometry to this scene
  28427. * @param geometry defines the geometry to be added to the scene.
  28428. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28429. * @return a boolean defining if the geometry was added or not
  28430. */
  28431. Scene.prototype.pushGeometry = function (geometry, force) {
  28432. if (!force && this.getGeometryByID(geometry.id)) {
  28433. return false;
  28434. }
  28435. this.addGeometry(geometry);
  28436. //notify the collision coordinator
  28437. if (this.collisionCoordinator) {
  28438. this.collisionCoordinator.onGeometryAdded(geometry);
  28439. }
  28440. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28441. return true;
  28442. };
  28443. /**
  28444. * Removes an existing geometry
  28445. * @param geometry defines the geometry to be removed from the scene
  28446. * @return a boolean defining if the geometry was removed or not
  28447. */
  28448. Scene.prototype.removeGeometry = function (geometry) {
  28449. var index;
  28450. if (this.geometriesById) {
  28451. index = this.geometriesById[geometry.id];
  28452. if (index === undefined) {
  28453. return false;
  28454. }
  28455. }
  28456. else {
  28457. index = this.geometries.indexOf(geometry);
  28458. if (index < 0) {
  28459. return false;
  28460. }
  28461. }
  28462. if (index !== this.geometries.length - 1) {
  28463. var lastGeometry = this.geometries[this.geometries.length - 1];
  28464. this.geometries[index] = lastGeometry;
  28465. if (this.geometriesById) {
  28466. this.geometriesById[lastGeometry.id] = index;
  28467. this.geometriesById[geometry.id] = undefined;
  28468. }
  28469. }
  28470. this.geometries.pop();
  28471. //notify the collision coordinator
  28472. if (this.collisionCoordinator) {
  28473. this.collisionCoordinator.onGeometryDeleted(geometry);
  28474. }
  28475. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28476. return true;
  28477. };
  28478. /**
  28479. * Gets the list of geometries attached to the scene
  28480. * @returns an array of Geometry
  28481. */
  28482. Scene.prototype.getGeometries = function () {
  28483. return this.geometries;
  28484. };
  28485. /**
  28486. * Gets the first added mesh found of a given ID
  28487. * @param id defines the id to search for
  28488. * @return the mesh found or null if not found at all
  28489. */
  28490. Scene.prototype.getMeshByID = function (id) {
  28491. for (var index = 0; index < this.meshes.length; index++) {
  28492. if (this.meshes[index].id === id) {
  28493. return this.meshes[index];
  28494. }
  28495. }
  28496. return null;
  28497. };
  28498. /**
  28499. * Gets a list of meshes using their id
  28500. * @param id defines the id to search for
  28501. * @returns a list of meshes
  28502. */
  28503. Scene.prototype.getMeshesByID = function (id) {
  28504. return this.meshes.filter(function (m) {
  28505. return m.id === id;
  28506. });
  28507. };
  28508. /**
  28509. * Gets the first added transform node found of a given ID
  28510. * @param id defines the id to search for
  28511. * @return the found transform node or null if not found at all.
  28512. */
  28513. Scene.prototype.getTransformNodeByID = function (id) {
  28514. for (var index = 0; index < this.transformNodes.length; index++) {
  28515. if (this.transformNodes[index].id === id) {
  28516. return this.transformNodes[index];
  28517. }
  28518. }
  28519. return null;
  28520. };
  28521. /**
  28522. * Gets a list of transform nodes using their id
  28523. * @param id defines the id to search for
  28524. * @returns a list of transform nodes
  28525. */
  28526. Scene.prototype.getTransformNodesByID = function (id) {
  28527. return this.transformNodes.filter(function (m) {
  28528. return m.id === id;
  28529. });
  28530. };
  28531. /**
  28532. * Gets a mesh with its auto-generated unique id
  28533. * @param uniqueId defines the unique id to search for
  28534. * @return the found mesh or null if not found at all.
  28535. */
  28536. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28537. for (var index = 0; index < this.meshes.length; index++) {
  28538. if (this.meshes[index].uniqueId === uniqueId) {
  28539. return this.meshes[index];
  28540. }
  28541. }
  28542. return null;
  28543. };
  28544. /**
  28545. * Gets a the last added mesh using a given id
  28546. * @param id defines the id to search for
  28547. * @return the found mesh or null if not found at all.
  28548. */
  28549. Scene.prototype.getLastMeshByID = function (id) {
  28550. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28551. if (this.meshes[index].id === id) {
  28552. return this.meshes[index];
  28553. }
  28554. }
  28555. return null;
  28556. };
  28557. /**
  28558. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28559. * @param id defines the id to search for
  28560. * @return the found node or null if not found at all
  28561. */
  28562. Scene.prototype.getLastEntryByID = function (id) {
  28563. var index;
  28564. for (index = this.meshes.length - 1; index >= 0; index--) {
  28565. if (this.meshes[index].id === id) {
  28566. return this.meshes[index];
  28567. }
  28568. }
  28569. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28570. if (this.transformNodes[index].id === id) {
  28571. return this.transformNodes[index];
  28572. }
  28573. }
  28574. for (index = this.cameras.length - 1; index >= 0; index--) {
  28575. if (this.cameras[index].id === id) {
  28576. return this.cameras[index];
  28577. }
  28578. }
  28579. for (index = this.lights.length - 1; index >= 0; index--) {
  28580. if (this.lights[index].id === id) {
  28581. return this.lights[index];
  28582. }
  28583. }
  28584. return null;
  28585. };
  28586. /**
  28587. * Gets a node (Mesh, Camera, Light) using a given id
  28588. * @param id defines the id to search for
  28589. * @return the found node or null if not found at all
  28590. */
  28591. Scene.prototype.getNodeByID = function (id) {
  28592. var mesh = this.getMeshByID(id);
  28593. if (mesh) {
  28594. return mesh;
  28595. }
  28596. var light = this.getLightByID(id);
  28597. if (light) {
  28598. return light;
  28599. }
  28600. var camera = this.getCameraByID(id);
  28601. if (camera) {
  28602. return camera;
  28603. }
  28604. var bone = this.getBoneByID(id);
  28605. return bone;
  28606. };
  28607. /**
  28608. * Gets a node (Mesh, Camera, Light) using a given name
  28609. * @param name defines the name to search for
  28610. * @return the found node or null if not found at all.
  28611. */
  28612. Scene.prototype.getNodeByName = function (name) {
  28613. var mesh = this.getMeshByName(name);
  28614. if (mesh) {
  28615. return mesh;
  28616. }
  28617. var light = this.getLightByName(name);
  28618. if (light) {
  28619. return light;
  28620. }
  28621. var camera = this.getCameraByName(name);
  28622. if (camera) {
  28623. return camera;
  28624. }
  28625. var bone = this.getBoneByName(name);
  28626. return bone;
  28627. };
  28628. /**
  28629. * Gets a mesh using a given name
  28630. * @param name defines the name to search for
  28631. * @return the found mesh or null if not found at all.
  28632. */
  28633. Scene.prototype.getMeshByName = function (name) {
  28634. for (var index = 0; index < this.meshes.length; index++) {
  28635. if (this.meshes[index].name === name) {
  28636. return this.meshes[index];
  28637. }
  28638. }
  28639. return null;
  28640. };
  28641. /**
  28642. * Gets a transform node using a given name
  28643. * @param name defines the name to search for
  28644. * @return the found transform node or null if not found at all.
  28645. */
  28646. Scene.prototype.getTransformNodeByName = function (name) {
  28647. for (var index = 0; index < this.transformNodes.length; index++) {
  28648. if (this.transformNodes[index].name === name) {
  28649. return this.transformNodes[index];
  28650. }
  28651. }
  28652. return null;
  28653. };
  28654. /**
  28655. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28656. * @param id defines the id to search for
  28657. * @return the found skeleton or null if not found at all.
  28658. */
  28659. Scene.prototype.getLastSkeletonByID = function (id) {
  28660. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28661. if (this.skeletons[index].id === id) {
  28662. return this.skeletons[index];
  28663. }
  28664. }
  28665. return null;
  28666. };
  28667. /**
  28668. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28669. * @param id defines the id to search for
  28670. * @return the found skeleton or null if not found at all.
  28671. */
  28672. Scene.prototype.getSkeletonById = function (id) {
  28673. for (var index = 0; index < this.skeletons.length; index++) {
  28674. if (this.skeletons[index].id === id) {
  28675. return this.skeletons[index];
  28676. }
  28677. }
  28678. return null;
  28679. };
  28680. /**
  28681. * Gets a skeleton using a given name
  28682. * @param name defines the name to search for
  28683. * @return the found skeleton or null if not found at all.
  28684. */
  28685. Scene.prototype.getSkeletonByName = function (name) {
  28686. for (var index = 0; index < this.skeletons.length; index++) {
  28687. if (this.skeletons[index].name === name) {
  28688. return this.skeletons[index];
  28689. }
  28690. }
  28691. return null;
  28692. };
  28693. /**
  28694. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28695. * @param id defines the id to search for
  28696. * @return the found morph target manager or null if not found at all.
  28697. */
  28698. Scene.prototype.getMorphTargetManagerById = function (id) {
  28699. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28700. if (this.morphTargetManagers[index].uniqueId === id) {
  28701. return this.morphTargetManagers[index];
  28702. }
  28703. }
  28704. return null;
  28705. };
  28706. /**
  28707. * Gets a boolean indicating if the given mesh is active
  28708. * @param mesh defines the mesh to look for
  28709. * @returns true if the mesh is in the active list
  28710. */
  28711. Scene.prototype.isActiveMesh = function (mesh) {
  28712. return (this._activeMeshes.indexOf(mesh) !== -1);
  28713. };
  28714. Object.defineProperty(Scene.prototype, "uid", {
  28715. /**
  28716. * Return a unique id as a string which can serve as an identifier for the scene
  28717. */
  28718. get: function () {
  28719. if (!this._uid) {
  28720. this._uid = BABYLON.Tools.RandomId();
  28721. }
  28722. return this._uid;
  28723. },
  28724. enumerable: true,
  28725. configurable: true
  28726. });
  28727. /**
  28728. * Add an externaly attached data from its key.
  28729. * This method call will fail and return false, if such key already exists.
  28730. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28731. * @param key the unique key that identifies the data
  28732. * @param data the data object to associate to the key for this Engine instance
  28733. * @return true if no such key were already present and the data was added successfully, false otherwise
  28734. */
  28735. Scene.prototype.addExternalData = function (key, data) {
  28736. if (!this._externalData) {
  28737. this._externalData = new BABYLON.StringDictionary();
  28738. }
  28739. return this._externalData.add(key, data);
  28740. };
  28741. /**
  28742. * Get an externaly attached data from its key
  28743. * @param key the unique key that identifies the data
  28744. * @return the associated data, if present (can be null), or undefined if not present
  28745. */
  28746. Scene.prototype.getExternalData = function (key) {
  28747. if (!this._externalData) {
  28748. return null;
  28749. }
  28750. return this._externalData.get(key);
  28751. };
  28752. /**
  28753. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28754. * @param key the unique key that identifies the data
  28755. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28756. * @return the associated data, can be null if the factory returned null.
  28757. */
  28758. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28759. if (!this._externalData) {
  28760. this._externalData = new BABYLON.StringDictionary();
  28761. }
  28762. return this._externalData.getOrAddWithFactory(key, factory);
  28763. };
  28764. /**
  28765. * Remove an externaly attached data from the Engine instance
  28766. * @param key the unique key that identifies the data
  28767. * @return true if the data was successfully removed, false if it doesn't exist
  28768. */
  28769. Scene.prototype.removeExternalData = function (key) {
  28770. return this._externalData.remove(key);
  28771. };
  28772. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28773. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28774. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28775. var step = _a[_i];
  28776. step.action(mesh, subMesh);
  28777. }
  28778. var material = subMesh.getMaterial();
  28779. if (material !== null && material !== undefined) {
  28780. // Render targets
  28781. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28782. if (this._processedMaterials.indexOf(material) === -1) {
  28783. this._processedMaterials.push(material);
  28784. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28785. }
  28786. }
  28787. // Dispatch
  28788. this._activeIndices.addCount(subMesh.indexCount, false);
  28789. this._renderingManager.dispatch(subMesh, mesh, material);
  28790. }
  28791. }
  28792. };
  28793. /**
  28794. * Clear the processed materials smart array preventing retention point in material dispose.
  28795. */
  28796. Scene.prototype.freeProcessedMaterials = function () {
  28797. this._processedMaterials.dispose();
  28798. };
  28799. Object.defineProperty(Scene.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
  28800. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  28801. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  28802. * when disposing several meshes in a row or a hierarchy of meshes.
  28803. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  28804. */
  28805. get: function () {
  28806. return this._preventFreeActiveMeshesAndRenderingGroups;
  28807. },
  28808. set: function (value) {
  28809. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  28810. return;
  28811. }
  28812. if (value) {
  28813. this.freeActiveMeshes();
  28814. this.freeRenderingGroups();
  28815. }
  28816. this._preventFreeActiveMeshesAndRenderingGroups = value;
  28817. },
  28818. enumerable: true,
  28819. configurable: true
  28820. });
  28821. /**
  28822. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28823. */
  28824. Scene.prototype.freeActiveMeshes = function () {
  28825. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28826. return;
  28827. }
  28828. this._activeMeshes.dispose();
  28829. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28830. this.activeCamera._activeMeshes.dispose();
  28831. }
  28832. if (this.activeCameras) {
  28833. for (var i = 0; i < this.activeCameras.length; i++) {
  28834. var activeCamera = this.activeCameras[i];
  28835. if (activeCamera && activeCamera._activeMeshes) {
  28836. activeCamera._activeMeshes.dispose();
  28837. }
  28838. }
  28839. }
  28840. };
  28841. /**
  28842. * Clear the info related to rendering groups preventing retention points during dispose.
  28843. */
  28844. Scene.prototype.freeRenderingGroups = function () {
  28845. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28846. return;
  28847. }
  28848. if (this._renderingManager) {
  28849. this._renderingManager.freeRenderingGroups();
  28850. }
  28851. if (this.textures) {
  28852. for (var i = 0; i < this.textures.length; i++) {
  28853. var texture = this.textures[i];
  28854. if (texture && texture.renderList) {
  28855. texture.freeRenderingGroups();
  28856. }
  28857. }
  28858. }
  28859. };
  28860. /** @hidden */
  28861. Scene.prototype._isInIntermediateRendering = function () {
  28862. return this._intermediateRendering;
  28863. };
  28864. /**
  28865. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28866. * @returns the current scene
  28867. */
  28868. Scene.prototype.freezeActiveMeshes = function () {
  28869. if (!this.activeCamera) {
  28870. return this;
  28871. }
  28872. if (!this._frustumPlanes) {
  28873. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28874. }
  28875. this._evaluateActiveMeshes();
  28876. this._activeMeshesFrozen = true;
  28877. return this;
  28878. };
  28879. /**
  28880. * Use this function to restart evaluating active meshes on every frame
  28881. * @returns the current scene
  28882. */
  28883. Scene.prototype.unfreezeActiveMeshes = function () {
  28884. this._activeMeshesFrozen = false;
  28885. return this;
  28886. };
  28887. Scene.prototype._evaluateActiveMeshes = function () {
  28888. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28889. return;
  28890. }
  28891. if (!this.activeCamera) {
  28892. return;
  28893. }
  28894. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28895. this.activeCamera._activeMeshes.reset();
  28896. this._activeMeshes.reset();
  28897. this._renderingManager.reset();
  28898. this._processedMaterials.reset();
  28899. this._activeParticleSystems.reset();
  28900. this._activeSkeletons.reset();
  28901. this._softwareSkinnedMeshes.reset();
  28902. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28903. var step = _a[_i];
  28904. step.action();
  28905. }
  28906. // Determine mesh candidates
  28907. var meshes = this.getActiveMeshCandidates();
  28908. // Check each mesh
  28909. var len = meshes.length;
  28910. for (var i = 0; i < len; i++) {
  28911. var mesh = meshes.data[i];
  28912. if (mesh.isBlocked) {
  28913. continue;
  28914. }
  28915. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28916. if (!mesh.isReady() || !mesh.isEnabled()) {
  28917. continue;
  28918. }
  28919. mesh.computeWorldMatrix();
  28920. // Intersections
  28921. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28922. this._meshesForIntersections.pushNoDuplicate(mesh);
  28923. }
  28924. // Switch to current LOD
  28925. var meshLOD = mesh.getLOD(this.activeCamera);
  28926. if (meshLOD === undefined || meshLOD === null) {
  28927. continue;
  28928. }
  28929. mesh._preActivate();
  28930. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  28931. this._activeMeshes.push(mesh);
  28932. this.activeCamera._activeMeshes.push(mesh);
  28933. mesh._activate(this._renderId);
  28934. if (meshLOD !== mesh) {
  28935. meshLOD._activate(this._renderId);
  28936. }
  28937. this._activeMesh(mesh, meshLOD);
  28938. }
  28939. }
  28940. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28941. // Particle systems
  28942. if (this.particlesEnabled) {
  28943. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28944. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28945. var particleSystem = this.particleSystems[particleIndex];
  28946. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28947. continue;
  28948. }
  28949. var emitter = particleSystem.emitter;
  28950. if (!emitter.position || emitter.isEnabled()) {
  28951. this._activeParticleSystems.push(particleSystem);
  28952. particleSystem.animate();
  28953. this._renderingManager.dispatchParticles(particleSystem);
  28954. }
  28955. }
  28956. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28957. }
  28958. };
  28959. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28960. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28961. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28962. mesh.skeleton.prepare();
  28963. }
  28964. if (!mesh.computeBonesUsingShaders) {
  28965. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28966. }
  28967. }
  28968. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28969. var step = _a[_i];
  28970. step.action(sourceMesh, mesh);
  28971. }
  28972. if (mesh !== undefined && mesh !== null
  28973. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28974. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28975. var len = subMeshes.length;
  28976. for (var i = 0; i < len; i++) {
  28977. var subMesh = subMeshes.data[i];
  28978. this._evaluateSubMesh(subMesh, mesh);
  28979. }
  28980. }
  28981. };
  28982. /**
  28983. * Update the transform matrix to update from the current active camera
  28984. * @param force defines a boolean used to force the update even if cache is up to date
  28985. */
  28986. Scene.prototype.updateTransformMatrix = function (force) {
  28987. if (!this.activeCamera) {
  28988. return;
  28989. }
  28990. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28991. };
  28992. /**
  28993. * 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)
  28994. * @param alternateCamera defines the camera to use
  28995. */
  28996. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28997. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28998. };
  28999. Scene.prototype._renderForCamera = function (camera, rigParent) {
  29000. if (camera && camera._skipRendering) {
  29001. return;
  29002. }
  29003. var engine = this._engine;
  29004. this.activeCamera = camera;
  29005. if (!this.activeCamera) {
  29006. throw new Error("Active camera not set");
  29007. }
  29008. // Viewport
  29009. engine.setViewport(this.activeCamera.viewport);
  29010. // Camera
  29011. this.resetCachedMaterial();
  29012. this._renderId++;
  29013. this.updateTransformMatrix();
  29014. if (camera._alternateCamera) {
  29015. this.updateAlternateTransformMatrix(camera._alternateCamera);
  29016. this._alternateRendering = true;
  29017. }
  29018. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  29019. // Meshes
  29020. this._evaluateActiveMeshes();
  29021. // Software skinning
  29022. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  29023. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  29024. mesh.applySkeleton(mesh.skeleton);
  29025. }
  29026. // Render targets
  29027. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29028. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  29029. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  29030. }
  29031. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  29032. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  29033. }
  29034. // Collects render targets from external components.
  29035. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  29036. var step = _a[_i];
  29037. step.action(this._renderTargets);
  29038. }
  29039. if (this.renderTargetsEnabled) {
  29040. this._intermediateRendering = true;
  29041. if (this._renderTargets.length > 0) {
  29042. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29043. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  29044. var renderTarget = this._renderTargets.data[renderIndex];
  29045. if (renderTarget._shouldRender()) {
  29046. this._renderId++;
  29047. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  29048. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  29049. }
  29050. }
  29051. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29052. this._renderId++;
  29053. }
  29054. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  29055. var step = _c[_b];
  29056. step.action(this.activeCamera);
  29057. }
  29058. this._intermediateRendering = false;
  29059. if (this.activeCamera.outputRenderTarget) {
  29060. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  29061. if (internalTexture) {
  29062. engine.bindFramebuffer(internalTexture);
  29063. }
  29064. else {
  29065. BABYLON.Tools.Error("Camera contains invalid customDefaultRenderTarget");
  29066. }
  29067. }
  29068. else {
  29069. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  29070. }
  29071. }
  29072. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29073. // Prepare Frame
  29074. if (this.postProcessManager) {
  29075. this.postProcessManager._prepareFrame();
  29076. }
  29077. // Before Camera Draw
  29078. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  29079. var step = _e[_d];
  29080. step.action(this.activeCamera);
  29081. }
  29082. // Render
  29083. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  29084. this._renderingManager.render(null, null, true, true);
  29085. this.onAfterDrawPhaseObservable.notifyObservers(this);
  29086. // After Camera Draw
  29087. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  29088. var step = _g[_f];
  29089. step.action(this.activeCamera);
  29090. }
  29091. // Finalize frame
  29092. if (this.postProcessManager) {
  29093. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  29094. }
  29095. // Reset some special arrays
  29096. this._renderTargets.reset();
  29097. this._alternateRendering = false;
  29098. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  29099. };
  29100. Scene.prototype._processSubCameras = function (camera) {
  29101. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  29102. this._renderForCamera(camera);
  29103. return;
  29104. }
  29105. // rig cameras
  29106. for (var index = 0; index < camera._rigCameras.length; index++) {
  29107. this._renderForCamera(camera._rigCameras[index], camera);
  29108. }
  29109. this.activeCamera = camera;
  29110. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29111. };
  29112. Scene.prototype._checkIntersections = function () {
  29113. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  29114. var sourceMesh = this._meshesForIntersections.data[index];
  29115. if (!sourceMesh.actionManager) {
  29116. continue;
  29117. }
  29118. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  29119. var action = sourceMesh.actionManager.actions[actionIndex];
  29120. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29121. var parameters = action.getTriggerParameter();
  29122. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  29123. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  29124. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  29125. if (areIntersecting && currentIntersectionInProgress === -1) {
  29126. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  29127. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29128. sourceMesh._intersectionsInProgress.push(otherMesh);
  29129. }
  29130. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29131. sourceMesh._intersectionsInProgress.push(otherMesh);
  29132. }
  29133. }
  29134. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  29135. //They intersected, and now they don't.
  29136. //is this trigger an exit trigger? execute an event.
  29137. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29138. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29139. }
  29140. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  29141. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  29142. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  29143. return otherMesh === parameterMesh;
  29144. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29145. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  29146. }
  29147. }
  29148. }
  29149. }
  29150. }
  29151. };
  29152. /** @hidden */
  29153. Scene.prototype._advancePhysicsEngineStep = function (step) {
  29154. // Do nothing. Code will be replaced if physics engine component is referenced
  29155. };
  29156. /**
  29157. * Render the scene
  29158. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  29159. */
  29160. Scene.prototype.render = function (updateCameras) {
  29161. if (updateCameras === void 0) { updateCameras = true; }
  29162. if (this.isDisposed) {
  29163. return;
  29164. }
  29165. this._frameId++;
  29166. // Register components that have been associated lately to the scene.
  29167. this._registerTransientComponents();
  29168. this._activeParticles.fetchNewFrame();
  29169. this._totalVertices.fetchNewFrame();
  29170. this._activeIndices.fetchNewFrame();
  29171. this._activeBones.fetchNewFrame();
  29172. this._meshesForIntersections.reset();
  29173. this.resetCachedMaterial();
  29174. this.onBeforeAnimationsObservable.notifyObservers(this);
  29175. // Actions
  29176. if (this.actionManager) {
  29177. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  29178. }
  29179. if (this._engine.isDeterministicLockStep()) {
  29180. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  29181. var defaultFPS = (60.0 / 1000.0);
  29182. var defaultFrameTime = this.getDeterministicFrameTime();
  29183. var stepsTaken = 0;
  29184. var maxSubSteps = this._engine.getLockstepMaxSteps();
  29185. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  29186. internalSteps = Math.min(internalSteps, maxSubSteps);
  29187. do {
  29188. this.onBeforeStepObservable.notifyObservers(this);
  29189. // Animations
  29190. this._animationRatio = defaultFrameTime * defaultFPS;
  29191. this._animate();
  29192. this.onAfterAnimationsObservable.notifyObservers(this);
  29193. // Physics
  29194. this._advancePhysicsEngineStep(defaultFrameTime);
  29195. this.onAfterStepObservable.notifyObservers(this);
  29196. this._currentStepId++;
  29197. stepsTaken++;
  29198. deltaTime -= defaultFrameTime;
  29199. } while (deltaTime > 0 && stepsTaken < internalSteps);
  29200. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  29201. }
  29202. else {
  29203. // Animations
  29204. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  29205. this._animationRatio = deltaTime * (60.0 / 1000.0);
  29206. this._animate();
  29207. this.onAfterAnimationsObservable.notifyObservers(this);
  29208. // Physics
  29209. this._advancePhysicsEngineStep(deltaTime);
  29210. }
  29211. // Before camera update steps
  29212. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  29213. var step = _a[_i];
  29214. step.action();
  29215. }
  29216. // Update Cameras
  29217. if (updateCameras) {
  29218. if (this.activeCameras.length > 0) {
  29219. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29220. var camera = this.activeCameras[cameraIndex];
  29221. camera.update();
  29222. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29223. // rig cameras
  29224. for (var index = 0; index < camera._rigCameras.length; index++) {
  29225. camera._rigCameras[index].update();
  29226. }
  29227. }
  29228. }
  29229. }
  29230. else if (this.activeCamera) {
  29231. this.activeCamera.update();
  29232. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29233. // rig cameras
  29234. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  29235. this.activeCamera._rigCameras[index].update();
  29236. }
  29237. }
  29238. }
  29239. }
  29240. // Before render
  29241. this.onBeforeRenderObservable.notifyObservers(this);
  29242. // Customs render targets
  29243. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29244. var engine = this.getEngine();
  29245. var currentActiveCamera = this.activeCamera;
  29246. if (this.renderTargetsEnabled) {
  29247. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29248. this._intermediateRendering = true;
  29249. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29250. var renderTarget = this.customRenderTargets[customIndex];
  29251. if (renderTarget._shouldRender()) {
  29252. this._renderId++;
  29253. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29254. if (!this.activeCamera) {
  29255. throw new Error("Active camera not set");
  29256. }
  29257. // Viewport
  29258. engine.setViewport(this.activeCamera.viewport);
  29259. // Camera
  29260. this.updateTransformMatrix();
  29261. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29262. }
  29263. }
  29264. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29265. this._intermediateRendering = false;
  29266. this._renderId++;
  29267. }
  29268. // Restore back buffer
  29269. if (this.customRenderTargets.length > 0) {
  29270. engine.restoreDefaultFramebuffer();
  29271. }
  29272. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29273. this.activeCamera = currentActiveCamera;
  29274. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29275. var step = _c[_b];
  29276. step.action();
  29277. }
  29278. // Clear
  29279. if (this.autoClearDepthAndStencil || this.autoClear) {
  29280. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29281. }
  29282. // Collects render targets from external components.
  29283. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29284. var step = _e[_d];
  29285. step.action(this._renderTargets);
  29286. }
  29287. // Multi-cameras?
  29288. if (this.activeCameras.length > 0) {
  29289. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29290. if (cameraIndex > 0) {
  29291. this._engine.clear(null, false, true, true);
  29292. }
  29293. this._processSubCameras(this.activeCameras[cameraIndex]);
  29294. }
  29295. }
  29296. else {
  29297. if (!this.activeCamera) {
  29298. throw new Error("No camera defined");
  29299. }
  29300. this._processSubCameras(this.activeCamera);
  29301. }
  29302. // Intersection checks
  29303. this._checkIntersections();
  29304. // Executes the after render stage actions.
  29305. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29306. var step = _g[_f];
  29307. step.action();
  29308. }
  29309. // After render
  29310. if (this.afterRender) {
  29311. this.afterRender();
  29312. }
  29313. this.onAfterRenderObservable.notifyObservers(this);
  29314. // Cleaning
  29315. if (this._toBeDisposed.length) {
  29316. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29317. var data = this._toBeDisposed[index];
  29318. if (data) {
  29319. data.dispose();
  29320. }
  29321. }
  29322. this._toBeDisposed = [];
  29323. }
  29324. if (this.dumpNextRenderTargets) {
  29325. this.dumpNextRenderTargets = false;
  29326. }
  29327. this._activeBones.addCount(0, true);
  29328. this._activeIndices.addCount(0, true);
  29329. this._activeParticles.addCount(0, true);
  29330. };
  29331. /**
  29332. * Freeze all materials
  29333. * A frozen material will not be updatable but should be faster to render
  29334. */
  29335. Scene.prototype.freezeMaterials = function () {
  29336. for (var i = 0; i < this.materials.length; i++) {
  29337. this.materials[i].freeze();
  29338. }
  29339. };
  29340. /**
  29341. * Unfreeze all materials
  29342. * A frozen material will not be updatable but should be faster to render
  29343. */
  29344. Scene.prototype.unfreezeMaterials = function () {
  29345. for (var i = 0; i < this.materials.length; i++) {
  29346. this.materials[i].unfreeze();
  29347. }
  29348. };
  29349. /**
  29350. * Releases all held ressources
  29351. */
  29352. Scene.prototype.dispose = function () {
  29353. this.beforeRender = null;
  29354. this.afterRender = null;
  29355. this.skeletons = [];
  29356. this.morphTargetManagers = [];
  29357. this._transientComponents = [];
  29358. this._isReadyForMeshStage.clear();
  29359. this._beforeEvaluateActiveMeshStage.clear();
  29360. this._evaluateSubMeshStage.clear();
  29361. this._activeMeshStage.clear();
  29362. this._cameraDrawRenderTargetStage.clear();
  29363. this._beforeCameraDrawStage.clear();
  29364. this._beforeRenderingGroupDrawStage.clear();
  29365. this._beforeRenderingMeshStage.clear();
  29366. this._afterRenderingMeshStage.clear();
  29367. this._afterRenderingGroupDrawStage.clear();
  29368. this._afterCameraDrawStage.clear();
  29369. this._afterRenderStage.clear();
  29370. this._beforeCameraUpdateStage.clear();
  29371. this._beforeClearStage.clear();
  29372. this._gatherRenderTargetsStage.clear();
  29373. this._gatherActiveCameraRenderTargetsStage.clear();
  29374. this._pointerMoveStage.clear();
  29375. this._pointerDownStage.clear();
  29376. this._pointerUpStage.clear();
  29377. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29378. var component = _a[_i];
  29379. component.dispose();
  29380. }
  29381. this.importedMeshesFiles = new Array();
  29382. this.stopAllAnimations();
  29383. this.resetCachedMaterial();
  29384. // Smart arrays
  29385. if (this.activeCamera) {
  29386. this.activeCamera._activeMeshes.dispose();
  29387. this.activeCamera = null;
  29388. }
  29389. this._activeMeshes.dispose();
  29390. this._renderingManager.dispose();
  29391. this._processedMaterials.dispose();
  29392. this._activeParticleSystems.dispose();
  29393. this._activeSkeletons.dispose();
  29394. this._softwareSkinnedMeshes.dispose();
  29395. this._renderTargets.dispose();
  29396. this._registeredForLateAnimationBindings.dispose();
  29397. this._meshesForIntersections.dispose();
  29398. this._toBeDisposed = [];
  29399. // Abort active requests
  29400. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29401. var request = _c[_b];
  29402. request.abort();
  29403. }
  29404. // Events
  29405. this.onDisposeObservable.notifyObservers(this);
  29406. this.onDisposeObservable.clear();
  29407. this.onBeforeRenderObservable.clear();
  29408. this.onAfterRenderObservable.clear();
  29409. this.onBeforeRenderTargetsRenderObservable.clear();
  29410. this.onAfterRenderTargetsRenderObservable.clear();
  29411. this.onAfterStepObservable.clear();
  29412. this.onBeforeStepObservable.clear();
  29413. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29414. this.onAfterActiveMeshesEvaluationObservable.clear();
  29415. this.onBeforeParticlesRenderingObservable.clear();
  29416. this.onAfterParticlesRenderingObservable.clear();
  29417. this.onBeforeDrawPhaseObservable.clear();
  29418. this.onAfterDrawPhaseObservable.clear();
  29419. this.onBeforeAnimationsObservable.clear();
  29420. this.onAfterAnimationsObservable.clear();
  29421. this.onDataLoadedObservable.clear();
  29422. this.onBeforeRenderingGroupObservable.clear();
  29423. this.onAfterRenderingGroupObservable.clear();
  29424. this.onMeshImportedObservable.clear();
  29425. this.onBeforeCameraRenderObservable.clear();
  29426. this.onAfterCameraRenderObservable.clear();
  29427. this.onReadyObservable.clear();
  29428. this.onNewCameraAddedObservable.clear();
  29429. this.onCameraRemovedObservable.clear();
  29430. this.onNewLightAddedObservable.clear();
  29431. this.onLightRemovedObservable.clear();
  29432. this.onNewGeometryAddedObservable.clear();
  29433. this.onGeometryRemovedObservable.clear();
  29434. this.onNewTransformNodeAddedObservable.clear();
  29435. this.onTransformNodeRemovedObservable.clear();
  29436. this.onNewMeshAddedObservable.clear();
  29437. this.onMeshRemovedObservable.clear();
  29438. this.onNewMaterialAddedObservable.clear();
  29439. this.onMaterialRemovedObservable.clear();
  29440. this.onNewTextureAddedObservable.clear();
  29441. this.onTextureRemovedObservable.clear();
  29442. this.onPrePointerObservable.clear();
  29443. this.onPointerObservable.clear();
  29444. this.onPreKeyboardObservable.clear();
  29445. this.onKeyboardObservable.clear();
  29446. this.detachControl();
  29447. // Detach cameras
  29448. var canvas = this._engine.getRenderingCanvas();
  29449. if (canvas) {
  29450. var index;
  29451. for (index = 0; index < this.cameras.length; index++) {
  29452. this.cameras[index].detachControl(canvas);
  29453. }
  29454. }
  29455. // Release animation groups
  29456. while (this.animationGroups.length) {
  29457. this.animationGroups[0].dispose();
  29458. }
  29459. // Release lights
  29460. while (this.lights.length) {
  29461. this.lights[0].dispose();
  29462. }
  29463. // Release meshes
  29464. while (this.meshes.length) {
  29465. this.meshes[0].dispose(true);
  29466. }
  29467. while (this.transformNodes.length) {
  29468. this.removeTransformNode(this.transformNodes[0]);
  29469. }
  29470. // Release cameras
  29471. while (this.cameras.length) {
  29472. this.cameras[0].dispose();
  29473. }
  29474. // Release materials
  29475. if (this.defaultMaterial) {
  29476. this.defaultMaterial.dispose();
  29477. }
  29478. while (this.multiMaterials.length) {
  29479. this.multiMaterials[0].dispose();
  29480. }
  29481. while (this.materials.length) {
  29482. this.materials[0].dispose();
  29483. }
  29484. // Release particles
  29485. while (this.particleSystems.length) {
  29486. this.particleSystems[0].dispose();
  29487. }
  29488. // Release postProcesses
  29489. while (this.postProcesses.length) {
  29490. this.postProcesses[0].dispose();
  29491. }
  29492. // Release textures
  29493. while (this.textures.length) {
  29494. this.textures[0].dispose();
  29495. }
  29496. // Release UBO
  29497. this._sceneUbo.dispose();
  29498. if (this._alternateSceneUbo) {
  29499. this._alternateSceneUbo.dispose();
  29500. }
  29501. // Post-processes
  29502. this.postProcessManager.dispose();
  29503. // Remove from engine
  29504. index = this._engine.scenes.indexOf(this);
  29505. if (index > -1) {
  29506. this._engine.scenes.splice(index, 1);
  29507. }
  29508. this._engine.wipeCaches(true);
  29509. this._isDisposed = true;
  29510. };
  29511. Object.defineProperty(Scene.prototype, "isDisposed", {
  29512. /**
  29513. * Gets if the scene is already disposed
  29514. */
  29515. get: function () {
  29516. return this._isDisposed;
  29517. },
  29518. enumerable: true,
  29519. configurable: true
  29520. });
  29521. /**
  29522. * Call this function to reduce memory footprint of the scene.
  29523. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29524. */
  29525. Scene.prototype.clearCachedVertexData = function () {
  29526. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29527. var mesh = this.meshes[meshIndex];
  29528. var geometry = mesh.geometry;
  29529. if (geometry) {
  29530. geometry._indices = [];
  29531. for (var vbName in geometry._vertexBuffers) {
  29532. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29533. continue;
  29534. }
  29535. geometry._vertexBuffers[vbName]._buffer._data = null;
  29536. }
  29537. }
  29538. }
  29539. };
  29540. /**
  29541. * This function will remove the local cached buffer data from texture.
  29542. * It will save memory but will prevent the texture from being rebuilt
  29543. */
  29544. Scene.prototype.cleanCachedTextureBuffer = function () {
  29545. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29546. var baseTexture = _a[_i];
  29547. var buffer = baseTexture._buffer;
  29548. if (buffer) {
  29549. baseTexture._buffer = null;
  29550. }
  29551. }
  29552. };
  29553. /**
  29554. * Get the world extend vectors with an optional filter
  29555. *
  29556. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29557. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29558. */
  29559. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29560. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29561. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29562. filterPredicate = filterPredicate || (function () { return true; });
  29563. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29564. mesh.computeWorldMatrix(true);
  29565. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29566. return;
  29567. }
  29568. var boundingInfo = mesh.getBoundingInfo();
  29569. var minBox = boundingInfo.boundingBox.minimumWorld;
  29570. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29571. BABYLON.Tools.CheckExtends(minBox, min, max);
  29572. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29573. });
  29574. return {
  29575. min: min,
  29576. max: max
  29577. };
  29578. };
  29579. // Picking
  29580. /**
  29581. * Creates a ray that can be used to pick in the scene
  29582. * @param x defines the x coordinate of the origin (on-screen)
  29583. * @param y defines the y coordinate of the origin (on-screen)
  29584. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29585. * @param camera defines the camera to use for the picking
  29586. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29587. * @returns a Ray
  29588. */
  29589. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29590. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29591. var result = BABYLON.Ray.Zero();
  29592. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29593. return result;
  29594. };
  29595. /**
  29596. * Creates a ray that can be used to pick in the scene
  29597. * @param x defines the x coordinate of the origin (on-screen)
  29598. * @param y defines the y coordinate of the origin (on-screen)
  29599. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29600. * @param result defines the ray where to store the picking ray
  29601. * @param camera defines the camera to use for the picking
  29602. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29603. * @returns the current scene
  29604. */
  29605. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29606. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29607. var engine = this._engine;
  29608. if (!camera) {
  29609. if (!this.activeCamera) {
  29610. throw new Error("Active camera not set");
  29611. }
  29612. camera = this.activeCamera;
  29613. }
  29614. var cameraViewport = camera.viewport;
  29615. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29616. // Moving coordinates to local viewport world
  29617. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29618. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29619. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29620. return this;
  29621. };
  29622. /**
  29623. * Creates a ray that can be used to pick in the scene
  29624. * @param x defines the x coordinate of the origin (on-screen)
  29625. * @param y defines the y coordinate of the origin (on-screen)
  29626. * @param camera defines the camera to use for the picking
  29627. * @returns a Ray
  29628. */
  29629. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29630. var result = BABYLON.Ray.Zero();
  29631. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29632. return result;
  29633. };
  29634. /**
  29635. * Creates a ray that can be used to pick in the scene
  29636. * @param x defines the x coordinate of the origin (on-screen)
  29637. * @param y defines the y coordinate of the origin (on-screen)
  29638. * @param result defines the ray where to store the picking ray
  29639. * @param camera defines the camera to use for the picking
  29640. * @returns the current scene
  29641. */
  29642. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29643. if (!BABYLON.PickingInfo) {
  29644. return this;
  29645. }
  29646. var engine = this._engine;
  29647. if (!camera) {
  29648. if (!this.activeCamera) {
  29649. throw new Error("Active camera not set");
  29650. }
  29651. camera = this.activeCamera;
  29652. }
  29653. var cameraViewport = camera.viewport;
  29654. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29655. var identity = BABYLON.Matrix.Identity();
  29656. // Moving coordinates to local viewport world
  29657. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29658. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29659. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29660. return this;
  29661. };
  29662. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29663. if (!BABYLON.PickingInfo) {
  29664. return null;
  29665. }
  29666. var pickingInfo = null;
  29667. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29668. var mesh = this.meshes[meshIndex];
  29669. if (predicate) {
  29670. if (!predicate(mesh)) {
  29671. continue;
  29672. }
  29673. }
  29674. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29675. continue;
  29676. }
  29677. var world = mesh.getWorldMatrix();
  29678. var ray = rayFunction(world);
  29679. var result = mesh.intersects(ray, fastCheck);
  29680. if (!result || !result.hit) {
  29681. continue;
  29682. }
  29683. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29684. continue;
  29685. }
  29686. pickingInfo = result;
  29687. if (fastCheck) {
  29688. break;
  29689. }
  29690. }
  29691. return pickingInfo || new BABYLON.PickingInfo();
  29692. };
  29693. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29694. if (!BABYLON.PickingInfo) {
  29695. return null;
  29696. }
  29697. var pickingInfos = new Array();
  29698. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29699. var mesh = this.meshes[meshIndex];
  29700. if (predicate) {
  29701. if (!predicate(mesh)) {
  29702. continue;
  29703. }
  29704. }
  29705. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29706. continue;
  29707. }
  29708. var world = mesh.getWorldMatrix();
  29709. var ray = rayFunction(world);
  29710. var result = mesh.intersects(ray, false);
  29711. if (!result || !result.hit) {
  29712. continue;
  29713. }
  29714. pickingInfos.push(result);
  29715. }
  29716. return pickingInfos;
  29717. };
  29718. /** Launch a ray to try to pick a mesh in the scene
  29719. * @param x position on screen
  29720. * @param y position on screen
  29721. * @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
  29722. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29723. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29724. * @returns a PickingInfo
  29725. */
  29726. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29727. var _this = this;
  29728. if (!BABYLON.PickingInfo) {
  29729. return null;
  29730. }
  29731. var result = this._internalPick(function (world) {
  29732. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29733. return _this._tempPickingRay;
  29734. }, predicate, fastCheck);
  29735. if (result) {
  29736. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29737. }
  29738. return result;
  29739. };
  29740. /** Use the given ray to pick a mesh in the scene
  29741. * @param ray The ray to use to pick meshes
  29742. * @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
  29743. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29744. * @returns a PickingInfo
  29745. */
  29746. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29747. var _this = this;
  29748. var result = this._internalPick(function (world) {
  29749. if (!_this._pickWithRayInverseMatrix) {
  29750. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29751. }
  29752. world.invertToRef(_this._pickWithRayInverseMatrix);
  29753. if (!_this._cachedRayForTransform) {
  29754. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29755. }
  29756. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29757. return _this._cachedRayForTransform;
  29758. }, predicate, fastCheck);
  29759. if (result) {
  29760. result.ray = ray;
  29761. }
  29762. return result;
  29763. };
  29764. /**
  29765. * Launch a ray to try to pick a mesh in the scene
  29766. * @param x X position on screen
  29767. * @param y Y position on screen
  29768. * @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
  29769. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29770. * @returns an array of PickingInfo
  29771. */
  29772. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29773. var _this = this;
  29774. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29775. };
  29776. /**
  29777. * Launch a ray to try to pick a mesh in the scene
  29778. * @param ray Ray to use
  29779. * @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
  29780. * @returns an array of PickingInfo
  29781. */
  29782. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29783. var _this = this;
  29784. return this._internalMultiPick(function (world) {
  29785. if (!_this._pickWithRayInverseMatrix) {
  29786. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29787. }
  29788. world.invertToRef(_this._pickWithRayInverseMatrix);
  29789. if (!_this._cachedRayForTransform) {
  29790. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29791. }
  29792. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29793. return _this._cachedRayForTransform;
  29794. }, predicate);
  29795. };
  29796. /**
  29797. * Force the value of meshUnderPointer
  29798. * @param mesh defines the mesh to use
  29799. */
  29800. Scene.prototype.setPointerOverMesh = function (mesh) {
  29801. if (this._pointerOverMesh === mesh) {
  29802. return;
  29803. }
  29804. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29805. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29806. }
  29807. this._pointerOverMesh = mesh;
  29808. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29809. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29810. }
  29811. };
  29812. /**
  29813. * Gets the mesh under the pointer
  29814. * @returns a Mesh or null if no mesh is under the pointer
  29815. */
  29816. Scene.prototype.getPointerOverMesh = function () {
  29817. return this._pointerOverMesh;
  29818. };
  29819. // Misc.
  29820. /** @hidden */
  29821. Scene.prototype._rebuildGeometries = function () {
  29822. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29823. var geometry = _a[_i];
  29824. geometry._rebuild();
  29825. }
  29826. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29827. var mesh = _c[_b];
  29828. mesh._rebuild();
  29829. }
  29830. if (this.postProcessManager) {
  29831. this.postProcessManager._rebuild();
  29832. }
  29833. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29834. var component = _e[_d];
  29835. component.rebuild();
  29836. }
  29837. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29838. var system = _g[_f];
  29839. system.rebuild();
  29840. }
  29841. };
  29842. /** @hidden */
  29843. Scene.prototype._rebuildTextures = function () {
  29844. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29845. var texture = _a[_i];
  29846. texture._rebuild();
  29847. }
  29848. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29849. };
  29850. // Tags
  29851. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29852. if (tagsQuery === undefined) {
  29853. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29854. return list;
  29855. }
  29856. var listByTags = [];
  29857. forEach = forEach || (function (item) { return; });
  29858. for (var i in list) {
  29859. var item = list[i];
  29860. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29861. listByTags.push(item);
  29862. forEach(item);
  29863. }
  29864. }
  29865. return listByTags;
  29866. };
  29867. /**
  29868. * Get a list of meshes by tags
  29869. * @param tagsQuery defines the tags query to use
  29870. * @param forEach defines a predicate used to filter results
  29871. * @returns an array of Mesh
  29872. */
  29873. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29874. return this._getByTags(this.meshes, tagsQuery, forEach);
  29875. };
  29876. /**
  29877. * Get a list of cameras by tags
  29878. * @param tagsQuery defines the tags query to use
  29879. * @param forEach defines a predicate used to filter results
  29880. * @returns an array of Camera
  29881. */
  29882. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29883. return this._getByTags(this.cameras, tagsQuery, forEach);
  29884. };
  29885. /**
  29886. * Get a list of lights by tags
  29887. * @param tagsQuery defines the tags query to use
  29888. * @param forEach defines a predicate used to filter results
  29889. * @returns an array of Light
  29890. */
  29891. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29892. return this._getByTags(this.lights, tagsQuery, forEach);
  29893. };
  29894. /**
  29895. * Get a list of materials by tags
  29896. * @param tagsQuery defines the tags query to use
  29897. * @param forEach defines a predicate used to filter results
  29898. * @returns an array of Material
  29899. */
  29900. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29901. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29902. };
  29903. /**
  29904. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29905. * This allowed control for front to back rendering or reversly depending of the special needs.
  29906. *
  29907. * @param renderingGroupId The rendering group id corresponding to its index
  29908. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29909. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29910. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29911. */
  29912. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29913. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29914. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29915. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29916. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29917. };
  29918. /**
  29919. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29920. *
  29921. * @param renderingGroupId The rendering group id corresponding to its index
  29922. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29923. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29924. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29925. */
  29926. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29927. if (depth === void 0) { depth = true; }
  29928. if (stencil === void 0) { stencil = true; }
  29929. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29930. };
  29931. /**
  29932. * Gets the current auto clear configuration for one rendering group of the rendering
  29933. * manager.
  29934. * @param index the rendering group index to get the information for
  29935. * @returns The auto clear setup for the requested rendering group
  29936. */
  29937. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29938. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29939. };
  29940. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29941. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29942. get: function () {
  29943. return this._blockMaterialDirtyMechanism;
  29944. },
  29945. set: function (value) {
  29946. if (this._blockMaterialDirtyMechanism === value) {
  29947. return;
  29948. }
  29949. this._blockMaterialDirtyMechanism = value;
  29950. if (!value) { // Do a complete update
  29951. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29952. }
  29953. },
  29954. enumerable: true,
  29955. configurable: true
  29956. });
  29957. /**
  29958. * Will flag all materials as dirty to trigger new shader compilation
  29959. * @param flag defines the flag used to specify which material part must be marked as dirty
  29960. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29961. */
  29962. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29963. if (this._blockMaterialDirtyMechanism) {
  29964. return;
  29965. }
  29966. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29967. var material = _a[_i];
  29968. if (predicate && !predicate(material)) {
  29969. continue;
  29970. }
  29971. material.markAsDirty(flag);
  29972. }
  29973. };
  29974. /** @hidden */
  29975. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError) {
  29976. var _this = this;
  29977. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  29978. this._activeRequests.push(request);
  29979. request.onCompleteObservable.add(function (request) {
  29980. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29981. });
  29982. return request;
  29983. };
  29984. /** @hidden */
  29985. Scene.prototype._loadFileAsync = function (url, useOfflineSupport, useArrayBuffer) {
  29986. var _this = this;
  29987. return new Promise(function (resolve, reject) {
  29988. _this._loadFile(url, function (data) {
  29989. resolve(data);
  29990. }, undefined, useOfflineSupport, useArrayBuffer, function (request, exception) {
  29991. reject(exception);
  29992. });
  29993. });
  29994. };
  29995. // Statics
  29996. Scene._uniqueIdCounter = 0;
  29997. /** The fog is deactivated */
  29998. Scene.FOGMODE_NONE = 0;
  29999. /** The fog density is following an exponential function */
  30000. Scene.FOGMODE_EXP = 1;
  30001. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  30002. Scene.FOGMODE_EXP2 = 2;
  30003. /** The fog density is following a linear function. */
  30004. Scene.FOGMODE_LINEAR = 3;
  30005. /**
  30006. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  30007. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30008. */
  30009. Scene.MinDeltaTime = 1.0;
  30010. /**
  30011. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  30012. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30013. */
  30014. Scene.MaxDeltaTime = 1000.0;
  30015. /** The distance in pixel that you have to move to prevent some events */
  30016. Scene.DragMovementThreshold = 10; // in pixels
  30017. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  30018. Scene.LongPressDelay = 500; // in milliseconds
  30019. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  30020. Scene.DoubleClickDelay = 300; // in milliseconds
  30021. /** If you need to check double click without raising a single click at first click, enable this flag */
  30022. Scene.ExclusiveDoubleClickMode = false;
  30023. return Scene;
  30024. }(BABYLON.AbstractScene));
  30025. BABYLON.Scene = Scene;
  30026. })(BABYLON || (BABYLON = {}));
  30027. //# sourceMappingURL=babylon.scene.js.map
  30028. var BABYLON;
  30029. (function (BABYLON) {
  30030. /**
  30031. * Set of assets to keep when moving a scene into an asset container.
  30032. */
  30033. var KeepAssets = /** @class */ (function (_super) {
  30034. __extends(KeepAssets, _super);
  30035. function KeepAssets() {
  30036. return _super !== null && _super.apply(this, arguments) || this;
  30037. }
  30038. return KeepAssets;
  30039. }(BABYLON.AbstractScene));
  30040. BABYLON.KeepAssets = KeepAssets;
  30041. /**
  30042. * Container with a set of assets that can be added or removed from a scene.
  30043. */
  30044. var AssetContainer = /** @class */ (function (_super) {
  30045. __extends(AssetContainer, _super);
  30046. /**
  30047. * Instantiates an AssetContainer.
  30048. * @param scene The scene the AssetContainer belongs to.
  30049. */
  30050. function AssetContainer(scene) {
  30051. var _this = _super.call(this) || this;
  30052. _this.scene = scene;
  30053. _this["sounds"] = [];
  30054. _this["effectLayers"] = [];
  30055. _this["layers"] = [];
  30056. _this["lensFlareSystems"] = [];
  30057. _this["proceduralTextures"] = [];
  30058. return _this;
  30059. }
  30060. /**
  30061. * Adds all the assets from the container to the scene.
  30062. */
  30063. AssetContainer.prototype.addAllToScene = function () {
  30064. var _this = this;
  30065. this.cameras.forEach(function (o) {
  30066. _this.scene.addCamera(o);
  30067. });
  30068. this.lights.forEach(function (o) {
  30069. _this.scene.addLight(o);
  30070. });
  30071. this.meshes.forEach(function (o) {
  30072. _this.scene.addMesh(o);
  30073. });
  30074. this.skeletons.forEach(function (o) {
  30075. _this.scene.addSkeleton(o);
  30076. });
  30077. this.animations.forEach(function (o) {
  30078. _this.scene.addAnimation(o);
  30079. });
  30080. this.animationGroups.forEach(function (o) {
  30081. _this.scene.addAnimationGroup(o);
  30082. });
  30083. this.multiMaterials.forEach(function (o) {
  30084. _this.scene.addMultiMaterial(o);
  30085. });
  30086. this.materials.forEach(function (o) {
  30087. _this.scene.addMaterial(o);
  30088. });
  30089. this.morphTargetManagers.forEach(function (o) {
  30090. _this.scene.addMorphTargetManager(o);
  30091. });
  30092. this.geometries.forEach(function (o) {
  30093. _this.scene.addGeometry(o);
  30094. });
  30095. this.transformNodes.forEach(function (o) {
  30096. _this.scene.addTransformNode(o);
  30097. });
  30098. this.actionManagers.forEach(function (o) {
  30099. _this.scene.addActionManager(o);
  30100. });
  30101. this.textures.forEach(function (o) {
  30102. _this.scene.addTexture(o);
  30103. });
  30104. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30105. var component = _a[_i];
  30106. component.addFromContainer(this);
  30107. }
  30108. };
  30109. /**
  30110. * Removes all the assets in the container from the scene
  30111. */
  30112. AssetContainer.prototype.removeAllFromScene = function () {
  30113. var _this = this;
  30114. this.cameras.forEach(function (o) {
  30115. _this.scene.removeCamera(o);
  30116. });
  30117. this.lights.forEach(function (o) {
  30118. _this.scene.removeLight(o);
  30119. });
  30120. this.meshes.forEach(function (o) {
  30121. _this.scene.removeMesh(o);
  30122. });
  30123. this.skeletons.forEach(function (o) {
  30124. _this.scene.removeSkeleton(o);
  30125. });
  30126. this.animations.forEach(function (o) {
  30127. _this.scene.removeAnimation(o);
  30128. });
  30129. this.animationGroups.forEach(function (o) {
  30130. _this.scene.removeAnimationGroup(o);
  30131. });
  30132. this.multiMaterials.forEach(function (o) {
  30133. _this.scene.removeMultiMaterial(o);
  30134. });
  30135. this.materials.forEach(function (o) {
  30136. _this.scene.removeMaterial(o);
  30137. });
  30138. this.morphTargetManagers.forEach(function (o) {
  30139. _this.scene.removeMorphTargetManager(o);
  30140. });
  30141. this.geometries.forEach(function (o) {
  30142. _this.scene.removeGeometry(o);
  30143. });
  30144. this.transformNodes.forEach(function (o) {
  30145. _this.scene.removeTransformNode(o);
  30146. });
  30147. this.actionManagers.forEach(function (o) {
  30148. _this.scene.removeActionManager(o);
  30149. });
  30150. this.textures.forEach(function (o) {
  30151. _this.scene.removeTexture(o);
  30152. });
  30153. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30154. var component = _a[_i];
  30155. component.removeFromContainer(this);
  30156. }
  30157. };
  30158. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  30159. if (!sourceAssets) {
  30160. return;
  30161. }
  30162. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  30163. var asset = sourceAssets_1[_i];
  30164. var move = true;
  30165. if (keepAssets) {
  30166. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  30167. var keepAsset = keepAssets_1[_a];
  30168. if (asset === keepAsset) {
  30169. move = false;
  30170. break;
  30171. }
  30172. }
  30173. }
  30174. if (move) {
  30175. targetAssets.push(asset);
  30176. }
  30177. }
  30178. };
  30179. /**
  30180. * Removes all the assets contained in the scene and adds them to the container.
  30181. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  30182. */
  30183. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  30184. if (keepAssets === undefined) {
  30185. keepAssets = new KeepAssets();
  30186. }
  30187. for (var key in this) {
  30188. if (this.hasOwnProperty(key)) {
  30189. this[key] = this[key] || [];
  30190. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  30191. }
  30192. }
  30193. this.removeAllFromScene();
  30194. };
  30195. /**
  30196. * 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.
  30197. * @returns the root mesh
  30198. */
  30199. AssetContainer.prototype.createRootMesh = function () {
  30200. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  30201. this.meshes.forEach(function (m) {
  30202. if (!m.parent) {
  30203. rootMesh.addChild(m);
  30204. }
  30205. });
  30206. this.meshes.unshift(rootMesh);
  30207. return rootMesh;
  30208. };
  30209. return AssetContainer;
  30210. }(BABYLON.AbstractScene));
  30211. BABYLON.AssetContainer = AssetContainer;
  30212. })(BABYLON || (BABYLON = {}));
  30213. //# sourceMappingURL=babylon.assetContainer.js.map
  30214. var BABYLON;
  30215. (function (BABYLON) {
  30216. /**
  30217. * Class used to store data that will be store in GPU memory
  30218. */
  30219. var Buffer = /** @class */ (function () {
  30220. /**
  30221. * Constructor
  30222. * @param engine the engine
  30223. * @param data the data to use for this buffer
  30224. * @param updatable whether the data is updatable
  30225. * @param stride the stride (optional)
  30226. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30227. * @param instanced whether the buffer is instanced (optional)
  30228. * @param useBytes set to true if the stride in in bytes (optional)
  30229. */
  30230. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  30231. if (stride === void 0) { stride = 0; }
  30232. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  30233. if (instanced === void 0) { instanced = false; }
  30234. if (useBytes === void 0) { useBytes = false; }
  30235. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  30236. this._engine = engine.getScene().getEngine();
  30237. }
  30238. else {
  30239. this._engine = engine;
  30240. }
  30241. this._updatable = updatable;
  30242. this._instanced = instanced;
  30243. this._data = data;
  30244. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  30245. if (!postponeInternalCreation) { // by default
  30246. this.create();
  30247. }
  30248. }
  30249. /**
  30250. * Create a new VertexBuffer based on the current buffer
  30251. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30252. * @param offset defines offset in the buffer (0 by default)
  30253. * @param size defines the size in floats of attributes (position is 3 for instance)
  30254. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30255. * @param instanced defines if the vertex buffer contains indexed data
  30256. * @param useBytes defines if the offset and stride are in bytes
  30257. * @returns the new vertex buffer
  30258. */
  30259. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30260. if (useBytes === void 0) { useBytes = false; }
  30261. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30262. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30263. // a lot of these parameters are ignored as they are overriden by the buffer
  30264. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30265. };
  30266. // Properties
  30267. /**
  30268. * Gets a boolean indicating if the Buffer is updatable?
  30269. * @returns true if the buffer is updatable
  30270. */
  30271. Buffer.prototype.isUpdatable = function () {
  30272. return this._updatable;
  30273. };
  30274. /**
  30275. * Gets current buffer's data
  30276. * @returns a DataArray or null
  30277. */
  30278. Buffer.prototype.getData = function () {
  30279. return this._data;
  30280. };
  30281. /**
  30282. * Gets underlying native buffer
  30283. * @returns underlying native buffer
  30284. */
  30285. Buffer.prototype.getBuffer = function () {
  30286. return this._buffer;
  30287. };
  30288. /**
  30289. * Gets the stride in float32 units (i.e. byte stride / 4).
  30290. * May not be an integer if the byte stride is not divisible by 4.
  30291. * DEPRECATED. Use byteStride instead.
  30292. * @returns the stride in float32 units
  30293. */
  30294. Buffer.prototype.getStrideSize = function () {
  30295. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30296. };
  30297. // Methods
  30298. /**
  30299. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30300. * @param data defines the data to store
  30301. */
  30302. Buffer.prototype.create = function (data) {
  30303. if (data === void 0) { data = null; }
  30304. if (!data && this._buffer) {
  30305. return; // nothing to do
  30306. }
  30307. data = data || this._data;
  30308. if (!data) {
  30309. return;
  30310. }
  30311. if (!this._buffer) { // create buffer
  30312. if (this._updatable) {
  30313. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30314. this._data = data;
  30315. }
  30316. else {
  30317. this._buffer = this._engine.createVertexBuffer(data);
  30318. }
  30319. }
  30320. else if (this._updatable) { // update buffer
  30321. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30322. this._data = data;
  30323. }
  30324. };
  30325. /** @hidden */
  30326. Buffer.prototype._rebuild = function () {
  30327. this._buffer = null;
  30328. this.create(this._data);
  30329. };
  30330. /**
  30331. * Update current buffer data
  30332. * @param data defines the data to store
  30333. */
  30334. Buffer.prototype.update = function (data) {
  30335. this.create(data);
  30336. };
  30337. /**
  30338. * Updates the data directly.
  30339. * @param data the new data
  30340. * @param offset the new offset
  30341. * @param vertexCount the vertex count (optional)
  30342. * @param useBytes set to true if the offset is in bytes
  30343. */
  30344. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30345. if (useBytes === void 0) { useBytes = false; }
  30346. if (!this._buffer) {
  30347. return;
  30348. }
  30349. if (this._updatable) { // update buffer
  30350. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30351. this._data = null;
  30352. }
  30353. };
  30354. /**
  30355. * Release all resources
  30356. */
  30357. Buffer.prototype.dispose = function () {
  30358. if (!this._buffer) {
  30359. return;
  30360. }
  30361. if (this._engine._releaseBuffer(this._buffer)) {
  30362. this._buffer = null;
  30363. }
  30364. };
  30365. return Buffer;
  30366. }());
  30367. BABYLON.Buffer = Buffer;
  30368. })(BABYLON || (BABYLON = {}));
  30369. //# sourceMappingURL=babylon.buffer.js.map
  30370. var BABYLON;
  30371. (function (BABYLON) {
  30372. /**
  30373. * Specialized buffer used to store vertex data
  30374. */
  30375. var VertexBuffer = /** @class */ (function () {
  30376. /**
  30377. * Constructor
  30378. * @param engine the engine
  30379. * @param data the data to use for this vertex buffer
  30380. * @param kind the vertex buffer kind
  30381. * @param updatable whether the data is updatable
  30382. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30383. * @param stride the stride (optional)
  30384. * @param instanced whether the buffer is instanced (optional)
  30385. * @param offset the offset of the data (optional)
  30386. * @param size the number of components (optional)
  30387. * @param type the type of the component (optional)
  30388. * @param normalized whether the data contains normalized data (optional)
  30389. * @param useBytes set to true if stride and offset are in bytes (optional)
  30390. */
  30391. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30392. if (normalized === void 0) { normalized = false; }
  30393. if (useBytes === void 0) { useBytes = false; }
  30394. if (data instanceof BABYLON.Buffer) {
  30395. this._buffer = data;
  30396. this._ownsBuffer = false;
  30397. }
  30398. else {
  30399. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30400. this._ownsBuffer = true;
  30401. }
  30402. this._kind = kind;
  30403. if (type == undefined) {
  30404. var data_1 = this.getData();
  30405. this.type = VertexBuffer.FLOAT;
  30406. if (data_1 instanceof Int8Array) {
  30407. this.type = VertexBuffer.BYTE;
  30408. }
  30409. else if (data_1 instanceof Uint8Array) {
  30410. this.type = VertexBuffer.UNSIGNED_BYTE;
  30411. }
  30412. else if (data_1 instanceof Int16Array) {
  30413. this.type = VertexBuffer.SHORT;
  30414. }
  30415. else if (data_1 instanceof Uint16Array) {
  30416. this.type = VertexBuffer.UNSIGNED_SHORT;
  30417. }
  30418. else if (data_1 instanceof Int32Array) {
  30419. this.type = VertexBuffer.INT;
  30420. }
  30421. else if (data_1 instanceof Uint32Array) {
  30422. this.type = VertexBuffer.UNSIGNED_INT;
  30423. }
  30424. }
  30425. else {
  30426. this.type = type;
  30427. }
  30428. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30429. if (useBytes) {
  30430. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30431. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30432. this.byteOffset = offset || 0;
  30433. }
  30434. else {
  30435. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30436. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30437. this.byteOffset = (offset || 0) * typeByteLength;
  30438. }
  30439. this.normalized = normalized;
  30440. this._instanced = instanced !== undefined ? instanced : false;
  30441. this._instanceDivisor = instanced ? 1 : 0;
  30442. }
  30443. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30444. /**
  30445. * Gets or sets the instance divisor when in instanced mode
  30446. */
  30447. get: function () {
  30448. return this._instanceDivisor;
  30449. },
  30450. set: function (value) {
  30451. this._instanceDivisor = value;
  30452. if (value == 0) {
  30453. this._instanced = false;
  30454. }
  30455. else {
  30456. this._instanced = true;
  30457. }
  30458. },
  30459. enumerable: true,
  30460. configurable: true
  30461. });
  30462. /** @hidden */
  30463. VertexBuffer.prototype._rebuild = function () {
  30464. if (!this._buffer) {
  30465. return;
  30466. }
  30467. this._buffer._rebuild();
  30468. };
  30469. /**
  30470. * Returns the kind of the VertexBuffer (string)
  30471. * @returns a string
  30472. */
  30473. VertexBuffer.prototype.getKind = function () {
  30474. return this._kind;
  30475. };
  30476. // Properties
  30477. /**
  30478. * Gets a boolean indicating if the VertexBuffer is updatable?
  30479. * @returns true if the buffer is updatable
  30480. */
  30481. VertexBuffer.prototype.isUpdatable = function () {
  30482. return this._buffer.isUpdatable();
  30483. };
  30484. /**
  30485. * Gets current buffer's data
  30486. * @returns a DataArray or null
  30487. */
  30488. VertexBuffer.prototype.getData = function () {
  30489. return this._buffer.getData();
  30490. };
  30491. /**
  30492. * Gets underlying native buffer
  30493. * @returns underlying native buffer
  30494. */
  30495. VertexBuffer.prototype.getBuffer = function () {
  30496. return this._buffer.getBuffer();
  30497. };
  30498. /**
  30499. * Gets the stride in float32 units (i.e. byte stride / 4).
  30500. * May not be an integer if the byte stride is not divisible by 4.
  30501. * DEPRECATED. Use byteStride instead.
  30502. * @returns the stride in float32 units
  30503. */
  30504. VertexBuffer.prototype.getStrideSize = function () {
  30505. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30506. };
  30507. /**
  30508. * Returns the offset as a multiple of the type byte length.
  30509. * DEPRECATED. Use byteOffset instead.
  30510. * @returns the offset in bytes
  30511. */
  30512. VertexBuffer.prototype.getOffset = function () {
  30513. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30514. };
  30515. /**
  30516. * Returns the number of components per vertex attribute (integer)
  30517. * @returns the size in float
  30518. */
  30519. VertexBuffer.prototype.getSize = function () {
  30520. return this._size;
  30521. };
  30522. /**
  30523. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30524. * @returns true if this buffer is instanced
  30525. */
  30526. VertexBuffer.prototype.getIsInstanced = function () {
  30527. return this._instanced;
  30528. };
  30529. /**
  30530. * Returns the instancing divisor, zero for non-instanced (integer).
  30531. * @returns a number
  30532. */
  30533. VertexBuffer.prototype.getInstanceDivisor = function () {
  30534. return this._instanceDivisor;
  30535. };
  30536. // Methods
  30537. /**
  30538. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30539. * @param data defines the data to store
  30540. */
  30541. VertexBuffer.prototype.create = function (data) {
  30542. this._buffer.create(data);
  30543. };
  30544. /**
  30545. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30546. * This function will create a new buffer if the current one is not updatable
  30547. * @param data defines the data to store
  30548. */
  30549. VertexBuffer.prototype.update = function (data) {
  30550. this._buffer.update(data);
  30551. };
  30552. /**
  30553. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30554. * Returns the directly updated WebGLBuffer.
  30555. * @param data the new data
  30556. * @param offset the new offset
  30557. * @param useBytes set to true if the offset is in bytes
  30558. */
  30559. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30560. if (useBytes === void 0) { useBytes = false; }
  30561. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30562. };
  30563. /**
  30564. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30565. */
  30566. VertexBuffer.prototype.dispose = function () {
  30567. if (this._ownsBuffer) {
  30568. this._buffer.dispose();
  30569. }
  30570. };
  30571. /**
  30572. * Enumerates each value of this vertex buffer as numbers.
  30573. * @param count the number of values to enumerate
  30574. * @param callback the callback function called for each value
  30575. */
  30576. VertexBuffer.prototype.forEach = function (count, callback) {
  30577. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30578. };
  30579. /**
  30580. * Deduces the stride given a kind.
  30581. * @param kind The kind string to deduce
  30582. * @returns The deduced stride
  30583. */
  30584. VertexBuffer.DeduceStride = function (kind) {
  30585. switch (kind) {
  30586. case VertexBuffer.UVKind:
  30587. case VertexBuffer.UV2Kind:
  30588. case VertexBuffer.UV3Kind:
  30589. case VertexBuffer.UV4Kind:
  30590. case VertexBuffer.UV5Kind:
  30591. case VertexBuffer.UV6Kind:
  30592. return 2;
  30593. case VertexBuffer.NormalKind:
  30594. case VertexBuffer.PositionKind:
  30595. return 3;
  30596. case VertexBuffer.ColorKind:
  30597. case VertexBuffer.MatricesIndicesKind:
  30598. case VertexBuffer.MatricesIndicesExtraKind:
  30599. case VertexBuffer.MatricesWeightsKind:
  30600. case VertexBuffer.MatricesWeightsExtraKind:
  30601. case VertexBuffer.TangentKind:
  30602. return 4;
  30603. default:
  30604. throw new Error("Invalid kind '" + kind + "'");
  30605. }
  30606. };
  30607. /**
  30608. * Gets the byte length of the given type.
  30609. * @param type the type
  30610. * @returns the number of bytes
  30611. */
  30612. VertexBuffer.GetTypeByteLength = function (type) {
  30613. switch (type) {
  30614. case VertexBuffer.BYTE:
  30615. case VertexBuffer.UNSIGNED_BYTE:
  30616. return 1;
  30617. case VertexBuffer.SHORT:
  30618. case VertexBuffer.UNSIGNED_SHORT:
  30619. return 2;
  30620. case VertexBuffer.INT:
  30621. case VertexBuffer.FLOAT:
  30622. return 4;
  30623. default:
  30624. throw new Error("Invalid type '" + type + "'");
  30625. }
  30626. };
  30627. /**
  30628. * Enumerates each value of the given parameters as numbers.
  30629. * @param data the data to enumerate
  30630. * @param byteOffset the byte offset of the data
  30631. * @param byteStride the byte stride of the data
  30632. * @param componentCount the number of components per element
  30633. * @param componentType the type of the component
  30634. * @param count the total number of components
  30635. * @param normalized whether the data is normalized
  30636. * @param callback the callback function called for each value
  30637. */
  30638. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30639. if (data instanceof Array) {
  30640. var offset = byteOffset / 4;
  30641. var stride = byteStride / 4;
  30642. for (var index = 0; index < count; index += componentCount) {
  30643. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30644. callback(data[offset + componentIndex], index + componentIndex);
  30645. }
  30646. offset += stride;
  30647. }
  30648. }
  30649. else {
  30650. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30651. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30652. for (var index = 0; index < count; index += componentCount) {
  30653. var componentByteOffset = byteOffset;
  30654. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30655. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30656. callback(value, index + componentIndex);
  30657. componentByteOffset += componentByteLength;
  30658. }
  30659. byteOffset += byteStride;
  30660. }
  30661. }
  30662. };
  30663. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30664. switch (type) {
  30665. case VertexBuffer.BYTE: {
  30666. var value = dataView.getInt8(byteOffset);
  30667. if (normalized) {
  30668. value = Math.max(value / 127, -1);
  30669. }
  30670. return value;
  30671. }
  30672. case VertexBuffer.UNSIGNED_BYTE: {
  30673. var value = dataView.getUint8(byteOffset);
  30674. if (normalized) {
  30675. value = value / 255;
  30676. }
  30677. return value;
  30678. }
  30679. case VertexBuffer.SHORT: {
  30680. var value = dataView.getInt16(byteOffset, true);
  30681. if (normalized) {
  30682. value = Math.max(value / 16383, -1);
  30683. }
  30684. return value;
  30685. }
  30686. case VertexBuffer.UNSIGNED_SHORT: {
  30687. var value = dataView.getUint16(byteOffset, true);
  30688. if (normalized) {
  30689. value = value / 65535;
  30690. }
  30691. return value;
  30692. }
  30693. case VertexBuffer.FLOAT: {
  30694. return dataView.getFloat32(byteOffset, true);
  30695. }
  30696. default: {
  30697. throw new Error("Invalid component type " + type);
  30698. }
  30699. }
  30700. };
  30701. /**
  30702. * The byte type.
  30703. */
  30704. VertexBuffer.BYTE = 5120;
  30705. /**
  30706. * The unsigned byte type.
  30707. */
  30708. VertexBuffer.UNSIGNED_BYTE = 5121;
  30709. /**
  30710. * The short type.
  30711. */
  30712. VertexBuffer.SHORT = 5122;
  30713. /**
  30714. * The unsigned short type.
  30715. */
  30716. VertexBuffer.UNSIGNED_SHORT = 5123;
  30717. /**
  30718. * The integer type.
  30719. */
  30720. VertexBuffer.INT = 5124;
  30721. /**
  30722. * The unsigned integer type.
  30723. */
  30724. VertexBuffer.UNSIGNED_INT = 5125;
  30725. /**
  30726. * The float type.
  30727. */
  30728. VertexBuffer.FLOAT = 5126;
  30729. // Enums
  30730. /**
  30731. * Positions
  30732. */
  30733. VertexBuffer.PositionKind = "position";
  30734. /**
  30735. * Normals
  30736. */
  30737. VertexBuffer.NormalKind = "normal";
  30738. /**
  30739. * Tangents
  30740. */
  30741. VertexBuffer.TangentKind = "tangent";
  30742. /**
  30743. * Texture coordinates
  30744. */
  30745. VertexBuffer.UVKind = "uv";
  30746. /**
  30747. * Texture coordinates 2
  30748. */
  30749. VertexBuffer.UV2Kind = "uv2";
  30750. /**
  30751. * Texture coordinates 3
  30752. */
  30753. VertexBuffer.UV3Kind = "uv3";
  30754. /**
  30755. * Texture coordinates 4
  30756. */
  30757. VertexBuffer.UV4Kind = "uv4";
  30758. /**
  30759. * Texture coordinates 5
  30760. */
  30761. VertexBuffer.UV5Kind = "uv5";
  30762. /**
  30763. * Texture coordinates 6
  30764. */
  30765. VertexBuffer.UV6Kind = "uv6";
  30766. /**
  30767. * Colors
  30768. */
  30769. VertexBuffer.ColorKind = "color";
  30770. /**
  30771. * Matrix indices (for bones)
  30772. */
  30773. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30774. /**
  30775. * Matrix weights (for bones)
  30776. */
  30777. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30778. /**
  30779. * Additional matrix indices (for bones)
  30780. */
  30781. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30782. /**
  30783. * Additional matrix weights (for bones)
  30784. */
  30785. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30786. return VertexBuffer;
  30787. }());
  30788. BABYLON.VertexBuffer = VertexBuffer;
  30789. })(BABYLON || (BABYLON = {}));
  30790. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30791. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30792. var BABYLON;
  30793. (function (BABYLON) {
  30794. /**
  30795. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30796. */
  30797. var DummyInternalTextureTracker = /** @class */ (function () {
  30798. function DummyInternalTextureTracker() {
  30799. /**
  30800. * Gets or set the previous tracker in the list
  30801. */
  30802. this.previous = null;
  30803. /**
  30804. * Gets or set the next tracker in the list
  30805. */
  30806. this.next = null;
  30807. }
  30808. return DummyInternalTextureTracker;
  30809. }());
  30810. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30811. })(BABYLON || (BABYLON = {}));
  30812. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30813. var BABYLON;
  30814. (function (BABYLON) {
  30815. /**
  30816. * Class used to store data associated with WebGL texture data for the engine
  30817. * This class should not be used directly
  30818. */
  30819. var InternalTexture = /** @class */ (function () {
  30820. /**
  30821. * Creates a new InternalTexture
  30822. * @param engine defines the engine to use
  30823. * @param dataSource defines the type of data that will be used
  30824. * @param delayAllocation if the texture allocation should be delayed (default: false)
  30825. */
  30826. function InternalTexture(engine, dataSource, delayAllocation) {
  30827. if (delayAllocation === void 0) { delayAllocation = false; }
  30828. /**
  30829. * Observable called when the texture is loaded
  30830. */
  30831. this.onLoadedObservable = new BABYLON.Observable();
  30832. /**
  30833. * Gets or set the previous tracker in the list
  30834. */
  30835. this.previous = null;
  30836. /**
  30837. * Gets or set the next tracker in the list
  30838. */
  30839. this.next = null;
  30840. // Private
  30841. /** @hidden */
  30842. this._initialSlot = -1;
  30843. /** @hidden */
  30844. this._designatedSlot = -1;
  30845. /** @hidden */
  30846. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30847. /** @hidden */
  30848. this._comparisonFunction = 0;
  30849. /** @hidden */
  30850. this._sphericalPolynomial = null;
  30851. /** @hidden */
  30852. this._lodGenerationScale = 0;
  30853. /** @hidden */
  30854. this._lodGenerationOffset = 0;
  30855. /** @hidden */
  30856. this._isRGBD = false;
  30857. /** @hidden */
  30858. this._references = 1;
  30859. this._engine = engine;
  30860. this._dataSource = dataSource;
  30861. if (!delayAllocation) {
  30862. this._webGLTexture = engine._createTexture();
  30863. }
  30864. }
  30865. /**
  30866. * Gets the Engine the texture belongs to.
  30867. * @returns The babylon engine
  30868. */
  30869. InternalTexture.prototype.getEngine = function () {
  30870. return this._engine;
  30871. };
  30872. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30873. /**
  30874. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30875. */
  30876. get: function () {
  30877. return this._dataSource;
  30878. },
  30879. enumerable: true,
  30880. configurable: true
  30881. });
  30882. /**
  30883. * Increments the number of references (ie. the number of Texture that point to it)
  30884. */
  30885. InternalTexture.prototype.incrementReferences = function () {
  30886. this._references++;
  30887. };
  30888. /**
  30889. * Change the size of the texture (not the size of the content)
  30890. * @param width defines the new width
  30891. * @param height defines the new height
  30892. * @param depth defines the new depth (1 by default)
  30893. */
  30894. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30895. if (depth === void 0) { depth = 1; }
  30896. this.width = width;
  30897. this.height = height;
  30898. this.depth = depth;
  30899. this.baseWidth = width;
  30900. this.baseHeight = height;
  30901. this.baseDepth = depth;
  30902. this._size = width * height * depth;
  30903. };
  30904. /** @hidden */
  30905. InternalTexture.prototype._rebuild = function () {
  30906. var _this = this;
  30907. var proxy;
  30908. this.isReady = false;
  30909. this._cachedCoordinatesMode = null;
  30910. this._cachedWrapU = null;
  30911. this._cachedWrapV = null;
  30912. this._cachedAnisotropicFilteringLevel = null;
  30913. switch (this._dataSource) {
  30914. case InternalTexture.DATASOURCE_TEMP:
  30915. return;
  30916. case InternalTexture.DATASOURCE_URL:
  30917. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30918. _this.isReady = true;
  30919. }, null, this._buffer, undefined, this.format);
  30920. proxy._swapAndDie(this);
  30921. return;
  30922. case InternalTexture.DATASOURCE_RAW:
  30923. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30924. proxy._swapAndDie(this);
  30925. this.isReady = true;
  30926. return;
  30927. case InternalTexture.DATASOURCE_RAW3D:
  30928. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30929. proxy._swapAndDie(this);
  30930. this.isReady = true;
  30931. return;
  30932. case InternalTexture.DATASOURCE_DYNAMIC:
  30933. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30934. proxy._swapAndDie(this);
  30935. // The engine will make sure to update content so no need to flag it as isReady = true
  30936. return;
  30937. case InternalTexture.DATASOURCE_RENDERTARGET:
  30938. var options = new BABYLON.RenderTargetCreationOptions();
  30939. options.generateDepthBuffer = this._generateDepthBuffer;
  30940. options.generateMipMaps = this.generateMipMaps;
  30941. options.generateStencilBuffer = this._generateStencilBuffer;
  30942. options.samplingMode = this.samplingMode;
  30943. options.type = this.type;
  30944. if (this.isCube) {
  30945. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30946. }
  30947. else {
  30948. var size = {
  30949. width: this.width,
  30950. height: this.height
  30951. };
  30952. proxy = this._engine.createRenderTargetTexture(size, options);
  30953. }
  30954. proxy._swapAndDie(this);
  30955. this.isReady = true;
  30956. return;
  30957. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30958. var depthTextureOptions = {
  30959. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30960. comparisonFunction: this._comparisonFunction,
  30961. generateStencil: this._generateStencilBuffer,
  30962. isCube: this.isCube
  30963. };
  30964. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30965. proxy._swapAndDie(this);
  30966. this.isReady = true;
  30967. return;
  30968. case InternalTexture.DATASOURCE_CUBE:
  30969. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30970. _this.isReady = true;
  30971. }, null, this.format, this._extension);
  30972. proxy._swapAndDie(this);
  30973. return;
  30974. case InternalTexture.DATASOURCE_CUBERAW:
  30975. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30976. proxy._swapAndDie(this);
  30977. this.isReady = true;
  30978. return;
  30979. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30980. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30981. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30982. _this.isReady = true;
  30983. });
  30984. proxy._swapAndDie(this);
  30985. return;
  30986. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30987. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30988. if (proxy) {
  30989. proxy._swapAndDie(_this);
  30990. }
  30991. _this.isReady = true;
  30992. }, null, this.format, this._extension);
  30993. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30994. return;
  30995. }
  30996. };
  30997. /** @hidden */
  30998. InternalTexture.prototype._swapAndDie = function (target) {
  30999. target._webGLTexture = this._webGLTexture;
  31000. if (this._framebuffer) {
  31001. target._framebuffer = this._framebuffer;
  31002. }
  31003. if (this._depthStencilBuffer) {
  31004. target._depthStencilBuffer = this._depthStencilBuffer;
  31005. }
  31006. if (this._lodTextureHigh) {
  31007. if (target._lodTextureHigh) {
  31008. target._lodTextureHigh.dispose();
  31009. }
  31010. target._lodTextureHigh = this._lodTextureHigh;
  31011. }
  31012. if (this._lodTextureMid) {
  31013. if (target._lodTextureMid) {
  31014. target._lodTextureMid.dispose();
  31015. }
  31016. target._lodTextureMid = this._lodTextureMid;
  31017. }
  31018. if (this._lodTextureLow) {
  31019. if (target._lodTextureLow) {
  31020. target._lodTextureLow.dispose();
  31021. }
  31022. target._lodTextureLow = this._lodTextureLow;
  31023. }
  31024. var cache = this._engine.getLoadedTexturesCache();
  31025. var index = cache.indexOf(this);
  31026. if (index !== -1) {
  31027. cache.splice(index, 1);
  31028. }
  31029. };
  31030. /**
  31031. * Dispose the current allocated resources
  31032. */
  31033. InternalTexture.prototype.dispose = function () {
  31034. if (!this._webGLTexture) {
  31035. return;
  31036. }
  31037. this._references--;
  31038. if (this._references === 0) {
  31039. this._engine._releaseTexture(this);
  31040. this._webGLTexture = null;
  31041. this.previous = null;
  31042. this.next = null;
  31043. }
  31044. };
  31045. /**
  31046. * The source of the texture data is unknown
  31047. */
  31048. InternalTexture.DATASOURCE_UNKNOWN = 0;
  31049. /**
  31050. * Texture data comes from an URL
  31051. */
  31052. InternalTexture.DATASOURCE_URL = 1;
  31053. /**
  31054. * Texture data is only used for temporary storage
  31055. */
  31056. InternalTexture.DATASOURCE_TEMP = 2;
  31057. /**
  31058. * Texture data comes from raw data (ArrayBuffer)
  31059. */
  31060. InternalTexture.DATASOURCE_RAW = 3;
  31061. /**
  31062. * Texture content is dynamic (video or dynamic texture)
  31063. */
  31064. InternalTexture.DATASOURCE_DYNAMIC = 4;
  31065. /**
  31066. * Texture content is generated by rendering to it
  31067. */
  31068. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  31069. /**
  31070. * Texture content is part of a multi render target process
  31071. */
  31072. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  31073. /**
  31074. * Texture data comes from a cube data file
  31075. */
  31076. InternalTexture.DATASOURCE_CUBE = 7;
  31077. /**
  31078. * Texture data comes from a raw cube data
  31079. */
  31080. InternalTexture.DATASOURCE_CUBERAW = 8;
  31081. /**
  31082. * Texture data come from a prefiltered cube data file
  31083. */
  31084. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  31085. /**
  31086. * Texture content is raw 3D data
  31087. */
  31088. InternalTexture.DATASOURCE_RAW3D = 10;
  31089. /**
  31090. * Texture content is a depth texture
  31091. */
  31092. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  31093. /**
  31094. * Texture data comes from a raw cube data encoded with RGBD
  31095. */
  31096. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  31097. return InternalTexture;
  31098. }());
  31099. BABYLON.InternalTexture = InternalTexture;
  31100. })(BABYLON || (BABYLON = {}));
  31101. //# sourceMappingURL=babylon.internalTexture.js.map
  31102. var BABYLON;
  31103. (function (BABYLON) {
  31104. /**
  31105. * Base class of all the textures in babylon.
  31106. * It groups all the common properties the materials, post process, lights... might need
  31107. * in order to make a correct use of the texture.
  31108. */
  31109. var BaseTexture = /** @class */ (function () {
  31110. /**
  31111. * Instantiates a new BaseTexture.
  31112. * Base class of all the textures in babylon.
  31113. * It groups all the common properties the materials, post process, lights... might need
  31114. * in order to make a correct use of the texture.
  31115. * @param scene Define the scene the texture blongs to
  31116. */
  31117. function BaseTexture(scene) {
  31118. this._hasAlpha = false;
  31119. /**
  31120. * Defines if the alpha value should be determined via the rgb values.
  31121. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  31122. */
  31123. this.getAlphaFromRGB = false;
  31124. /**
  31125. * Intensity or strength of the texture.
  31126. * It is commonly used by materials to fine tune the intensity of the texture
  31127. */
  31128. this.level = 1;
  31129. /**
  31130. * Define the UV chanel to use starting from 0 and defaulting to 0.
  31131. * This is part of the texture as textures usually maps to one uv set.
  31132. */
  31133. this.coordinatesIndex = 0;
  31134. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  31135. /**
  31136. * | Value | Type | Description |
  31137. * | ----- | ------------------ | ----------- |
  31138. * | 0 | CLAMP_ADDRESSMODE | |
  31139. * | 1 | WRAP_ADDRESSMODE | |
  31140. * | 2 | MIRROR_ADDRESSMODE | |
  31141. */
  31142. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31143. /**
  31144. * | Value | Type | Description |
  31145. * | ----- | ------------------ | ----------- |
  31146. * | 0 | CLAMP_ADDRESSMODE | |
  31147. * | 1 | WRAP_ADDRESSMODE | |
  31148. * | 2 | MIRROR_ADDRESSMODE | |
  31149. */
  31150. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31151. /**
  31152. * | Value | Type | Description |
  31153. * | ----- | ------------------ | ----------- |
  31154. * | 0 | CLAMP_ADDRESSMODE | |
  31155. * | 1 | WRAP_ADDRESSMODE | |
  31156. * | 2 | MIRROR_ADDRESSMODE | |
  31157. */
  31158. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  31159. /**
  31160. * With compliant hardware and browser (supporting anisotropic filtering)
  31161. * this defines the level of anisotropic filtering in the texture.
  31162. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  31163. */
  31164. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  31165. /**
  31166. * Define if the texture is a cube texture or if false a 2d texture.
  31167. */
  31168. this.isCube = false;
  31169. /**
  31170. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  31171. */
  31172. this.is3D = false;
  31173. /**
  31174. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  31175. * HDR texture are usually stored in linear space.
  31176. * This only impacts the PBR and Background materials
  31177. */
  31178. this.gammaSpace = true;
  31179. /**
  31180. * Is Z inverted in the texture (useful in a cube texture).
  31181. */
  31182. this.invertZ = false;
  31183. /**
  31184. * @hidden
  31185. */
  31186. this.lodLevelInAlpha = false;
  31187. /**
  31188. * Define if the texture is a render target.
  31189. */
  31190. this.isRenderTarget = false;
  31191. /**
  31192. * Define the list of animation attached to the texture.
  31193. */
  31194. this.animations = new Array();
  31195. /**
  31196. * An event triggered when the texture is disposed.
  31197. */
  31198. this.onDisposeObservable = new BABYLON.Observable();
  31199. /**
  31200. * Define the current state of the loading sequence when in delayed load mode.
  31201. */
  31202. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31203. this._cachedSize = BABYLON.Size.Zero();
  31204. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31205. if (this._scene) {
  31206. this._scene.textures.push(this);
  31207. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  31208. }
  31209. this._uid = null;
  31210. }
  31211. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  31212. get: function () {
  31213. return this._hasAlpha;
  31214. },
  31215. /**
  31216. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  31217. */
  31218. set: function (value) {
  31219. if (this._hasAlpha === value) {
  31220. return;
  31221. }
  31222. this._hasAlpha = value;
  31223. if (this._scene) {
  31224. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  31225. }
  31226. },
  31227. enumerable: true,
  31228. configurable: true
  31229. });
  31230. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  31231. get: function () {
  31232. return this._coordinatesMode;
  31233. },
  31234. /**
  31235. * How a texture is mapped.
  31236. *
  31237. * | Value | Type | Description |
  31238. * | ----- | ----------------------------------- | ----------- |
  31239. * | 0 | EXPLICIT_MODE | |
  31240. * | 1 | SPHERICAL_MODE | |
  31241. * | 2 | PLANAR_MODE | |
  31242. * | 3 | CUBIC_MODE | |
  31243. * | 4 | PROJECTION_MODE | |
  31244. * | 5 | SKYBOX_MODE | |
  31245. * | 6 | INVCUBIC_MODE | |
  31246. * | 7 | EQUIRECTANGULAR_MODE | |
  31247. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  31248. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  31249. */
  31250. set: function (value) {
  31251. if (this._coordinatesMode === value) {
  31252. return;
  31253. }
  31254. this._coordinatesMode = value;
  31255. if (this._scene) {
  31256. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31257. }
  31258. },
  31259. enumerable: true,
  31260. configurable: true
  31261. });
  31262. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31263. /**
  31264. * Gets whether or not the texture contains RGBD data.
  31265. */
  31266. get: function () {
  31267. return this._texture != null && this._texture._isRGBD;
  31268. },
  31269. enumerable: true,
  31270. configurable: true
  31271. });
  31272. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31273. /**
  31274. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31275. */
  31276. get: function () {
  31277. if (this._texture) {
  31278. return this._texture._lodGenerationOffset;
  31279. }
  31280. return 0.0;
  31281. },
  31282. set: function (value) {
  31283. if (this._texture) {
  31284. this._texture._lodGenerationOffset = value;
  31285. }
  31286. },
  31287. enumerable: true,
  31288. configurable: true
  31289. });
  31290. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31291. /**
  31292. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31293. */
  31294. get: function () {
  31295. if (this._texture) {
  31296. return this._texture._lodGenerationScale;
  31297. }
  31298. return 0.0;
  31299. },
  31300. set: function (value) {
  31301. if (this._texture) {
  31302. this._texture._lodGenerationScale = value;
  31303. }
  31304. },
  31305. enumerable: true,
  31306. configurable: true
  31307. });
  31308. Object.defineProperty(BaseTexture.prototype, "uid", {
  31309. /**
  31310. * Define the unique id of the texture in the scene.
  31311. */
  31312. get: function () {
  31313. if (!this._uid) {
  31314. this._uid = BABYLON.Tools.RandomId();
  31315. }
  31316. return this._uid;
  31317. },
  31318. enumerable: true,
  31319. configurable: true
  31320. });
  31321. /**
  31322. * Return a string representation of the texture.
  31323. * @returns the texture as a string
  31324. */
  31325. BaseTexture.prototype.toString = function () {
  31326. return this.name;
  31327. };
  31328. /**
  31329. * Get the class name of the texture.
  31330. * @returns "BaseTexture"
  31331. */
  31332. BaseTexture.prototype.getClassName = function () {
  31333. return "BaseTexture";
  31334. };
  31335. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31336. /**
  31337. * Callback triggered when the texture has been disposed.
  31338. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31339. */
  31340. set: function (callback) {
  31341. if (this._onDisposeObserver) {
  31342. this.onDisposeObservable.remove(this._onDisposeObserver);
  31343. }
  31344. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31345. },
  31346. enumerable: true,
  31347. configurable: true
  31348. });
  31349. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31350. /**
  31351. * Define if the texture is preventinga material to render or not.
  31352. * If not and the texture is not ready, the engine will use a default black texture instead.
  31353. */
  31354. get: function () {
  31355. return true;
  31356. },
  31357. enumerable: true,
  31358. configurable: true
  31359. });
  31360. /**
  31361. * Get the scene the texture belongs to.
  31362. * @returns the scene or null if undefined
  31363. */
  31364. BaseTexture.prototype.getScene = function () {
  31365. return this._scene;
  31366. };
  31367. /**
  31368. * Get the texture transform matrix used to offset tile the texture for istance.
  31369. * @returns the transformation matrix
  31370. */
  31371. BaseTexture.prototype.getTextureMatrix = function () {
  31372. return BABYLON.Matrix.IdentityReadOnly;
  31373. };
  31374. /**
  31375. * Get the texture reflection matrix used to rotate/transform the reflection.
  31376. * @returns the reflection matrix
  31377. */
  31378. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31379. return BABYLON.Matrix.IdentityReadOnly;
  31380. };
  31381. /**
  31382. * Get the underlying lower level texture from Babylon.
  31383. * @returns the insternal texture
  31384. */
  31385. BaseTexture.prototype.getInternalTexture = function () {
  31386. return this._texture;
  31387. };
  31388. /**
  31389. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31390. * @returns true if ready or not blocking
  31391. */
  31392. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31393. return !this.isBlocking || this.isReady();
  31394. };
  31395. /**
  31396. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31397. * @returns true if fully ready
  31398. */
  31399. BaseTexture.prototype.isReady = function () {
  31400. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31401. this.delayLoad();
  31402. return false;
  31403. }
  31404. if (this._texture) {
  31405. return this._texture.isReady;
  31406. }
  31407. return false;
  31408. };
  31409. /**
  31410. * Get the size of the texture.
  31411. * @returns the texture size.
  31412. */
  31413. BaseTexture.prototype.getSize = function () {
  31414. if (this._texture) {
  31415. if (this._texture.width) {
  31416. this._cachedSize.width = this._texture.width;
  31417. this._cachedSize.height = this._texture.height;
  31418. return this._cachedSize;
  31419. }
  31420. if (this._texture._size) {
  31421. this._cachedSize.width = this._texture._size;
  31422. this._cachedSize.height = this._texture._size;
  31423. return this._cachedSize;
  31424. }
  31425. }
  31426. return this._cachedSize;
  31427. };
  31428. /**
  31429. * Get the base size of the texture.
  31430. * It can be different from the size if the texture has been resized for POT for instance
  31431. * @returns the base size
  31432. */
  31433. BaseTexture.prototype.getBaseSize = function () {
  31434. if (!this.isReady() || !this._texture) {
  31435. return BABYLON.Size.Zero();
  31436. }
  31437. if (this._texture._size) {
  31438. return new BABYLON.Size(this._texture._size, this._texture._size);
  31439. }
  31440. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31441. };
  31442. /**
  31443. * Scales the texture if is `canRescale()`
  31444. * @param ratio the resize factor we want to use to rescale
  31445. */
  31446. BaseTexture.prototype.scale = function (ratio) {
  31447. };
  31448. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31449. /**
  31450. * Get if the texture can rescale.
  31451. */
  31452. get: function () {
  31453. return false;
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. /** @hidden */
  31459. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31460. if (!this._scene) {
  31461. return null;
  31462. }
  31463. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31464. for (var index = 0; index < texturesCache.length; index++) {
  31465. var texturesCacheEntry = texturesCache[index];
  31466. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31467. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31468. texturesCacheEntry.incrementReferences();
  31469. return texturesCacheEntry;
  31470. }
  31471. }
  31472. }
  31473. return null;
  31474. };
  31475. /** @hidden */
  31476. BaseTexture.prototype._rebuild = function () {
  31477. };
  31478. /**
  31479. * Triggers the load sequence in delayed load mode.
  31480. */
  31481. BaseTexture.prototype.delayLoad = function () {
  31482. };
  31483. /**
  31484. * Clones the texture.
  31485. * @returns the cloned texture
  31486. */
  31487. BaseTexture.prototype.clone = function () {
  31488. return null;
  31489. };
  31490. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31491. /**
  31492. * Get the texture underlying type (INT, FLOAT...)
  31493. */
  31494. get: function () {
  31495. if (!this._texture) {
  31496. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31497. }
  31498. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31499. },
  31500. enumerable: true,
  31501. configurable: true
  31502. });
  31503. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31504. /**
  31505. * Get the texture underlying format (RGB, RGBA...)
  31506. */
  31507. get: function () {
  31508. if (!this._texture) {
  31509. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31510. }
  31511. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. /**
  31517. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31518. * This will returns an RGBA array buffer containing either in values (0-255) or
  31519. * float values (0-1) depending of the underlying buffer type.
  31520. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31521. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31522. * @param buffer defines a user defined buffer to fill with data (can be null)
  31523. * @returns The Array buffer containing the pixels data.
  31524. */
  31525. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31526. if (faceIndex === void 0) { faceIndex = 0; }
  31527. if (level === void 0) { level = 0; }
  31528. if (buffer === void 0) { buffer = null; }
  31529. if (!this._texture) {
  31530. return null;
  31531. }
  31532. var size = this.getSize();
  31533. var width = size.width;
  31534. var height = size.height;
  31535. var scene = this.getScene();
  31536. if (!scene) {
  31537. return null;
  31538. }
  31539. var engine = scene.getEngine();
  31540. if (level != 0) {
  31541. width = width / Math.pow(2, level);
  31542. height = height / Math.pow(2, level);
  31543. width = Math.round(width);
  31544. height = Math.round(height);
  31545. }
  31546. if (this._texture.isCube) {
  31547. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31548. }
  31549. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31550. };
  31551. /**
  31552. * Release and destroy the underlying lower level texture aka internalTexture.
  31553. */
  31554. BaseTexture.prototype.releaseInternalTexture = function () {
  31555. if (this._texture) {
  31556. this._texture.dispose();
  31557. this._texture = null;
  31558. }
  31559. };
  31560. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31561. /**
  31562. * Get the polynomial representation of the texture data.
  31563. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31564. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31565. */
  31566. get: function () {
  31567. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31568. return null;
  31569. }
  31570. if (!this._texture._sphericalPolynomial) {
  31571. this._texture._sphericalPolynomial =
  31572. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31573. }
  31574. return this._texture._sphericalPolynomial;
  31575. },
  31576. set: function (value) {
  31577. if (this._texture) {
  31578. this._texture._sphericalPolynomial = value;
  31579. }
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31585. /** @hidden */
  31586. get: function () {
  31587. if (this._texture) {
  31588. return this._texture._lodTextureHigh;
  31589. }
  31590. return null;
  31591. },
  31592. enumerable: true,
  31593. configurable: true
  31594. });
  31595. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31596. /** @hidden */
  31597. get: function () {
  31598. if (this._texture) {
  31599. return this._texture._lodTextureMid;
  31600. }
  31601. return null;
  31602. },
  31603. enumerable: true,
  31604. configurable: true
  31605. });
  31606. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31607. /** @hidden */
  31608. get: function () {
  31609. if (this._texture) {
  31610. return this._texture._lodTextureLow;
  31611. }
  31612. return null;
  31613. },
  31614. enumerable: true,
  31615. configurable: true
  31616. });
  31617. /**
  31618. * Dispose the texture and release its associated resources.
  31619. */
  31620. BaseTexture.prototype.dispose = function () {
  31621. if (!this._scene) {
  31622. return;
  31623. }
  31624. // Animations
  31625. this._scene.stopAnimation(this);
  31626. // Remove from scene
  31627. this._scene._removePendingData(this);
  31628. var index = this._scene.textures.indexOf(this);
  31629. if (index >= 0) {
  31630. this._scene.textures.splice(index, 1);
  31631. }
  31632. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31633. if (this._texture === undefined) {
  31634. return;
  31635. }
  31636. // Release
  31637. this.releaseInternalTexture();
  31638. // Callback
  31639. this.onDisposeObservable.notifyObservers(this);
  31640. this.onDisposeObservable.clear();
  31641. };
  31642. /**
  31643. * Serialize the texture into a JSON representation that can be parsed later on.
  31644. * @returns the JSON representation of the texture
  31645. */
  31646. BaseTexture.prototype.serialize = function () {
  31647. if (!this.name) {
  31648. return null;
  31649. }
  31650. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31651. // Animations
  31652. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31653. return serializationObject;
  31654. };
  31655. /**
  31656. * Helper function to be called back once a list of texture contains only ready textures.
  31657. * @param textures Define the list of textures to wait for
  31658. * @param callback Define the callback triggered once the entire list will be ready
  31659. */
  31660. BaseTexture.WhenAllReady = function (textures, callback) {
  31661. var numRemaining = textures.length;
  31662. if (numRemaining === 0) {
  31663. callback();
  31664. return;
  31665. }
  31666. var _loop_1 = function () {
  31667. texture = textures[i];
  31668. if (texture.isReady()) {
  31669. if (--numRemaining === 0) {
  31670. callback();
  31671. }
  31672. }
  31673. else {
  31674. onLoadObservable = texture.onLoadObservable;
  31675. var onLoadCallback_1 = function () {
  31676. onLoadObservable.removeCallback(onLoadCallback_1);
  31677. if (--numRemaining === 0) {
  31678. callback();
  31679. }
  31680. };
  31681. onLoadObservable.add(onLoadCallback_1);
  31682. }
  31683. };
  31684. var texture, onLoadObservable;
  31685. for (var i = 0; i < textures.length; i++) {
  31686. _loop_1();
  31687. }
  31688. };
  31689. /**
  31690. * Default anisotropic filtering level for the application.
  31691. * It is set to 4 as a good tradeoff between perf and quality.
  31692. */
  31693. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31694. __decorate([
  31695. BABYLON.serialize()
  31696. ], BaseTexture.prototype, "name", void 0);
  31697. __decorate([
  31698. BABYLON.serialize("hasAlpha")
  31699. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31700. __decorate([
  31701. BABYLON.serialize()
  31702. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31703. __decorate([
  31704. BABYLON.serialize()
  31705. ], BaseTexture.prototype, "level", void 0);
  31706. __decorate([
  31707. BABYLON.serialize()
  31708. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31709. __decorate([
  31710. BABYLON.serialize("coordinatesMode")
  31711. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31712. __decorate([
  31713. BABYLON.serialize()
  31714. ], BaseTexture.prototype, "wrapU", void 0);
  31715. __decorate([
  31716. BABYLON.serialize()
  31717. ], BaseTexture.prototype, "wrapV", void 0);
  31718. __decorate([
  31719. BABYLON.serialize()
  31720. ], BaseTexture.prototype, "wrapR", void 0);
  31721. __decorate([
  31722. BABYLON.serialize()
  31723. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31724. __decorate([
  31725. BABYLON.serialize()
  31726. ], BaseTexture.prototype, "isCube", void 0);
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], BaseTexture.prototype, "is3D", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], BaseTexture.prototype, "gammaSpace", void 0);
  31733. __decorate([
  31734. BABYLON.serialize()
  31735. ], BaseTexture.prototype, "invertZ", void 0);
  31736. __decorate([
  31737. BABYLON.serialize()
  31738. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31739. __decorate([
  31740. BABYLON.serialize()
  31741. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31742. __decorate([
  31743. BABYLON.serialize()
  31744. ], BaseTexture.prototype, "lodGenerationScale", null);
  31745. __decorate([
  31746. BABYLON.serialize()
  31747. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31748. return BaseTexture;
  31749. }());
  31750. BABYLON.BaseTexture = BaseTexture;
  31751. })(BABYLON || (BABYLON = {}));
  31752. //# sourceMappingURL=babylon.baseTexture.js.map
  31753. var BABYLON;
  31754. (function (BABYLON) {
  31755. /**
  31756. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31757. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31758. */
  31759. var Texture = /** @class */ (function (_super) {
  31760. __extends(Texture, _super);
  31761. /**
  31762. * Instantiates a new texture.
  31763. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31764. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31765. * @param url define the url of the picture to load as a texture
  31766. * @param scene define the scene the texture will belong to
  31767. * @param noMipmap define if the texture will require mip maps or not
  31768. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31769. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31770. * @param onLoad define a callback triggered when the texture has been loaded
  31771. * @param onError define a callback triggered when an error occurred during the loading session
  31772. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31773. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31774. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31775. */
  31776. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31777. if (noMipmap === void 0) { noMipmap = false; }
  31778. if (invertY === void 0) { invertY = true; }
  31779. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31780. if (onLoad === void 0) { onLoad = null; }
  31781. if (onError === void 0) { onError = null; }
  31782. if (buffer === void 0) { buffer = null; }
  31783. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31784. var _this = _super.call(this, scene) || this;
  31785. /**
  31786. * Define an offset on the texture to offset the u coordinates of the UVs
  31787. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31788. */
  31789. _this.uOffset = 0;
  31790. /**
  31791. * Define an offset on the texture to offset the v coordinates of the UVs
  31792. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31793. */
  31794. _this.vOffset = 0;
  31795. /**
  31796. * Define an offset on the texture to scale the u coordinates of the UVs
  31797. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31798. */
  31799. _this.uScale = 1.0;
  31800. /**
  31801. * Define an offset on the texture to scale the v coordinates of the UVs
  31802. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31803. */
  31804. _this.vScale = 1.0;
  31805. /**
  31806. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31807. * @see http://doc.babylonjs.com/how_to/more_materials
  31808. */
  31809. _this.uAng = 0;
  31810. /**
  31811. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31812. * @see http://doc.babylonjs.com/how_to/more_materials
  31813. */
  31814. _this.vAng = 0;
  31815. /**
  31816. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31817. * @see http://doc.babylonjs.com/how_to/more_materials
  31818. */
  31819. _this.wAng = 0;
  31820. /**
  31821. * Defines the center of rotation (U)
  31822. */
  31823. _this.uRotationCenter = 0.5;
  31824. /**
  31825. * Defines the center of rotation (V)
  31826. */
  31827. _this.vRotationCenter = 0.5;
  31828. /**
  31829. * Defines the center of rotation (W)
  31830. */
  31831. _this.wRotationCenter = 0.5;
  31832. /**
  31833. * Observable triggered once the texture has been loaded.
  31834. */
  31835. _this.onLoadObservable = new BABYLON.Observable();
  31836. _this._isBlocking = true;
  31837. _this.name = url || "";
  31838. _this.url = url;
  31839. _this._noMipmap = noMipmap;
  31840. _this._invertY = invertY;
  31841. _this._samplingMode = samplingMode;
  31842. _this._buffer = buffer;
  31843. _this._deleteBuffer = deleteBuffer;
  31844. if (format) {
  31845. _this._format = format;
  31846. }
  31847. scene = _this.getScene();
  31848. if (!scene) {
  31849. return _this;
  31850. }
  31851. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31852. var load = function () {
  31853. if (_this.onLoadObservable.hasObservers()) {
  31854. _this.onLoadObservable.notifyObservers(_this);
  31855. }
  31856. if (onLoad) {
  31857. onLoad();
  31858. }
  31859. if (!_this.isBlocking && scene) {
  31860. scene.resetCachedMaterial();
  31861. }
  31862. };
  31863. if (!_this.url) {
  31864. _this._delayedOnLoad = load;
  31865. _this._delayedOnError = onError;
  31866. return _this;
  31867. }
  31868. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31869. if (!_this._texture) {
  31870. if (!scene.useDelayedTextureLoading) {
  31871. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31872. if (deleteBuffer) {
  31873. delete _this._buffer;
  31874. }
  31875. }
  31876. else {
  31877. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31878. _this._delayedOnLoad = load;
  31879. _this._delayedOnError = onError;
  31880. }
  31881. }
  31882. else {
  31883. if (_this._texture.isReady) {
  31884. BABYLON.Tools.SetImmediate(function () { return load(); });
  31885. }
  31886. else {
  31887. _this._texture.onLoadedObservable.add(load);
  31888. }
  31889. }
  31890. return _this;
  31891. }
  31892. Object.defineProperty(Texture.prototype, "noMipmap", {
  31893. /**
  31894. * Are mip maps generated for this texture or not.
  31895. */
  31896. get: function () {
  31897. return this._noMipmap;
  31898. },
  31899. enumerable: true,
  31900. configurable: true
  31901. });
  31902. Object.defineProperty(Texture.prototype, "isBlocking", {
  31903. get: function () {
  31904. return this._isBlocking;
  31905. },
  31906. /**
  31907. * Is the texture preventing material to render while loading.
  31908. * If false, a default texture will be used instead of the loading one during the preparation step.
  31909. */
  31910. set: function (value) {
  31911. this._isBlocking = value;
  31912. },
  31913. enumerable: true,
  31914. configurable: true
  31915. });
  31916. Object.defineProperty(Texture.prototype, "samplingMode", {
  31917. /**
  31918. * Get the current sampling mode associated with the texture.
  31919. */
  31920. get: function () {
  31921. return this._samplingMode;
  31922. },
  31923. enumerable: true,
  31924. configurable: true
  31925. });
  31926. /**
  31927. * Update the url (and optional buffer) of this texture if url was null during construction.
  31928. * @param url the url of the texture
  31929. * @param buffer the buffer of the texture (defaults to null)
  31930. */
  31931. Texture.prototype.updateURL = function (url, buffer) {
  31932. if (buffer === void 0) { buffer = null; }
  31933. if (this.url) {
  31934. throw new Error("URL is already set");
  31935. }
  31936. this.url = url;
  31937. this._buffer = buffer;
  31938. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31939. this.delayLoad();
  31940. };
  31941. /**
  31942. * Finish the loading sequence of a texture flagged as delayed load.
  31943. * @hidden
  31944. */
  31945. Texture.prototype.delayLoad = function () {
  31946. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31947. return;
  31948. }
  31949. var scene = this.getScene();
  31950. if (!scene) {
  31951. return;
  31952. }
  31953. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31954. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31955. if (!this._texture) {
  31956. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31957. if (this._deleteBuffer) {
  31958. delete this._buffer;
  31959. }
  31960. }
  31961. else {
  31962. if (this._delayedOnLoad) {
  31963. if (this._texture.isReady) {
  31964. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31965. }
  31966. else {
  31967. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31968. }
  31969. }
  31970. }
  31971. this._delayedOnLoad = null;
  31972. this._delayedOnError = null;
  31973. };
  31974. /**
  31975. * Update the sampling mode of the texture.
  31976. * Default is Trilinear mode.
  31977. *
  31978. * | Value | Type | Description |
  31979. * | ----- | ------------------ | ----------- |
  31980. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31981. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31982. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31983. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31984. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31985. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31986. * | 7 | NEAREST_LINEAR | |
  31987. * | 8 | NEAREST_NEAREST | |
  31988. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31989. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31990. * | 11 | LINEAR_LINEAR | |
  31991. * | 12 | LINEAR_NEAREST | |
  31992. *
  31993. * > _mag_: magnification filter (close to the viewer)
  31994. * > _min_: minification filter (far from the viewer)
  31995. * > _mip_: filter used between mip map levels
  31996. *@param samplingMode Define the new sampling mode of the texture
  31997. */
  31998. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31999. if (!this._texture) {
  32000. return;
  32001. }
  32002. var scene = this.getScene();
  32003. if (!scene) {
  32004. return;
  32005. }
  32006. this._samplingMode = samplingMode;
  32007. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  32008. };
  32009. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  32010. x *= this.uScale;
  32011. y *= this.vScale;
  32012. x -= this.uRotationCenter * this.uScale;
  32013. y -= this.vRotationCenter * this.vScale;
  32014. z -= this.wRotationCenter;
  32015. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  32016. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  32017. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  32018. t.z += this.wRotationCenter;
  32019. };
  32020. /**
  32021. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  32022. * @returns the transform matrix of the texture.
  32023. */
  32024. Texture.prototype.getTextureMatrix = function () {
  32025. var _this = this;
  32026. if (this.uOffset === this._cachedUOffset &&
  32027. this.vOffset === this._cachedVOffset &&
  32028. this.uScale === this._cachedUScale &&
  32029. this.vScale === this._cachedVScale &&
  32030. this.uAng === this._cachedUAng &&
  32031. this.vAng === this._cachedVAng &&
  32032. this.wAng === this._cachedWAng) {
  32033. return this._cachedTextureMatrix;
  32034. }
  32035. this._cachedUOffset = this.uOffset;
  32036. this._cachedVOffset = this.vOffset;
  32037. this._cachedUScale = this.uScale;
  32038. this._cachedVScale = this.vScale;
  32039. this._cachedUAng = this.uAng;
  32040. this._cachedVAng = this.vAng;
  32041. this._cachedWAng = this.wAng;
  32042. if (!this._cachedTextureMatrix) {
  32043. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32044. this._rowGenerationMatrix = new BABYLON.Matrix();
  32045. this._t0 = BABYLON.Vector3.Zero();
  32046. this._t1 = BABYLON.Vector3.Zero();
  32047. this._t2 = BABYLON.Vector3.Zero();
  32048. }
  32049. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  32050. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  32051. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  32052. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  32053. this._t1.subtractInPlace(this._t0);
  32054. this._t2.subtractInPlace(this._t0);
  32055. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32056. this._cachedTextureMatrix.m[0] = this._t1.x;
  32057. this._cachedTextureMatrix.m[1] = this._t1.y;
  32058. this._cachedTextureMatrix.m[2] = this._t1.z;
  32059. this._cachedTextureMatrix.m[4] = this._t2.x;
  32060. this._cachedTextureMatrix.m[5] = this._t2.y;
  32061. this._cachedTextureMatrix.m[6] = this._t2.z;
  32062. this._cachedTextureMatrix.m[8] = this._t0.x;
  32063. this._cachedTextureMatrix.m[9] = this._t0.y;
  32064. this._cachedTextureMatrix.m[10] = this._t0.z;
  32065. var scene = this.getScene();
  32066. if (!scene) {
  32067. return this._cachedTextureMatrix;
  32068. }
  32069. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32070. return mat.hasTexture(_this);
  32071. });
  32072. return this._cachedTextureMatrix;
  32073. };
  32074. /**
  32075. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  32076. * @returns The reflection texture transform
  32077. */
  32078. Texture.prototype.getReflectionTextureMatrix = function () {
  32079. var _this = this;
  32080. var scene = this.getScene();
  32081. if (!scene) {
  32082. return this._cachedTextureMatrix;
  32083. }
  32084. if (this.uOffset === this._cachedUOffset &&
  32085. this.vOffset === this._cachedVOffset &&
  32086. this.uScale === this._cachedUScale &&
  32087. this.vScale === this._cachedVScale &&
  32088. this.coordinatesMode === this._cachedCoordinatesMode) {
  32089. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  32090. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  32091. return this._cachedTextureMatrix;
  32092. }
  32093. }
  32094. else {
  32095. return this._cachedTextureMatrix;
  32096. }
  32097. }
  32098. if (!this._cachedTextureMatrix) {
  32099. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32100. }
  32101. if (!this._projectionModeMatrix) {
  32102. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  32103. }
  32104. this._cachedUOffset = this.uOffset;
  32105. this._cachedVOffset = this.vOffset;
  32106. this._cachedUScale = this.uScale;
  32107. this._cachedVScale = this.vScale;
  32108. this._cachedCoordinatesMode = this.coordinatesMode;
  32109. switch (this.coordinatesMode) {
  32110. case Texture.PLANAR_MODE:
  32111. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32112. this._cachedTextureMatrix[0] = this.uScale;
  32113. this._cachedTextureMatrix[5] = this.vScale;
  32114. this._cachedTextureMatrix[12] = this.uOffset;
  32115. this._cachedTextureMatrix[13] = this.vOffset;
  32116. break;
  32117. case Texture.PROJECTION_MODE:
  32118. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  32119. this._projectionModeMatrix.m[0] = 0.5;
  32120. this._projectionModeMatrix.m[5] = -0.5;
  32121. this._projectionModeMatrix.m[10] = 0.0;
  32122. this._projectionModeMatrix.m[12] = 0.5;
  32123. this._projectionModeMatrix.m[13] = 0.5;
  32124. this._projectionModeMatrix.m[14] = 1.0;
  32125. this._projectionModeMatrix.m[15] = 1.0;
  32126. var projectionMatrix = scene.getProjectionMatrix();
  32127. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  32128. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  32129. break;
  32130. default:
  32131. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32132. break;
  32133. }
  32134. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32135. return (mat.getActiveTextures().indexOf(_this) !== -1);
  32136. });
  32137. return this._cachedTextureMatrix;
  32138. };
  32139. /**
  32140. * Clones the texture.
  32141. * @returns the cloned texture
  32142. */
  32143. Texture.prototype.clone = function () {
  32144. var _this = this;
  32145. return BABYLON.SerializationHelper.Clone(function () {
  32146. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  32147. }, this);
  32148. };
  32149. /**
  32150. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  32151. * @returns The JSON representation of the texture
  32152. */
  32153. Texture.prototype.serialize = function () {
  32154. var serializationObject = _super.prototype.serialize.call(this);
  32155. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  32156. serializationObject.base64String = this._buffer;
  32157. serializationObject.name = serializationObject.name.replace("data:", "");
  32158. }
  32159. serializationObject.invertY = this._invertY;
  32160. serializationObject.samplingMode = this.samplingMode;
  32161. return serializationObject;
  32162. };
  32163. /**
  32164. * Get the current class name of the texture usefull for serialization or dynamic coding.
  32165. * @returns "Texture"
  32166. */
  32167. Texture.prototype.getClassName = function () {
  32168. return "Texture";
  32169. };
  32170. /**
  32171. * Dispose the texture and release its associated resources.
  32172. */
  32173. Texture.prototype.dispose = function () {
  32174. _super.prototype.dispose.call(this);
  32175. this.onLoadObservable.clear();
  32176. this._delayedOnLoad = null;
  32177. this._delayedOnError = null;
  32178. };
  32179. /**
  32180. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  32181. * @param parsedTexture Define the JSON representation of the texture
  32182. * @param scene Define the scene the parsed texture should be instantiated in
  32183. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  32184. * @returns The parsed texture if successful
  32185. */
  32186. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  32187. if (parsedTexture.customType) {
  32188. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  32189. // Update Sampling Mode
  32190. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  32191. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  32192. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  32193. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  32194. }
  32195. }
  32196. return parsedCustomTexture;
  32197. }
  32198. if (parsedTexture.isCube) {
  32199. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  32200. }
  32201. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  32202. return null;
  32203. }
  32204. var texture = BABYLON.SerializationHelper.Parse(function () {
  32205. var generateMipMaps = true;
  32206. if (parsedTexture.noMipmap) {
  32207. generateMipMaps = false;
  32208. }
  32209. if (parsedTexture.mirrorPlane) {
  32210. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32211. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  32212. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  32213. return mirrorTexture;
  32214. }
  32215. else if (parsedTexture.isRenderTarget) {
  32216. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32217. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  32218. return renderTargetTexture;
  32219. }
  32220. else {
  32221. var texture;
  32222. if (parsedTexture.base64String) {
  32223. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  32224. }
  32225. else {
  32226. var url = rootUrl + parsedTexture.name;
  32227. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  32228. url = parsedTexture.url;
  32229. }
  32230. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  32231. }
  32232. return texture;
  32233. }
  32234. }, parsedTexture, scene);
  32235. // Update Sampling Mode
  32236. if (parsedTexture.samplingMode) {
  32237. var sampling = parsedTexture.samplingMode;
  32238. if (texture._samplingMode !== sampling) {
  32239. texture.updateSamplingMode(sampling);
  32240. }
  32241. }
  32242. // Animations
  32243. if (parsedTexture.animations) {
  32244. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32245. var parsedAnimation = parsedTexture.animations[animationIndex];
  32246. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32247. }
  32248. }
  32249. return texture;
  32250. };
  32251. /**
  32252. * Creates a texture from its base 64 representation.
  32253. * @param data Define the base64 payload without the data: prefix
  32254. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32255. * @param scene Define the scene the texture should belong to
  32256. * @param noMipmap Forces the texture to not create mip map information if true
  32257. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32258. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32259. * @param onLoad define a callback triggered when the texture has been loaded
  32260. * @param onError define a callback triggered when an error occurred during the loading session
  32261. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32262. * @returns the created texture
  32263. */
  32264. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32265. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32266. if (onLoad === void 0) { onLoad = null; }
  32267. if (onError === void 0) { onError = null; }
  32268. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32269. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32270. };
  32271. /**
  32272. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32273. * @param data Define the base64 payload without the data: prefix
  32274. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32275. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32276. * @param scene Define the scene the texture should belong to
  32277. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32278. * @param noMipmap Forces the texture to not create mip map information if true
  32279. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32280. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32281. * @param onLoad define a callback triggered when the texture has been loaded
  32282. * @param onError define a callback triggered when an error occurred during the loading session
  32283. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32284. * @returns the created texture
  32285. */
  32286. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32287. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32288. if (noMipmap === void 0) { noMipmap = false; }
  32289. if (invertY === void 0) { invertY = true; }
  32290. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32291. if (onLoad === void 0) { onLoad = null; }
  32292. if (onError === void 0) { onError = null; }
  32293. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32294. if (name.substr(0, 5) !== "data:") {
  32295. name = "data:" + name;
  32296. }
  32297. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32298. };
  32299. /** nearest is mag = nearest and min = nearest and mip = linear */
  32300. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32301. /** nearest is mag = nearest and min = nearest and mip = linear */
  32302. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32303. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32304. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32305. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32306. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32307. /** Trilinear is mag = linear and min = linear and mip = linear */
  32308. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32309. /** Trilinear is mag = linear and min = linear and mip = linear */
  32310. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32311. /** mag = nearest and min = nearest and mip = nearest */
  32312. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32313. /** mag = nearest and min = linear and mip = nearest */
  32314. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32315. /** mag = nearest and min = linear and mip = linear */
  32316. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32317. /** mag = nearest and min = linear and mip = none */
  32318. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32319. /** mag = nearest and min = nearest and mip = none */
  32320. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32321. /** mag = linear and min = nearest and mip = nearest */
  32322. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32323. /** mag = linear and min = nearest and mip = linear */
  32324. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32325. /** mag = linear and min = linear and mip = none */
  32326. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32327. /** mag = linear and min = nearest and mip = none */
  32328. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32329. /** Explicit coordinates mode */
  32330. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32331. /** Spherical coordinates mode */
  32332. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32333. /** Planar coordinates mode */
  32334. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32335. /** Cubic coordinates mode */
  32336. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32337. /** Projection coordinates mode */
  32338. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32339. /** Inverse Cubic coordinates mode */
  32340. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32341. /** Inverse Cubic coordinates mode */
  32342. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32343. /** Equirectangular coordinates mode */
  32344. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32345. /** Equirectangular Fixed coordinates mode */
  32346. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32347. /** Equirectangular Fixed Mirrored coordinates mode */
  32348. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32349. /** Texture is not repeating outside of 0..1 UVs */
  32350. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32351. /** Texture is repeating outside of 0..1 UVs */
  32352. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32353. /** Texture is repeating and mirrored */
  32354. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32355. /**
  32356. * 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
  32357. */
  32358. Texture.UseSerializedUrlIfAny = false;
  32359. __decorate([
  32360. BABYLON.serialize()
  32361. ], Texture.prototype, "url", void 0);
  32362. __decorate([
  32363. BABYLON.serialize()
  32364. ], Texture.prototype, "uOffset", void 0);
  32365. __decorate([
  32366. BABYLON.serialize()
  32367. ], Texture.prototype, "vOffset", void 0);
  32368. __decorate([
  32369. BABYLON.serialize()
  32370. ], Texture.prototype, "uScale", void 0);
  32371. __decorate([
  32372. BABYLON.serialize()
  32373. ], Texture.prototype, "vScale", void 0);
  32374. __decorate([
  32375. BABYLON.serialize()
  32376. ], Texture.prototype, "uAng", void 0);
  32377. __decorate([
  32378. BABYLON.serialize()
  32379. ], Texture.prototype, "vAng", void 0);
  32380. __decorate([
  32381. BABYLON.serialize()
  32382. ], Texture.prototype, "wAng", void 0);
  32383. __decorate([
  32384. BABYLON.serialize()
  32385. ], Texture.prototype, "uRotationCenter", void 0);
  32386. __decorate([
  32387. BABYLON.serialize()
  32388. ], Texture.prototype, "vRotationCenter", void 0);
  32389. __decorate([
  32390. BABYLON.serialize()
  32391. ], Texture.prototype, "wRotationCenter", void 0);
  32392. __decorate([
  32393. BABYLON.serialize()
  32394. ], Texture.prototype, "isBlocking", null);
  32395. return Texture;
  32396. }(BABYLON.BaseTexture));
  32397. BABYLON.Texture = Texture;
  32398. })(BABYLON || (BABYLON = {}));
  32399. //# sourceMappingURL=babylon.texture.js.map
  32400. var BABYLON;
  32401. (function (BABYLON) {
  32402. /**
  32403. * @hidden
  32404. **/
  32405. var _CreationDataStorage = /** @class */ (function () {
  32406. function _CreationDataStorage() {
  32407. }
  32408. return _CreationDataStorage;
  32409. }());
  32410. BABYLON._CreationDataStorage = _CreationDataStorage;
  32411. /**
  32412. * @hidden
  32413. **/
  32414. var _InstanceDataStorage = /** @class */ (function () {
  32415. function _InstanceDataStorage() {
  32416. this.visibleInstances = {};
  32417. this.renderIdForInstances = new Array();
  32418. this.batchCache = new _InstancesBatch();
  32419. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32420. }
  32421. return _InstanceDataStorage;
  32422. }());
  32423. /**
  32424. * @hidden
  32425. **/
  32426. var _InstancesBatch = /** @class */ (function () {
  32427. function _InstancesBatch() {
  32428. this.mustReturn = false;
  32429. this.visibleInstances = new Array();
  32430. this.renderSelf = new Array();
  32431. }
  32432. return _InstancesBatch;
  32433. }());
  32434. BABYLON._InstancesBatch = _InstancesBatch;
  32435. /**
  32436. * Class used to represent renderable models
  32437. */
  32438. var Mesh = /** @class */ (function (_super) {
  32439. __extends(Mesh, _super);
  32440. /**
  32441. * @constructor
  32442. * @param name The value used by scene.getMeshByName() to do a lookup.
  32443. * @param scene The scene to add this mesh to.
  32444. * @param parent The parent of this mesh, if it has one
  32445. * @param source An optional Mesh from which geometry is shared, cloned.
  32446. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32447. * When false, achieved by calling a clone(), also passing False.
  32448. * This will make creation of children, recursive.
  32449. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32450. */
  32451. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32452. if (scene === void 0) { scene = null; }
  32453. if (parent === void 0) { parent = null; }
  32454. if (source === void 0) { source = null; }
  32455. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32456. var _this = _super.call(this, name, scene) || this;
  32457. // Members
  32458. /**
  32459. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32460. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32461. */
  32462. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32463. /**
  32464. * Gets the list of instances created from this mesh
  32465. * it is not supposed to be modified manually.
  32466. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  32467. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32468. */
  32469. _this.instances = new Array();
  32470. _this._LODLevels = new Array();
  32471. /** @hidden */
  32472. _this._instanceDataStorage = new _InstanceDataStorage();
  32473. // Use by builder only to know what orientation were the mesh build in.
  32474. /** @hidden */
  32475. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32476. /**
  32477. * Use this property to change the original side orientation defined at construction time
  32478. */
  32479. _this.overrideMaterialSideOrientation = null;
  32480. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32481. // Will be used to save a source mesh reference, If any
  32482. _this._source = null;
  32483. scene = _this.getScene();
  32484. if (source) {
  32485. // Geometry
  32486. if (source._geometry) {
  32487. source._geometry.applyToMesh(_this);
  32488. }
  32489. // Deep copy
  32490. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32491. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32492. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32493. ], ["_poseMatrix"]);
  32494. // Source mesh
  32495. _this._source = source;
  32496. if (scene.useClonedMeshhMap) {
  32497. if (!source.meshMap) {
  32498. source.meshMap = {};
  32499. }
  32500. source.meshMap[_this.uniqueId] = _this;
  32501. }
  32502. // Construction Params
  32503. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32504. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32505. _this._creationDataStorage = source._creationDataStorage;
  32506. // Animation ranges
  32507. if (_this._source._ranges) {
  32508. var ranges = _this._source._ranges;
  32509. for (var name in ranges) {
  32510. if (!ranges.hasOwnProperty(name)) {
  32511. continue;
  32512. }
  32513. if (!ranges[name]) {
  32514. continue;
  32515. }
  32516. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32517. }
  32518. }
  32519. // Metadata
  32520. if (source.metadata && source.metadata.clone) {
  32521. _this.metadata = source.metadata.clone();
  32522. }
  32523. else {
  32524. _this.metadata = source.metadata;
  32525. }
  32526. // Tags
  32527. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32528. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32529. }
  32530. // Parent
  32531. _this.parent = source.parent;
  32532. // Pivot
  32533. _this.setPivotMatrix(source.getPivotMatrix());
  32534. _this.id = name + "." + source.id;
  32535. // Material
  32536. _this.material = source.material;
  32537. var index;
  32538. if (!doNotCloneChildren) {
  32539. // Children
  32540. var directDescendants = source.getDescendants(true);
  32541. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32542. var child = directDescendants[index_1];
  32543. if (child.clone) {
  32544. child.clone(name + "." + child.name, _this);
  32545. }
  32546. }
  32547. }
  32548. // Physics clone
  32549. var physicsEngine = _this.getScene().getPhysicsEngine();
  32550. if (clonePhysicsImpostor && physicsEngine) {
  32551. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32552. if (impostor) {
  32553. _this.physicsImpostor = impostor.clone(_this);
  32554. }
  32555. }
  32556. // Particles
  32557. for (index = 0; index < scene.particleSystems.length; index++) {
  32558. var system = scene.particleSystems[index];
  32559. if (system.emitter === source) {
  32560. system.clone(system.name, _this);
  32561. }
  32562. }
  32563. _this.refreshBoundingInfo();
  32564. _this.computeWorldMatrix(true);
  32565. }
  32566. // Parent
  32567. if (parent !== null) {
  32568. _this.parent = parent;
  32569. }
  32570. return _this;
  32571. }
  32572. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32573. /**
  32574. * An event triggered before rendering the mesh
  32575. */
  32576. get: function () {
  32577. if (!this._onBeforeRenderObservable) {
  32578. this._onBeforeRenderObservable = new BABYLON.Observable();
  32579. }
  32580. return this._onBeforeRenderObservable;
  32581. },
  32582. enumerable: true,
  32583. configurable: true
  32584. });
  32585. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32586. /**
  32587. * An event triggered after rendering the mesh
  32588. */
  32589. get: function () {
  32590. if (!this._onAfterRenderObservable) {
  32591. this._onAfterRenderObservable = new BABYLON.Observable();
  32592. }
  32593. return this._onAfterRenderObservable;
  32594. },
  32595. enumerable: true,
  32596. configurable: true
  32597. });
  32598. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32599. /**
  32600. * An event triggered before drawing the mesh
  32601. */
  32602. get: function () {
  32603. if (!this._onBeforeDrawObservable) {
  32604. this._onBeforeDrawObservable = new BABYLON.Observable();
  32605. }
  32606. return this._onBeforeDrawObservable;
  32607. },
  32608. enumerable: true,
  32609. configurable: true
  32610. });
  32611. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32612. /**
  32613. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32614. */
  32615. set: function (callback) {
  32616. if (this._onBeforeDrawObserver) {
  32617. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32618. }
  32619. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32620. },
  32621. enumerable: true,
  32622. configurable: true
  32623. });
  32624. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32625. /**
  32626. * Gets or sets the morph target manager
  32627. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32628. */
  32629. get: function () {
  32630. return this._morphTargetManager;
  32631. },
  32632. set: function (value) {
  32633. if (this._morphTargetManager === value) {
  32634. return;
  32635. }
  32636. this._morphTargetManager = value;
  32637. this._syncGeometryWithMorphTargetManager();
  32638. },
  32639. enumerable: true,
  32640. configurable: true
  32641. });
  32642. Object.defineProperty(Mesh.prototype, "source", {
  32643. /**
  32644. * Gets the source mesh (the one used to clone this one from)
  32645. */
  32646. get: function () {
  32647. return this._source;
  32648. },
  32649. enumerable: true,
  32650. configurable: true
  32651. });
  32652. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32653. /**
  32654. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32655. */
  32656. get: function () {
  32657. return this._unIndexed;
  32658. },
  32659. set: function (value) {
  32660. if (this._unIndexed !== value) {
  32661. this._unIndexed = value;
  32662. this._markSubMeshesAsAttributesDirty();
  32663. }
  32664. },
  32665. enumerable: true,
  32666. configurable: true
  32667. });
  32668. // Methods
  32669. /**
  32670. * Gets the class name
  32671. * @returns the string "Mesh".
  32672. */
  32673. Mesh.prototype.getClassName = function () {
  32674. return "Mesh";
  32675. };
  32676. /**
  32677. * Returns a description of this mesh
  32678. * @param fullDetails define if full details about this mesh must be used
  32679. * @returns a descriptive string representing this mesh
  32680. */
  32681. Mesh.prototype.toString = function (fullDetails) {
  32682. var ret = _super.prototype.toString.call(this, fullDetails);
  32683. ret += ", n vertices: " + this.getTotalVertices();
  32684. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32685. if (this.animations) {
  32686. for (var i = 0; i < this.animations.length; i++) {
  32687. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32688. }
  32689. }
  32690. if (fullDetails) {
  32691. if (this._geometry) {
  32692. var ib = this.getIndices();
  32693. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32694. if (vb && ib) {
  32695. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32696. }
  32697. }
  32698. else {
  32699. ret += ", flat shading: UNKNOWN";
  32700. }
  32701. }
  32702. return ret;
  32703. };
  32704. /** @hidden */
  32705. Mesh.prototype._unBindEffect = function () {
  32706. _super.prototype._unBindEffect.call(this);
  32707. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32708. var instance = _a[_i];
  32709. instance._unBindEffect();
  32710. }
  32711. };
  32712. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32713. /**
  32714. * Gets a boolean indicating if this mesh has LOD
  32715. */
  32716. get: function () {
  32717. return this._LODLevels.length > 0;
  32718. },
  32719. enumerable: true,
  32720. configurable: true
  32721. });
  32722. /**
  32723. * Gets the list of MeshLODLevel associated with the current mesh
  32724. * @returns an array of MeshLODLevel
  32725. */
  32726. Mesh.prototype.getLODLevels = function () {
  32727. return this._LODLevels;
  32728. };
  32729. Mesh.prototype._sortLODLevels = function () {
  32730. this._LODLevels.sort(function (a, b) {
  32731. if (a.distance < b.distance) {
  32732. return 1;
  32733. }
  32734. if (a.distance > b.distance) {
  32735. return -1;
  32736. }
  32737. return 0;
  32738. });
  32739. };
  32740. /**
  32741. * Add a mesh as LOD level triggered at the given distance.
  32742. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32743. * @param distance The distance from the center of the object to show this level
  32744. * @param mesh The mesh to be added as LOD level (can be null)
  32745. * @return This mesh (for chaining)
  32746. */
  32747. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32748. if (mesh && mesh._masterMesh) {
  32749. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32750. return this;
  32751. }
  32752. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32753. this._LODLevels.push(level);
  32754. if (mesh) {
  32755. mesh._masterMesh = this;
  32756. }
  32757. this._sortLODLevels();
  32758. return this;
  32759. };
  32760. /**
  32761. * Returns the LOD level mesh at the passed distance or null if not found.
  32762. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32763. * @param distance The distance from the center of the object to show this level
  32764. * @returns a Mesh or `null`
  32765. */
  32766. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32767. for (var index = 0; index < this._LODLevels.length; index++) {
  32768. var level = this._LODLevels[index];
  32769. if (level.distance === distance) {
  32770. return level.mesh;
  32771. }
  32772. }
  32773. return null;
  32774. };
  32775. /**
  32776. * Remove a mesh from the LOD array
  32777. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32778. * @param mesh defines the mesh to be removed
  32779. * @return This mesh (for chaining)
  32780. */
  32781. Mesh.prototype.removeLODLevel = function (mesh) {
  32782. for (var index = 0; index < this._LODLevels.length; index++) {
  32783. if (this._LODLevels[index].mesh === mesh) {
  32784. this._LODLevels.splice(index, 1);
  32785. if (mesh) {
  32786. mesh._masterMesh = null;
  32787. }
  32788. }
  32789. }
  32790. this._sortLODLevels();
  32791. return this;
  32792. };
  32793. /**
  32794. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32795. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32796. * @param camera defines the camera to use to compute distance
  32797. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32798. * @return This mesh (for chaining)
  32799. */
  32800. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32801. if (!this._LODLevels || this._LODLevels.length === 0) {
  32802. return this;
  32803. }
  32804. var bSphere;
  32805. if (boundingSphere) {
  32806. bSphere = boundingSphere;
  32807. }
  32808. else {
  32809. var boundingInfo = this.getBoundingInfo();
  32810. bSphere = boundingInfo.boundingSphere;
  32811. }
  32812. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32813. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32814. if (this.onLODLevelSelection) {
  32815. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32816. }
  32817. return this;
  32818. }
  32819. for (var index = 0; index < this._LODLevels.length; index++) {
  32820. var level = this._LODLevels[index];
  32821. if (level.distance < distanceToCamera) {
  32822. if (level.mesh) {
  32823. level.mesh._preActivate();
  32824. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32825. }
  32826. if (this.onLODLevelSelection) {
  32827. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32828. }
  32829. return level.mesh;
  32830. }
  32831. }
  32832. if (this.onLODLevelSelection) {
  32833. this.onLODLevelSelection(distanceToCamera, this, this);
  32834. }
  32835. return this;
  32836. };
  32837. Object.defineProperty(Mesh.prototype, "geometry", {
  32838. /**
  32839. * Gets the mesh internal Geometry object
  32840. */
  32841. get: function () {
  32842. return this._geometry;
  32843. },
  32844. enumerable: true,
  32845. configurable: true
  32846. });
  32847. /**
  32848. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32849. * @returns the total number of vertices
  32850. */
  32851. Mesh.prototype.getTotalVertices = function () {
  32852. if (this._geometry === null || this._geometry === undefined) {
  32853. return 0;
  32854. }
  32855. return this._geometry.getTotalVertices();
  32856. };
  32857. /**
  32858. * Returns the content of an associated vertex buffer
  32859. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32860. * - BABYLON.VertexBuffer.PositionKind
  32861. * - BABYLON.VertexBuffer.UVKind
  32862. * - BABYLON.VertexBuffer.UV2Kind
  32863. * - BABYLON.VertexBuffer.UV3Kind
  32864. * - BABYLON.VertexBuffer.UV4Kind
  32865. * - BABYLON.VertexBuffer.UV5Kind
  32866. * - BABYLON.VertexBuffer.UV6Kind
  32867. * - BABYLON.VertexBuffer.ColorKind
  32868. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32869. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32870. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32871. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32872. * @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
  32873. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32874. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32875. */
  32876. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32877. if (!this._geometry) {
  32878. return null;
  32879. }
  32880. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32881. };
  32882. /**
  32883. * Returns the mesh VertexBuffer object from the requested `kind`
  32884. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32885. * - BABYLON.VertexBuffer.PositionKind
  32886. * - BABYLON.VertexBuffer.UVKind
  32887. * - BABYLON.VertexBuffer.UV2Kind
  32888. * - BABYLON.VertexBuffer.UV3Kind
  32889. * - BABYLON.VertexBuffer.UV4Kind
  32890. * - BABYLON.VertexBuffer.UV5Kind
  32891. * - BABYLON.VertexBuffer.UV6Kind
  32892. * - BABYLON.VertexBuffer.ColorKind
  32893. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32894. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32895. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32896. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32897. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32898. */
  32899. Mesh.prototype.getVertexBuffer = function (kind) {
  32900. if (!this._geometry) {
  32901. return null;
  32902. }
  32903. return this._geometry.getVertexBuffer(kind);
  32904. };
  32905. /**
  32906. * Tests if a specific vertex buffer is associated with this mesh
  32907. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32908. * - BABYLON.VertexBuffer.PositionKind
  32909. * - BABYLON.VertexBuffer.UVKind
  32910. * - BABYLON.VertexBuffer.UV2Kind
  32911. * - BABYLON.VertexBuffer.UV3Kind
  32912. * - BABYLON.VertexBuffer.UV4Kind
  32913. * - BABYLON.VertexBuffer.UV5Kind
  32914. * - BABYLON.VertexBuffer.UV6Kind
  32915. * - BABYLON.VertexBuffer.ColorKind
  32916. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32917. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32918. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32919. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32920. * @returns a boolean
  32921. */
  32922. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32923. if (!this._geometry) {
  32924. if (this._delayInfo) {
  32925. return this._delayInfo.indexOf(kind) !== -1;
  32926. }
  32927. return false;
  32928. }
  32929. return this._geometry.isVerticesDataPresent(kind);
  32930. };
  32931. /**
  32932. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32933. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32934. * - BABYLON.VertexBuffer.PositionKind
  32935. * - BABYLON.VertexBuffer.UVKind
  32936. * - BABYLON.VertexBuffer.UV2Kind
  32937. * - BABYLON.VertexBuffer.UV3Kind
  32938. * - BABYLON.VertexBuffer.UV4Kind
  32939. * - BABYLON.VertexBuffer.UV5Kind
  32940. * - BABYLON.VertexBuffer.UV6Kind
  32941. * - BABYLON.VertexBuffer.ColorKind
  32942. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32943. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32944. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32945. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32946. * @returns a boolean
  32947. */
  32948. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32949. if (!this._geometry) {
  32950. if (this._delayInfo) {
  32951. return this._delayInfo.indexOf(kind) !== -1;
  32952. }
  32953. return false;
  32954. }
  32955. return this._geometry.isVertexBufferUpdatable(kind);
  32956. };
  32957. /**
  32958. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32959. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32960. * - BABYLON.VertexBuffer.PositionKind
  32961. * - BABYLON.VertexBuffer.UVKind
  32962. * - BABYLON.VertexBuffer.UV2Kind
  32963. * - BABYLON.VertexBuffer.UV3Kind
  32964. * - BABYLON.VertexBuffer.UV4Kind
  32965. * - BABYLON.VertexBuffer.UV5Kind
  32966. * - BABYLON.VertexBuffer.UV6Kind
  32967. * - BABYLON.VertexBuffer.ColorKind
  32968. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32969. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32970. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32971. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32972. * @returns an array of strings
  32973. */
  32974. Mesh.prototype.getVerticesDataKinds = function () {
  32975. if (!this._geometry) {
  32976. var result = new Array();
  32977. if (this._delayInfo) {
  32978. this._delayInfo.forEach(function (kind, index, array) {
  32979. result.push(kind);
  32980. });
  32981. }
  32982. return result;
  32983. }
  32984. return this._geometry.getVerticesDataKinds();
  32985. };
  32986. /**
  32987. * Returns a positive integer : the total number of indices in this mesh geometry.
  32988. * @returns the numner of indices or zero if the mesh has no geometry.
  32989. */
  32990. Mesh.prototype.getTotalIndices = function () {
  32991. if (!this._geometry) {
  32992. return 0;
  32993. }
  32994. return this._geometry.getTotalIndices();
  32995. };
  32996. /**
  32997. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32998. * @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.
  32999. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  33000. * @returns the indices array or an empty array if the mesh has no geometry
  33001. */
  33002. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  33003. if (!this._geometry) {
  33004. return [];
  33005. }
  33006. return this._geometry.getIndices(copyWhenShared, forceCopy);
  33007. };
  33008. Object.defineProperty(Mesh.prototype, "isBlocked", {
  33009. get: function () {
  33010. return this._masterMesh !== null && this._masterMesh !== undefined;
  33011. },
  33012. enumerable: true,
  33013. configurable: true
  33014. });
  33015. /**
  33016. * Determine if the current mesh is ready to be rendered
  33017. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  33018. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  33019. * @returns true if all associated assets are ready (material, textures, shaders)
  33020. */
  33021. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  33022. if (completeCheck === void 0) { completeCheck = false; }
  33023. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  33024. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33025. return false;
  33026. }
  33027. if (!_super.prototype.isReady.call(this, completeCheck)) {
  33028. return false;
  33029. }
  33030. if (!this.subMeshes || this.subMeshes.length === 0) {
  33031. return true;
  33032. }
  33033. if (!completeCheck) {
  33034. return true;
  33035. }
  33036. var engine = this.getEngine();
  33037. var scene = this.getScene();
  33038. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  33039. this.computeWorldMatrix();
  33040. var mat = this.material || scene.defaultMaterial;
  33041. if (mat) {
  33042. if (mat._storeEffectOnSubMeshes) {
  33043. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33044. var subMesh = _a[_i];
  33045. var effectiveMaterial = subMesh.getMaterial();
  33046. if (effectiveMaterial) {
  33047. if (effectiveMaterial._storeEffectOnSubMeshes) {
  33048. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33049. return false;
  33050. }
  33051. }
  33052. else {
  33053. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33054. return false;
  33055. }
  33056. }
  33057. }
  33058. }
  33059. }
  33060. else {
  33061. if (!mat.isReady(this, hardwareInstancedRendering)) {
  33062. return false;
  33063. }
  33064. }
  33065. }
  33066. // Shadows
  33067. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  33068. var light = _c[_b];
  33069. var generator = light.getShadowGenerator();
  33070. if (generator) {
  33071. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  33072. var subMesh = _e[_d];
  33073. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  33074. return false;
  33075. }
  33076. }
  33077. }
  33078. }
  33079. // LOD
  33080. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  33081. var lod = _g[_f];
  33082. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  33083. return false;
  33084. }
  33085. }
  33086. return true;
  33087. };
  33088. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  33089. /**
  33090. * 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.
  33091. */
  33092. get: function () {
  33093. return this._areNormalsFrozen;
  33094. },
  33095. enumerable: true,
  33096. configurable: true
  33097. });
  33098. /**
  33099. * 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.
  33100. * @returns the current mesh
  33101. */
  33102. Mesh.prototype.freezeNormals = function () {
  33103. this._areNormalsFrozen = true;
  33104. return this;
  33105. };
  33106. /**
  33107. * 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
  33108. * @returns the current mesh
  33109. */
  33110. Mesh.prototype.unfreezeNormals = function () {
  33111. this._areNormalsFrozen = false;
  33112. return this;
  33113. };
  33114. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  33115. /**
  33116. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  33117. */
  33118. set: function (count) {
  33119. this._instanceDataStorage.overridenInstanceCount = count;
  33120. },
  33121. enumerable: true,
  33122. configurable: true
  33123. });
  33124. // Methods
  33125. /** @hidden */
  33126. Mesh.prototype._preActivate = function () {
  33127. var sceneRenderId = this.getScene().getRenderId();
  33128. if (this._preActivateId === sceneRenderId) {
  33129. return this;
  33130. }
  33131. this._preActivateId = sceneRenderId;
  33132. this._instanceDataStorage.visibleInstances = null;
  33133. return this;
  33134. };
  33135. /** @hidden */
  33136. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  33137. if (this._instanceDataStorage.visibleInstances) {
  33138. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  33139. }
  33140. return this;
  33141. };
  33142. /** @hidden */
  33143. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  33144. if (!this._instanceDataStorage.visibleInstances) {
  33145. this._instanceDataStorage.visibleInstances = {};
  33146. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  33147. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  33148. }
  33149. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  33150. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  33151. }
  33152. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  33153. return this;
  33154. };
  33155. /**
  33156. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  33157. * This means the mesh underlying bounding box and sphere are recomputed.
  33158. * @returns the current mesh
  33159. */
  33160. Mesh.prototype.refreshBoundingInfo = function () {
  33161. return this._refreshBoundingInfo(false);
  33162. };
  33163. /** @hidden */
  33164. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  33165. if (this._boundingInfo && this._boundingInfo.isLocked) {
  33166. return this;
  33167. }
  33168. var data = this._getPositionData(applySkeleton);
  33169. if (data) {
  33170. var bias = this.geometry ? this.geometry.boundingBias : null;
  33171. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  33172. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33173. }
  33174. if (this.subMeshes) {
  33175. for (var index = 0; index < this.subMeshes.length; index++) {
  33176. this.subMeshes[index].refreshBoundingInfo();
  33177. }
  33178. }
  33179. this._updateBoundingInfo();
  33180. return this;
  33181. };
  33182. Mesh.prototype._getPositionData = function (applySkeleton) {
  33183. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33184. if (data && applySkeleton && this.skeleton) {
  33185. data = BABYLON.Tools.Slice(data);
  33186. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33187. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33188. if (matricesWeightsData && matricesIndicesData) {
  33189. var needExtras = this.numBoneInfluencers > 4;
  33190. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33191. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33192. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  33193. var tempVector = BABYLON.Tmp.Vector3[0];
  33194. var finalMatrix = BABYLON.Tmp.Matrix[0];
  33195. var tempMatrix = BABYLON.Tmp.Matrix[1];
  33196. var matWeightIdx = 0;
  33197. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  33198. finalMatrix.reset();
  33199. var inf;
  33200. var weight;
  33201. for (inf = 0; inf < 4; inf++) {
  33202. weight = matricesWeightsData[matWeightIdx + inf];
  33203. if (weight > 0) {
  33204. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33205. finalMatrix.addToSelf(tempMatrix);
  33206. }
  33207. }
  33208. if (needExtras) {
  33209. for (inf = 0; inf < 4; inf++) {
  33210. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33211. if (weight > 0) {
  33212. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33213. finalMatrix.addToSelf(tempMatrix);
  33214. }
  33215. }
  33216. }
  33217. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  33218. tempVector.toArray(data, index);
  33219. }
  33220. }
  33221. }
  33222. return data;
  33223. };
  33224. /** @hidden */
  33225. Mesh.prototype._createGlobalSubMesh = function (force) {
  33226. var totalVertices = this.getTotalVertices();
  33227. if (!totalVertices || !this.getIndices()) {
  33228. return null;
  33229. }
  33230. // Check if we need to recreate the submeshes
  33231. if (this.subMeshes && this.subMeshes.length > 0) {
  33232. var ib = this.getIndices();
  33233. if (!ib) {
  33234. return null;
  33235. }
  33236. var totalIndices = ib.length;
  33237. var needToRecreate = false;
  33238. if (force) {
  33239. needToRecreate = true;
  33240. }
  33241. else {
  33242. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33243. var submesh = _a[_i];
  33244. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  33245. needToRecreate = true;
  33246. break;
  33247. }
  33248. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  33249. needToRecreate = true;
  33250. break;
  33251. }
  33252. }
  33253. }
  33254. if (!needToRecreate) {
  33255. return this.subMeshes[0];
  33256. }
  33257. }
  33258. this.releaseSubMeshes();
  33259. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33260. };
  33261. /**
  33262. * This function will subdivide the mesh into multiple submeshes
  33263. * @param count defines the expected number of submeshes
  33264. */
  33265. Mesh.prototype.subdivide = function (count) {
  33266. if (count < 1) {
  33267. return;
  33268. }
  33269. var totalIndices = this.getTotalIndices();
  33270. var subdivisionSize = (totalIndices / count) | 0;
  33271. var offset = 0;
  33272. // Ensure that subdivisionSize is a multiple of 3
  33273. while (subdivisionSize % 3 !== 0) {
  33274. subdivisionSize++;
  33275. }
  33276. this.releaseSubMeshes();
  33277. for (var index = 0; index < count; index++) {
  33278. if (offset >= totalIndices) {
  33279. break;
  33280. }
  33281. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33282. offset += subdivisionSize;
  33283. }
  33284. this.synchronizeInstances();
  33285. };
  33286. /**
  33287. * Copy a FloatArray into a specific associated vertex buffer
  33288. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33289. * - BABYLON.VertexBuffer.PositionKind
  33290. * - BABYLON.VertexBuffer.UVKind
  33291. * - BABYLON.VertexBuffer.UV2Kind
  33292. * - BABYLON.VertexBuffer.UV3Kind
  33293. * - BABYLON.VertexBuffer.UV4Kind
  33294. * - BABYLON.VertexBuffer.UV5Kind
  33295. * - BABYLON.VertexBuffer.UV6Kind
  33296. * - BABYLON.VertexBuffer.ColorKind
  33297. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33298. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33299. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33300. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33301. * @param data defines the data source
  33302. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33303. * @param stride defines the data stride size (can be null)
  33304. * @returns the current mesh
  33305. */
  33306. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33307. if (updatable === void 0) { updatable = false; }
  33308. if (!this._geometry) {
  33309. var vertexData = new BABYLON.VertexData();
  33310. vertexData.set(data, kind);
  33311. var scene = this.getScene();
  33312. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33313. }
  33314. else {
  33315. this._geometry.setVerticesData(kind, data, updatable, stride);
  33316. }
  33317. return this;
  33318. };
  33319. /**
  33320. * Flags an associated vertex buffer as updatable
  33321. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33322. * - BABYLON.VertexBuffer.PositionKind
  33323. * - BABYLON.VertexBuffer.UVKind
  33324. * - BABYLON.VertexBuffer.UV2Kind
  33325. * - BABYLON.VertexBuffer.UV3Kind
  33326. * - BABYLON.VertexBuffer.UV4Kind
  33327. * - BABYLON.VertexBuffer.UV5Kind
  33328. * - BABYLON.VertexBuffer.UV6Kind
  33329. * - BABYLON.VertexBuffer.ColorKind
  33330. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33331. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33332. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33333. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33334. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33335. */
  33336. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33337. if (updatable === void 0) { updatable = true; }
  33338. var vb = this.getVertexBuffer(kind);
  33339. if (!vb || vb.isUpdatable() === updatable) {
  33340. return;
  33341. }
  33342. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33343. };
  33344. /**
  33345. * Sets the mesh global Vertex Buffer
  33346. * @param buffer defines the buffer to use
  33347. * @returns the current mesh
  33348. */
  33349. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33350. if (!this._geometry) {
  33351. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33352. }
  33353. this._geometry.setVerticesBuffer(buffer);
  33354. return this;
  33355. };
  33356. /**
  33357. * Update a specific associated vertex buffer
  33358. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33359. * - BABYLON.VertexBuffer.PositionKind
  33360. * - BABYLON.VertexBuffer.UVKind
  33361. * - BABYLON.VertexBuffer.UV2Kind
  33362. * - BABYLON.VertexBuffer.UV3Kind
  33363. * - BABYLON.VertexBuffer.UV4Kind
  33364. * - BABYLON.VertexBuffer.UV5Kind
  33365. * - BABYLON.VertexBuffer.UV6Kind
  33366. * - BABYLON.VertexBuffer.ColorKind
  33367. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33368. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33369. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33370. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33371. * @param data defines the data source
  33372. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33373. * @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)
  33374. * @returns the current mesh
  33375. */
  33376. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33377. if (!this._geometry) {
  33378. return this;
  33379. }
  33380. if (!makeItUnique) {
  33381. this._geometry.updateVerticesData(kind, data, updateExtends);
  33382. }
  33383. else {
  33384. this.makeGeometryUnique();
  33385. this.updateVerticesData(kind, data, updateExtends, false);
  33386. }
  33387. return this;
  33388. };
  33389. /**
  33390. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33391. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33392. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33393. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33394. * @returns the current mesh
  33395. */
  33396. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33397. if (computeNormals === void 0) { computeNormals = true; }
  33398. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33399. if (!positions) {
  33400. return this;
  33401. }
  33402. positionFunction(positions);
  33403. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33404. if (computeNormals) {
  33405. var indices = this.getIndices();
  33406. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33407. if (!normals) {
  33408. return this;
  33409. }
  33410. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33411. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33412. }
  33413. return this;
  33414. };
  33415. /**
  33416. * Creates a un-shared specific occurence of the geometry for the mesh.
  33417. * @returns the current mesh
  33418. */
  33419. Mesh.prototype.makeGeometryUnique = function () {
  33420. if (!this._geometry) {
  33421. return this;
  33422. }
  33423. var oldGeometry = this._geometry;
  33424. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33425. oldGeometry.releaseForMesh(this, true);
  33426. geometry.applyToMesh(this);
  33427. return this;
  33428. };
  33429. /**
  33430. * Set the index buffer of this mesh
  33431. * @param indices defines the source data
  33432. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33433. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33434. * @returns the current mesh
  33435. */
  33436. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33437. if (totalVertices === void 0) { totalVertices = null; }
  33438. if (updatable === void 0) { updatable = false; }
  33439. if (!this._geometry) {
  33440. var vertexData = new BABYLON.VertexData();
  33441. vertexData.indices = indices;
  33442. var scene = this.getScene();
  33443. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33444. }
  33445. else {
  33446. this._geometry.setIndices(indices, totalVertices, updatable);
  33447. }
  33448. return this;
  33449. };
  33450. /**
  33451. * Update the current index buffer
  33452. * @param indices defines the source data
  33453. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33454. * @returns the current mesh
  33455. */
  33456. Mesh.prototype.updateIndices = function (indices, offset) {
  33457. if (!this._geometry) {
  33458. return this;
  33459. }
  33460. this._geometry.updateIndices(indices, offset);
  33461. return this;
  33462. };
  33463. /**
  33464. * Invert the geometry to move from a right handed system to a left handed one.
  33465. * @returns the current mesh
  33466. */
  33467. Mesh.prototype.toLeftHanded = function () {
  33468. if (!this._geometry) {
  33469. return this;
  33470. }
  33471. this._geometry.toLeftHanded();
  33472. return this;
  33473. };
  33474. /** @hidden */
  33475. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33476. if (!this._geometry) {
  33477. return this;
  33478. }
  33479. var engine = this.getScene().getEngine();
  33480. // Wireframe
  33481. var indexToBind;
  33482. if (this._unIndexed) {
  33483. indexToBind = null;
  33484. }
  33485. else {
  33486. switch (fillMode) {
  33487. case BABYLON.Material.PointFillMode:
  33488. indexToBind = null;
  33489. break;
  33490. case BABYLON.Material.WireFrameFillMode:
  33491. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33492. break;
  33493. default:
  33494. case BABYLON.Material.TriangleFillMode:
  33495. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33496. break;
  33497. }
  33498. }
  33499. // VBOs
  33500. this._geometry._bind(effect, indexToBind);
  33501. return this;
  33502. };
  33503. /** @hidden */
  33504. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33505. if (alternate === void 0) { alternate = false; }
  33506. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33507. return this;
  33508. }
  33509. if (this._onBeforeDrawObservable) {
  33510. this._onBeforeDrawObservable.notifyObservers(this);
  33511. }
  33512. var scene = this.getScene();
  33513. var engine = scene.getEngine();
  33514. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33515. // or triangles as points
  33516. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33517. }
  33518. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33519. // Triangles as wireframe
  33520. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33521. }
  33522. else {
  33523. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33524. }
  33525. if (scene._isAlternateRenderingEnabled && !alternate) {
  33526. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33527. if (!effect || !scene.activeCamera) {
  33528. return this;
  33529. }
  33530. scene._switchToAlternateCameraConfiguration(true);
  33531. this._effectiveMaterial.bindView(effect);
  33532. this._effectiveMaterial.bindViewProjection(effect);
  33533. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33534. this._draw(subMesh, fillMode, instancesCount, true);
  33535. engine.setViewport(scene.activeCamera.viewport);
  33536. scene._switchToAlternateCameraConfiguration(false);
  33537. this._effectiveMaterial.bindView(effect);
  33538. this._effectiveMaterial.bindViewProjection(effect);
  33539. }
  33540. return this;
  33541. };
  33542. /**
  33543. * Registers for this mesh a javascript function called just before the rendering process
  33544. * @param func defines the function to call before rendering this mesh
  33545. * @returns the current mesh
  33546. */
  33547. Mesh.prototype.registerBeforeRender = function (func) {
  33548. this.onBeforeRenderObservable.add(func);
  33549. return this;
  33550. };
  33551. /**
  33552. * Disposes a previously registered javascript function called before the rendering
  33553. * @param func defines the function to remove
  33554. * @returns the current mesh
  33555. */
  33556. Mesh.prototype.unregisterBeforeRender = function (func) {
  33557. this.onBeforeRenderObservable.removeCallback(func);
  33558. return this;
  33559. };
  33560. /**
  33561. * Registers for this mesh a javascript function called just after the rendering is complete
  33562. * @param func defines the function to call after rendering this mesh
  33563. * @returns the current mesh
  33564. */
  33565. Mesh.prototype.registerAfterRender = function (func) {
  33566. this.onAfterRenderObservable.add(func);
  33567. return this;
  33568. };
  33569. /**
  33570. * Disposes a previously registered javascript function called after the rendering.
  33571. * @param func defines the function to remove
  33572. * @returns the current mesh
  33573. */
  33574. Mesh.prototype.unregisterAfterRender = function (func) {
  33575. this.onAfterRenderObservable.removeCallback(func);
  33576. return this;
  33577. };
  33578. /** @hidden */
  33579. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33580. var scene = this.getScene();
  33581. var batchCache = this._instanceDataStorage.batchCache;
  33582. batchCache.mustReturn = false;
  33583. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33584. batchCache.visibleInstances[subMeshId] = null;
  33585. if (this._instanceDataStorage.visibleInstances) {
  33586. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33587. var currentRenderId = scene.getRenderId();
  33588. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33589. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33590. var selfRenderId = this._renderId;
  33591. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33592. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33593. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33594. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33595. }
  33596. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33597. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33598. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33599. batchCache.mustReturn = true;
  33600. return batchCache;
  33601. }
  33602. if (currentRenderId !== selfRenderId) {
  33603. batchCache.renderSelf[subMeshId] = false;
  33604. }
  33605. }
  33606. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33607. }
  33608. return batchCache;
  33609. };
  33610. /** @hidden */
  33611. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33612. var visibleInstances = batch.visibleInstances[subMesh._id];
  33613. if (!visibleInstances) {
  33614. return this;
  33615. }
  33616. var matricesCount = visibleInstances.length + 1;
  33617. var bufferSize = matricesCount * 16 * 4;
  33618. var instanceStorage = this._instanceDataStorage;
  33619. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33620. var instancesBuffer = instanceStorage.instancesBuffer;
  33621. while (instanceStorage.instancesBufferSize < bufferSize) {
  33622. instanceStorage.instancesBufferSize *= 2;
  33623. }
  33624. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33625. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33626. }
  33627. var offset = 0;
  33628. var instancesCount = 0;
  33629. var world = this.getWorldMatrix();
  33630. if (batch.renderSelf[subMesh._id]) {
  33631. world.copyToArray(instanceStorage.instancesData, offset);
  33632. offset += 16;
  33633. instancesCount++;
  33634. }
  33635. if (visibleInstances) {
  33636. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33637. var instance = visibleInstances[instanceIndex];
  33638. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33639. offset += 16;
  33640. instancesCount++;
  33641. }
  33642. }
  33643. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33644. if (instancesBuffer) {
  33645. instancesBuffer.dispose();
  33646. }
  33647. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33648. instanceStorage.instancesBuffer = instancesBuffer;
  33649. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33650. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33651. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33652. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33653. }
  33654. else {
  33655. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33656. }
  33657. this._bind(subMesh, effect, fillMode);
  33658. this._draw(subMesh, fillMode, instancesCount);
  33659. engine.unbindInstanceAttributes();
  33660. return this;
  33661. };
  33662. /** @hidden */
  33663. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33664. var scene = this.getScene();
  33665. var engine = scene.getEngine();
  33666. if (hardwareInstancedRendering) {
  33667. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33668. }
  33669. else {
  33670. if (batch.renderSelf[subMesh._id]) {
  33671. // Draw
  33672. if (onBeforeDraw) {
  33673. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33674. }
  33675. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33676. }
  33677. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33678. if (visibleInstancesForSubMesh) {
  33679. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33680. var instance = visibleInstancesForSubMesh[instanceIndex];
  33681. // World
  33682. var world = instance.getWorldMatrix();
  33683. if (onBeforeDraw) {
  33684. onBeforeDraw(true, world, effectiveMaterial);
  33685. }
  33686. // Draw
  33687. this._draw(subMesh, fillMode);
  33688. }
  33689. }
  33690. }
  33691. return this;
  33692. };
  33693. /**
  33694. * 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
  33695. * @param subMesh defines the subMesh to render
  33696. * @param enableAlphaMode defines if alpha mode can be changed
  33697. * @returns the current mesh
  33698. */
  33699. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33700. if (this._checkOcclusionQuery()) {
  33701. return this;
  33702. }
  33703. var scene = this.getScene();
  33704. // Managing instances
  33705. var batch = this._getInstancesRenderList(subMesh._id);
  33706. if (batch.mustReturn) {
  33707. return this;
  33708. }
  33709. // Checking geometry state
  33710. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33711. return this;
  33712. }
  33713. if (this._onBeforeRenderObservable) {
  33714. this._onBeforeRenderObservable.notifyObservers(this);
  33715. }
  33716. var engine = scene.getEngine();
  33717. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33718. // Material
  33719. var material = subMesh.getMaterial();
  33720. if (!material) {
  33721. return this;
  33722. }
  33723. this._effectiveMaterial = material;
  33724. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33725. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33726. return this;
  33727. }
  33728. }
  33729. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33730. return this;
  33731. }
  33732. // Alpha mode
  33733. if (enableAlphaMode) {
  33734. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33735. }
  33736. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33737. var step = _a[_i];
  33738. step.action(this, subMesh, batch);
  33739. }
  33740. var effect;
  33741. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33742. effect = subMesh.effect;
  33743. }
  33744. else {
  33745. effect = this._effectiveMaterial.getEffect();
  33746. }
  33747. if (!effect) {
  33748. return this;
  33749. }
  33750. var sideOrientation = this.overrideMaterialSideOrientation;
  33751. if (sideOrientation == null) {
  33752. sideOrientation = this._effectiveMaterial.sideOrientation;
  33753. if (this._getWorldMatrixDeterminant() < 0) {
  33754. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33755. }
  33756. }
  33757. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33758. if (this._effectiveMaterial.forceDepthWrite) {
  33759. engine.setDepthWrite(true);
  33760. }
  33761. // Bind
  33762. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33763. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33764. this._bind(subMesh, effect, fillMode);
  33765. }
  33766. var world = this.getWorldMatrix();
  33767. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33768. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33769. }
  33770. else {
  33771. this._effectiveMaterial.bind(world, this);
  33772. }
  33773. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33774. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33775. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33776. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33777. }
  33778. // Draw
  33779. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33780. // Unbind
  33781. this._effectiveMaterial.unbind();
  33782. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33783. var step = _c[_b];
  33784. step.action(this, subMesh, batch);
  33785. }
  33786. if (this._onAfterRenderObservable) {
  33787. this._onAfterRenderObservable.notifyObservers(this);
  33788. }
  33789. return this;
  33790. };
  33791. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33792. if (isInstance && effectiveMaterial) {
  33793. effectiveMaterial.bindOnlyWorldMatrix(world);
  33794. }
  33795. };
  33796. /**
  33797. * Renormalize the mesh and patch it up if there are no weights
  33798. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33799. * However in the case of zero weights then we set just a single influence to 1.
  33800. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33801. */
  33802. Mesh.prototype.cleanMatrixWeights = function () {
  33803. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33805. this.normalizeSkinWeightsAndExtra();
  33806. }
  33807. else {
  33808. this.normalizeSkinFourWeights();
  33809. }
  33810. }
  33811. };
  33812. // faster 4 weight version.
  33813. Mesh.prototype.normalizeSkinFourWeights = function () {
  33814. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33815. var numWeights = matricesWeights.length;
  33816. for (var a = 0; a < numWeights; a += 4) {
  33817. // accumulate weights
  33818. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33819. // check for invalid weight and just set it to 1.
  33820. if (t === 0) {
  33821. matricesWeights[a] = 1;
  33822. }
  33823. else {
  33824. // renormalize so everything adds to 1 use reciprical
  33825. var recip = 1 / t;
  33826. matricesWeights[a] *= recip;
  33827. matricesWeights[a + 1] *= recip;
  33828. matricesWeights[a + 2] *= recip;
  33829. matricesWeights[a + 3] *= recip;
  33830. }
  33831. }
  33832. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33833. };
  33834. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33835. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33836. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33837. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33838. var numWeights = matricesWeights.length;
  33839. for (var a = 0; a < numWeights; a += 4) {
  33840. // accumulate weights
  33841. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33842. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33843. // check for invalid weight and just set it to 1.
  33844. if (t === 0) {
  33845. matricesWeights[a] = 1;
  33846. }
  33847. else {
  33848. // renormalize so everything adds to 1 use reciprical
  33849. var recip = 1 / t;
  33850. matricesWeights[a] *= recip;
  33851. matricesWeights[a + 1] *= recip;
  33852. matricesWeights[a + 2] *= recip;
  33853. matricesWeights[a + 3] *= recip;
  33854. // same goes for extras
  33855. matricesWeightsExtra[a] *= recip;
  33856. matricesWeightsExtra[a + 1] *= recip;
  33857. matricesWeightsExtra[a + 2] *= recip;
  33858. matricesWeightsExtra[a + 3] *= recip;
  33859. }
  33860. }
  33861. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33862. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33863. };
  33864. /**
  33865. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33866. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33867. * the user know there was an issue with importing the mesh
  33868. * @returns a validation object with skinned, valid and report string
  33869. */
  33870. Mesh.prototype.validateSkinning = function () {
  33871. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33872. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33873. if (matricesWeights === null || this.skeleton == null) {
  33874. return { skinned: false, valid: true, report: "not skinned" };
  33875. }
  33876. var numWeights = matricesWeights.length;
  33877. var numberNotSorted = 0;
  33878. var missingWeights = 0;
  33879. var maxUsedWeights = 0;
  33880. var numberNotNormalized = 0;
  33881. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33882. var usedWeightCounts = new Array();
  33883. for (var a = 0; a <= numInfluences; a++) {
  33884. usedWeightCounts[a] = 0;
  33885. }
  33886. var toleranceEpsilon = 0.001;
  33887. for (var a = 0; a < numWeights; a += 4) {
  33888. var lastWeight = matricesWeights[a];
  33889. var t = lastWeight;
  33890. var usedWeights = t === 0 ? 0 : 1;
  33891. for (var b = 1; b < numInfluences; b++) {
  33892. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33893. if (d > lastWeight) {
  33894. numberNotSorted++;
  33895. }
  33896. if (d !== 0) {
  33897. usedWeights++;
  33898. }
  33899. t += d;
  33900. lastWeight = d;
  33901. }
  33902. // count the buffer weights usage
  33903. usedWeightCounts[usedWeights]++;
  33904. // max influences
  33905. if (usedWeights > maxUsedWeights) {
  33906. maxUsedWeights = usedWeights;
  33907. }
  33908. // check for invalid weight and just set it to 1.
  33909. if (t === 0) {
  33910. missingWeights++;
  33911. }
  33912. else {
  33913. // renormalize so everything adds to 1 use reciprical
  33914. var recip = 1 / t;
  33915. var tolerance = 0;
  33916. for (b = 0; b < numInfluences; b++) {
  33917. if (b < 4) {
  33918. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33919. }
  33920. else {
  33921. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33922. }
  33923. }
  33924. // arbitary epsilon value for dicdating not normalized
  33925. if (tolerance > toleranceEpsilon) {
  33926. numberNotNormalized++;
  33927. }
  33928. }
  33929. }
  33930. // validate bone indices are in range of the skeleton
  33931. var numBones = this.skeleton.bones.length;
  33932. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33933. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33934. var numBadBoneIndices = 0;
  33935. for (var a = 0; a < numWeights; a++) {
  33936. for (var b = 0; b < numInfluences; b++) {
  33937. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33938. if (index >= numBones || index < 0) {
  33939. numBadBoneIndices++;
  33940. }
  33941. }
  33942. }
  33943. // log mesh stats
  33944. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33945. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33946. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33947. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33948. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33949. };
  33950. /** @hidden */
  33951. Mesh.prototype._checkDelayState = function () {
  33952. var scene = this.getScene();
  33953. if (this._geometry) {
  33954. this._geometry.load(scene);
  33955. }
  33956. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33957. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33958. this._queueLoad(scene);
  33959. }
  33960. return this;
  33961. };
  33962. Mesh.prototype._queueLoad = function (scene) {
  33963. var _this = this;
  33964. scene._addPendingData(this);
  33965. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33966. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33967. if (data instanceof ArrayBuffer) {
  33968. _this._delayLoadingFunction(data, _this);
  33969. }
  33970. else {
  33971. _this._delayLoadingFunction(JSON.parse(data), _this);
  33972. }
  33973. _this.instances.forEach(function (instance) {
  33974. instance._syncSubMeshes();
  33975. });
  33976. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33977. scene._removePendingData(_this);
  33978. }, function () { }, scene.offlineProvider, getBinaryData);
  33979. return this;
  33980. };
  33981. /**
  33982. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33983. * A mesh is in the frustum if its bounding box intersects the frustum
  33984. * @param frustumPlanes defines the frustum to test
  33985. * @returns true if the mesh is in the frustum planes
  33986. */
  33987. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33988. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33989. return false;
  33990. }
  33991. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33992. return false;
  33993. }
  33994. this._checkDelayState();
  33995. return true;
  33996. };
  33997. /**
  33998. * Sets the mesh material by the material or multiMaterial `id` property
  33999. * @param id is a string identifying the material or the multiMaterial
  34000. * @returns the current mesh
  34001. */
  34002. Mesh.prototype.setMaterialByID = function (id) {
  34003. var materials = this.getScene().materials;
  34004. var index;
  34005. for (index = materials.length - 1; index > -1; index--) {
  34006. if (materials[index].id === id) {
  34007. this.material = materials[index];
  34008. return this;
  34009. }
  34010. }
  34011. // Multi
  34012. var multiMaterials = this.getScene().multiMaterials;
  34013. for (index = multiMaterials.length - 1; index > -1; index--) {
  34014. if (multiMaterials[index].id === id) {
  34015. this.material = multiMaterials[index];
  34016. return this;
  34017. }
  34018. }
  34019. return this;
  34020. };
  34021. /**
  34022. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  34023. * @returns an array of IAnimatable
  34024. */
  34025. Mesh.prototype.getAnimatables = function () {
  34026. var results = new Array();
  34027. if (this.material) {
  34028. results.push(this.material);
  34029. }
  34030. if (this.skeleton) {
  34031. results.push(this.skeleton);
  34032. }
  34033. return results;
  34034. };
  34035. /**
  34036. * Modifies the mesh geometry according to the passed transformation matrix.
  34037. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  34038. * The mesh normals are modified using the same transformation.
  34039. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34040. * @param transform defines the transform matrix to use
  34041. * @see http://doc.babylonjs.com/resources/baking_transformations
  34042. * @returns the current mesh
  34043. */
  34044. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  34045. // Position
  34046. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34047. return this;
  34048. }
  34049. var submeshes = this.subMeshes.splice(0);
  34050. this._resetPointsArrayCache();
  34051. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34052. var temp = new Array();
  34053. var index;
  34054. for (index = 0; index < data.length; index += 3) {
  34055. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  34056. }
  34057. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  34058. // Normals
  34059. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34060. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34061. temp = [];
  34062. for (index = 0; index < data.length; index += 3) {
  34063. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  34064. }
  34065. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  34066. }
  34067. // flip faces?
  34068. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  34069. this.flipFaces();
  34070. }
  34071. // Restore submeshes
  34072. this.releaseSubMeshes();
  34073. this.subMeshes = submeshes;
  34074. return this;
  34075. };
  34076. /**
  34077. * Modifies the mesh geometry according to its own current World Matrix.
  34078. * The mesh World Matrix is then reset.
  34079. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  34080. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34081. * @see http://doc.babylonjs.com/resources/baking_transformations
  34082. * @returns the current mesh
  34083. */
  34084. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  34085. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  34086. this.scaling.copyFromFloats(1, 1, 1);
  34087. this.position.copyFromFloats(0, 0, 0);
  34088. this.rotation.copyFromFloats(0, 0, 0);
  34089. //only if quaternion is already set
  34090. if (this.rotationQuaternion) {
  34091. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  34092. }
  34093. this._worldMatrix = BABYLON.Matrix.Identity();
  34094. return this;
  34095. };
  34096. Object.defineProperty(Mesh.prototype, "_positions", {
  34097. // Cache
  34098. /** @hidden */
  34099. get: function () {
  34100. if (this._geometry) {
  34101. return this._geometry._positions;
  34102. }
  34103. return null;
  34104. },
  34105. enumerable: true,
  34106. configurable: true
  34107. });
  34108. /** @hidden */
  34109. Mesh.prototype._resetPointsArrayCache = function () {
  34110. if (this._geometry) {
  34111. this._geometry._resetPointsArrayCache();
  34112. }
  34113. return this;
  34114. };
  34115. /** @hidden */
  34116. Mesh.prototype._generatePointsArray = function () {
  34117. if (this._geometry) {
  34118. return this._geometry._generatePointsArray();
  34119. }
  34120. return false;
  34121. };
  34122. /**
  34123. * Returns a new Mesh object generated from the current mesh properties.
  34124. * This method must not get confused with createInstance()
  34125. * @param name is a string, the name given to the new mesh
  34126. * @param newParent can be any Node object (default `null`)
  34127. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  34128. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  34129. * @returns a new mesh
  34130. */
  34131. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  34132. if (name === void 0) { name = ""; }
  34133. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  34134. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  34135. };
  34136. /**
  34137. * Releases resources associated with this mesh.
  34138. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  34139. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  34140. */
  34141. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  34142. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  34143. this.morphTargetManager = null;
  34144. if (this._geometry) {
  34145. this._geometry.releaseForMesh(this, true);
  34146. }
  34147. if (this._onBeforeDrawObservable) {
  34148. this._onBeforeDrawObservable.clear();
  34149. }
  34150. if (this._onBeforeRenderObservable) {
  34151. this._onBeforeRenderObservable.clear();
  34152. }
  34153. if (this._onAfterRenderObservable) {
  34154. this._onAfterRenderObservable.clear();
  34155. }
  34156. // Sources
  34157. if (this._scene.useClonedMeshhMap) {
  34158. if (this.meshMap) {
  34159. for (var uniqueId in this.meshMap) {
  34160. var mesh = this.meshMap[uniqueId];
  34161. if (mesh) {
  34162. mesh._source = null;
  34163. this.meshMap[uniqueId] = undefined;
  34164. }
  34165. }
  34166. }
  34167. if (this._source && this._source.meshMap) {
  34168. this._source.meshMap[this.uniqueId] = undefined;
  34169. }
  34170. }
  34171. else {
  34172. var meshes = this.getScene().meshes;
  34173. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  34174. var abstractMesh = meshes_1[_i];
  34175. var mesh = abstractMesh;
  34176. if (mesh._source && mesh._source === this) {
  34177. mesh._source = null;
  34178. }
  34179. }
  34180. }
  34181. this._source = null;
  34182. // Instances
  34183. if (this._instanceDataStorage.instancesBuffer) {
  34184. this._instanceDataStorage.instancesBuffer.dispose();
  34185. this._instanceDataStorage.instancesBuffer = null;
  34186. }
  34187. while (this.instances.length) {
  34188. this.instances[0].dispose();
  34189. }
  34190. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  34191. };
  34192. /**
  34193. * Modifies the mesh geometry according to a displacement map.
  34194. * 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.
  34195. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34196. * @param url is a string, the URL from the image file is to be downloaded.
  34197. * @param minHeight is the lower limit of the displacement.
  34198. * @param maxHeight is the upper limit of the displacement.
  34199. * @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.
  34200. * @param uvOffset is an optional vector2 used to offset UV.
  34201. * @param uvScale is an optional vector2 used to scale UV.
  34202. * @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.
  34203. * @returns the Mesh.
  34204. */
  34205. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  34206. var _this = this;
  34207. if (forceUpdate === void 0) { forceUpdate = false; }
  34208. var scene = this.getScene();
  34209. var onload = function (img) {
  34210. // Getting height map data
  34211. var canvas = document.createElement("canvas");
  34212. var context = canvas.getContext("2d");
  34213. var heightMapWidth = img.width;
  34214. var heightMapHeight = img.height;
  34215. canvas.width = heightMapWidth;
  34216. canvas.height = heightMapHeight;
  34217. context.drawImage(img, 0, 0);
  34218. // Create VertexData from map data
  34219. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  34220. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  34221. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  34222. //execute success callback, if set
  34223. if (onSuccess) {
  34224. onSuccess(_this);
  34225. }
  34226. };
  34227. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  34228. return this;
  34229. };
  34230. /**
  34231. * Modifies the mesh geometry according to a displacementMap buffer.
  34232. * 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.
  34233. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34234. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  34235. * @param heightMapWidth is the width of the buffer image.
  34236. * @param heightMapHeight is the height of the buffer image.
  34237. * @param minHeight is the lower limit of the displacement.
  34238. * @param maxHeight is the upper limit of the displacement.
  34239. * @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.
  34240. * @param uvOffset is an optional vector2 used to offset UV.
  34241. * @param uvScale is an optional vector2 used to scale UV.
  34242. * @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.
  34243. * @returns the Mesh.
  34244. */
  34245. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  34246. if (forceUpdate === void 0) { forceUpdate = false; }
  34247. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  34248. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  34249. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34250. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  34251. return this;
  34252. }
  34253. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  34254. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34255. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34256. var position = BABYLON.Vector3.Zero();
  34257. var normal = BABYLON.Vector3.Zero();
  34258. var uv = BABYLON.Vector2.Zero();
  34259. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  34260. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  34261. for (var index = 0; index < positions.length; index += 3) {
  34262. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  34263. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  34264. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  34265. // Compute height
  34266. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  34267. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  34268. var pos = (u + v * heightMapWidth) * 4;
  34269. var r = buffer[pos] / 255.0;
  34270. var g = buffer[pos + 1] / 255.0;
  34271. var b = buffer[pos + 2] / 255.0;
  34272. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34273. normal.normalize();
  34274. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  34275. position = position.add(normal);
  34276. position.toArray(positions, index);
  34277. }
  34278. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34279. if (forceUpdate) {
  34280. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34281. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34282. }
  34283. else {
  34284. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34285. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34286. }
  34287. return this;
  34288. };
  34289. /**
  34290. * Modify the mesh to get a flat shading rendering.
  34291. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34292. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34293. * @returns current mesh
  34294. */
  34295. Mesh.prototype.convertToFlatShadedMesh = function () {
  34296. var kinds = this.getVerticesDataKinds();
  34297. var vbs = {};
  34298. var data = {};
  34299. var newdata = {};
  34300. var updatableNormals = false;
  34301. var kindIndex;
  34302. var kind;
  34303. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34304. kind = kinds[kindIndex];
  34305. var vertexBuffer = this.getVertexBuffer(kind);
  34306. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34307. updatableNormals = vertexBuffer.isUpdatable();
  34308. kinds.splice(kindIndex, 1);
  34309. kindIndex--;
  34310. continue;
  34311. }
  34312. vbs[kind] = vertexBuffer;
  34313. data[kind] = vbs[kind].getData();
  34314. newdata[kind] = [];
  34315. }
  34316. // Save previous submeshes
  34317. var previousSubmeshes = this.subMeshes.slice(0);
  34318. var indices = this.getIndices();
  34319. var totalIndices = this.getTotalIndices();
  34320. // Generating unique vertices per face
  34321. var index;
  34322. for (index = 0; index < totalIndices; index++) {
  34323. var vertexIndex = indices[index];
  34324. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34325. kind = kinds[kindIndex];
  34326. var stride = vbs[kind].getStrideSize();
  34327. for (var offset = 0; offset < stride; offset++) {
  34328. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34329. }
  34330. }
  34331. }
  34332. // Updating faces & normal
  34333. var normals = [];
  34334. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34335. for (index = 0; index < totalIndices; index += 3) {
  34336. indices[index] = index;
  34337. indices[index + 1] = index + 1;
  34338. indices[index + 2] = index + 2;
  34339. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34340. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34341. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34342. var p1p2 = p1.subtract(p2);
  34343. var p3p2 = p3.subtract(p2);
  34344. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34345. // Store same normals for every vertex
  34346. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34347. normals.push(normal.x);
  34348. normals.push(normal.y);
  34349. normals.push(normal.z);
  34350. }
  34351. }
  34352. this.setIndices(indices);
  34353. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34354. // Updating vertex buffers
  34355. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34356. kind = kinds[kindIndex];
  34357. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34358. }
  34359. // Updating submeshes
  34360. this.releaseSubMeshes();
  34361. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34362. var previousOne = previousSubmeshes[submeshIndex];
  34363. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34364. }
  34365. this.synchronizeInstances();
  34366. return this;
  34367. };
  34368. /**
  34369. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34370. * In other words, more vertices, no more indices and a single bigger VBO.
  34371. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34372. * @returns current mesh
  34373. */
  34374. Mesh.prototype.convertToUnIndexedMesh = function () {
  34375. var kinds = this.getVerticesDataKinds();
  34376. var vbs = {};
  34377. var data = {};
  34378. var newdata = {};
  34379. var kindIndex;
  34380. var kind;
  34381. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34382. kind = kinds[kindIndex];
  34383. var vertexBuffer = this.getVertexBuffer(kind);
  34384. vbs[kind] = vertexBuffer;
  34385. data[kind] = vbs[kind].getData();
  34386. newdata[kind] = [];
  34387. }
  34388. // Save previous submeshes
  34389. var previousSubmeshes = this.subMeshes.slice(0);
  34390. var indices = this.getIndices();
  34391. var totalIndices = this.getTotalIndices();
  34392. // Generating unique vertices per face
  34393. var index;
  34394. for (index = 0; index < totalIndices; index++) {
  34395. var vertexIndex = indices[index];
  34396. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34397. kind = kinds[kindIndex];
  34398. var stride = vbs[kind].getStrideSize();
  34399. for (var offset = 0; offset < stride; offset++) {
  34400. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34401. }
  34402. }
  34403. }
  34404. // Updating indices
  34405. for (index = 0; index < totalIndices; index += 3) {
  34406. indices[index] = index;
  34407. indices[index + 1] = index + 1;
  34408. indices[index + 2] = index + 2;
  34409. }
  34410. this.setIndices(indices);
  34411. // Updating vertex buffers
  34412. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34413. kind = kinds[kindIndex];
  34414. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34415. }
  34416. // Updating submeshes
  34417. this.releaseSubMeshes();
  34418. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34419. var previousOne = previousSubmeshes[submeshIndex];
  34420. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34421. }
  34422. this._unIndexed = true;
  34423. this.synchronizeInstances();
  34424. return this;
  34425. };
  34426. /**
  34427. * Inverses facet orientations.
  34428. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34429. * @param flipNormals will also inverts the normals
  34430. * @returns current mesh
  34431. */
  34432. Mesh.prototype.flipFaces = function (flipNormals) {
  34433. if (flipNormals === void 0) { flipNormals = false; }
  34434. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34435. var i;
  34436. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34437. for (i = 0; i < vertex_data.normals.length; i++) {
  34438. vertex_data.normals[i] *= -1;
  34439. }
  34440. }
  34441. if (vertex_data.indices) {
  34442. var temp;
  34443. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34444. // reassign indices
  34445. temp = vertex_data.indices[i + 1];
  34446. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34447. vertex_data.indices[i + 2] = temp;
  34448. }
  34449. }
  34450. vertex_data.applyToMesh(this);
  34451. return this;
  34452. };
  34453. // Instances
  34454. /**
  34455. * Creates a new InstancedMesh object from the mesh model.
  34456. * Warning : this method is not supported for Line mesh and LineSystem
  34457. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34458. * @param name defines the name of the new instance
  34459. * @returns a new InstancedMesh
  34460. */
  34461. Mesh.prototype.createInstance = function (name) {
  34462. return new BABYLON.InstancedMesh(name, this);
  34463. };
  34464. /**
  34465. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34466. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34467. * @returns the current mesh
  34468. */
  34469. Mesh.prototype.synchronizeInstances = function () {
  34470. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34471. var instance = this.instances[instanceIndex];
  34472. instance._syncSubMeshes();
  34473. }
  34474. return this;
  34475. };
  34476. /**
  34477. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34478. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34479. * This should be used together with the simplification to avoid disappearing triangles.
  34480. * @param successCallback an optional success callback to be called after the optimization finished.
  34481. * @returns the current mesh
  34482. */
  34483. Mesh.prototype.optimizeIndices = function (successCallback) {
  34484. var _this = this;
  34485. var indices = this.getIndices();
  34486. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34487. if (!positions || !indices) {
  34488. return this;
  34489. }
  34490. var vectorPositions = new Array();
  34491. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34492. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34493. }
  34494. var dupes = new Array();
  34495. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34496. var realPos = vectorPositions.length - 1 - iteration;
  34497. var testedPosition = vectorPositions[realPos];
  34498. for (var j = 0; j < realPos; ++j) {
  34499. var againstPosition = vectorPositions[j];
  34500. if (testedPosition.equals(againstPosition)) {
  34501. dupes[realPos] = j;
  34502. break;
  34503. }
  34504. }
  34505. }, function () {
  34506. for (var i = 0; i < indices.length; ++i) {
  34507. indices[i] = dupes[indices[i]] || indices[i];
  34508. }
  34509. //indices are now reordered
  34510. var originalSubMeshes = _this.subMeshes.slice(0);
  34511. _this.setIndices(indices);
  34512. _this.subMeshes = originalSubMeshes;
  34513. if (successCallback) {
  34514. successCallback(_this);
  34515. }
  34516. });
  34517. return this;
  34518. };
  34519. /**
  34520. * Serialize current mesh
  34521. * @param serializationObject defines the object which will receive the serialization data
  34522. */
  34523. Mesh.prototype.serialize = function (serializationObject) {
  34524. serializationObject.name = this.name;
  34525. serializationObject.id = this.id;
  34526. serializationObject.type = this.getClassName();
  34527. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34528. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34529. }
  34530. serializationObject.position = this.position.asArray();
  34531. if (this.rotationQuaternion) {
  34532. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34533. }
  34534. else if (this.rotation) {
  34535. serializationObject.rotation = this.rotation.asArray();
  34536. }
  34537. serializationObject.scaling = this.scaling.asArray();
  34538. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34539. serializationObject.isEnabled = this.isEnabled(false);
  34540. serializationObject.isVisible = this.isVisible;
  34541. serializationObject.infiniteDistance = this.infiniteDistance;
  34542. serializationObject.pickable = this.isPickable;
  34543. serializationObject.receiveShadows = this.receiveShadows;
  34544. serializationObject.billboardMode = this.billboardMode;
  34545. serializationObject.visibility = this.visibility;
  34546. serializationObject.checkCollisions = this.checkCollisions;
  34547. serializationObject.isBlocker = this.isBlocker;
  34548. // Parent
  34549. if (this.parent) {
  34550. serializationObject.parentId = this.parent.id;
  34551. }
  34552. // Geometry
  34553. serializationObject.isUnIndexed = this.isUnIndexed;
  34554. var geometry = this._geometry;
  34555. if (geometry) {
  34556. var geometryId = geometry.id;
  34557. serializationObject.geometryId = geometryId;
  34558. // SubMeshes
  34559. serializationObject.subMeshes = [];
  34560. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34561. var subMesh = this.subMeshes[subIndex];
  34562. serializationObject.subMeshes.push({
  34563. materialIndex: subMesh.materialIndex,
  34564. verticesStart: subMesh.verticesStart,
  34565. verticesCount: subMesh.verticesCount,
  34566. indexStart: subMesh.indexStart,
  34567. indexCount: subMesh.indexCount
  34568. });
  34569. }
  34570. }
  34571. // Material
  34572. if (this.material) {
  34573. serializationObject.materialId = this.material.id;
  34574. }
  34575. else {
  34576. this.material = null;
  34577. }
  34578. // Morph targets
  34579. if (this.morphTargetManager) {
  34580. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34581. }
  34582. // Skeleton
  34583. if (this.skeleton) {
  34584. serializationObject.skeletonId = this.skeleton.id;
  34585. }
  34586. // Physics
  34587. //TODO implement correct serialization for physics impostors.
  34588. var impostor = this.getPhysicsImpostor();
  34589. if (impostor) {
  34590. serializationObject.physicsMass = impostor.getParam("mass");
  34591. serializationObject.physicsFriction = impostor.getParam("friction");
  34592. serializationObject.physicsRestitution = impostor.getParam("mass");
  34593. serializationObject.physicsImpostor = impostor.type;
  34594. }
  34595. // Metadata
  34596. if (this.metadata) {
  34597. serializationObject.metadata = this.metadata;
  34598. }
  34599. // Instances
  34600. serializationObject.instances = [];
  34601. for (var index = 0; index < this.instances.length; index++) {
  34602. var instance = this.instances[index];
  34603. if (instance.doNotSerialize) {
  34604. continue;
  34605. }
  34606. var serializationInstance = {
  34607. name: instance.name,
  34608. id: instance.id,
  34609. position: instance.position.asArray(),
  34610. scaling: instance.scaling.asArray()
  34611. };
  34612. if (instance.parent) {
  34613. serializationInstance.parentId = instance.parent.id;
  34614. }
  34615. if (instance.rotationQuaternion) {
  34616. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34617. }
  34618. else if (instance.rotation) {
  34619. serializationInstance.rotation = instance.rotation.asArray();
  34620. }
  34621. serializationObject.instances.push(serializationInstance);
  34622. // Animations
  34623. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34624. serializationInstance.ranges = instance.serializeAnimationRanges();
  34625. }
  34626. //
  34627. // Animations
  34628. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34629. serializationObject.ranges = this.serializeAnimationRanges();
  34630. // Layer mask
  34631. serializationObject.layerMask = this.layerMask;
  34632. // Alpha
  34633. serializationObject.alphaIndex = this.alphaIndex;
  34634. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34635. // Overlay
  34636. serializationObject.overlayAlpha = this.overlayAlpha;
  34637. serializationObject.overlayColor = this.overlayColor.asArray();
  34638. serializationObject.renderOverlay = this.renderOverlay;
  34639. // Fog
  34640. serializationObject.applyFog = this.applyFog;
  34641. // Action Manager
  34642. if (this.actionManager) {
  34643. serializationObject.actions = this.actionManager.serialize(this.name);
  34644. }
  34645. };
  34646. /** @hidden */
  34647. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34648. if (!this.geometry) {
  34649. return;
  34650. }
  34651. this._markSubMeshesAsAttributesDirty();
  34652. var morphTargetManager = this._morphTargetManager;
  34653. if (morphTargetManager && morphTargetManager.vertexCount) {
  34654. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34655. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34656. this.morphTargetManager = null;
  34657. return;
  34658. }
  34659. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34660. var morphTarget = morphTargetManager.getActiveTarget(index);
  34661. var positions = morphTarget.getPositions();
  34662. if (!positions) {
  34663. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34664. return;
  34665. }
  34666. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34667. var normals = morphTarget.getNormals();
  34668. if (normals) {
  34669. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34670. }
  34671. var tangents = morphTarget.getTangents();
  34672. if (tangents) {
  34673. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34674. }
  34675. }
  34676. }
  34677. else {
  34678. var index = 0;
  34679. // Positions
  34680. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34681. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34682. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34683. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34684. }
  34685. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34686. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34687. }
  34688. index++;
  34689. }
  34690. }
  34691. };
  34692. // Statics
  34693. /**
  34694. * Returns a new Mesh object parsed from the source provided.
  34695. * @param parsedMesh is the source
  34696. * @param scene defines the hosting scene
  34697. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34698. * @returns a new Mesh
  34699. */
  34700. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34701. var mesh;
  34702. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34703. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34704. }
  34705. else {
  34706. mesh = new Mesh(parsedMesh.name, scene);
  34707. }
  34708. mesh.id = parsedMesh.id;
  34709. if (BABYLON.Tags) {
  34710. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34711. }
  34712. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34713. if (parsedMesh.metadata !== undefined) {
  34714. mesh.metadata = parsedMesh.metadata;
  34715. }
  34716. if (parsedMesh.rotationQuaternion) {
  34717. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34718. }
  34719. else if (parsedMesh.rotation) {
  34720. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34721. }
  34722. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34723. if (parsedMesh.localMatrix) {
  34724. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34725. }
  34726. else if (parsedMesh.pivotMatrix) {
  34727. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34728. }
  34729. mesh.setEnabled(parsedMesh.isEnabled);
  34730. mesh.isVisible = parsedMesh.isVisible;
  34731. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34732. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34733. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34734. if (parsedMesh.applyFog !== undefined) {
  34735. mesh.applyFog = parsedMesh.applyFog;
  34736. }
  34737. if (parsedMesh.pickable !== undefined) {
  34738. mesh.isPickable = parsedMesh.pickable;
  34739. }
  34740. if (parsedMesh.alphaIndex !== undefined) {
  34741. mesh.alphaIndex = parsedMesh.alphaIndex;
  34742. }
  34743. mesh.receiveShadows = parsedMesh.receiveShadows;
  34744. mesh.billboardMode = parsedMesh.billboardMode;
  34745. if (parsedMesh.visibility !== undefined) {
  34746. mesh.visibility = parsedMesh.visibility;
  34747. }
  34748. mesh.checkCollisions = parsedMesh.checkCollisions;
  34749. if (parsedMesh.isBlocker !== undefined) {
  34750. mesh.isBlocker = parsedMesh.isBlocker;
  34751. }
  34752. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34753. // freezeWorldMatrix
  34754. if (parsedMesh.freezeWorldMatrix) {
  34755. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34756. }
  34757. // Parent
  34758. if (parsedMesh.parentId) {
  34759. mesh._waitingParentId = parsedMesh.parentId;
  34760. }
  34761. // Actions
  34762. if (parsedMesh.actions !== undefined) {
  34763. mesh._waitingActions = parsedMesh.actions;
  34764. }
  34765. // Overlay
  34766. if (parsedMesh.overlayAlpha !== undefined) {
  34767. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34768. }
  34769. if (parsedMesh.overlayColor !== undefined) {
  34770. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34771. }
  34772. if (parsedMesh.renderOverlay !== undefined) {
  34773. mesh.renderOverlay = parsedMesh.renderOverlay;
  34774. }
  34775. // Geometry
  34776. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34777. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34778. if (parsedMesh.delayLoadingFile) {
  34779. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34780. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34781. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34782. if (parsedMesh._binaryInfo) {
  34783. mesh._binaryInfo = parsedMesh._binaryInfo;
  34784. }
  34785. mesh._delayInfo = [];
  34786. if (parsedMesh.hasUVs) {
  34787. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34788. }
  34789. if (parsedMesh.hasUVs2) {
  34790. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34791. }
  34792. if (parsedMesh.hasUVs3) {
  34793. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34794. }
  34795. if (parsedMesh.hasUVs4) {
  34796. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34797. }
  34798. if (parsedMesh.hasUVs5) {
  34799. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34800. }
  34801. if (parsedMesh.hasUVs6) {
  34802. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34803. }
  34804. if (parsedMesh.hasColors) {
  34805. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34806. }
  34807. if (parsedMesh.hasMatricesIndices) {
  34808. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34809. }
  34810. if (parsedMesh.hasMatricesWeights) {
  34811. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34812. }
  34813. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34814. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34815. mesh._checkDelayState();
  34816. }
  34817. }
  34818. else {
  34819. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34820. }
  34821. // Material
  34822. if (parsedMesh.materialId) {
  34823. mesh.setMaterialByID(parsedMesh.materialId);
  34824. }
  34825. else {
  34826. mesh.material = null;
  34827. }
  34828. // Morph targets
  34829. if (parsedMesh.morphTargetManagerId > -1) {
  34830. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34831. }
  34832. // Skeleton
  34833. if (parsedMesh.skeletonId > -1) {
  34834. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34835. if (parsedMesh.numBoneInfluencers) {
  34836. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34837. }
  34838. }
  34839. // Animations
  34840. if (parsedMesh.animations) {
  34841. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34842. var parsedAnimation = parsedMesh.animations[animationIndex];
  34843. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34844. }
  34845. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34846. }
  34847. if (parsedMesh.autoAnimate) {
  34848. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34849. }
  34850. // Layer Mask
  34851. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34852. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34853. }
  34854. else {
  34855. mesh.layerMask = 0x0FFFFFFF;
  34856. }
  34857. // Physics
  34858. if (parsedMesh.physicsImpostor) {
  34859. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34860. mass: parsedMesh.physicsMass,
  34861. friction: parsedMesh.physicsFriction,
  34862. restitution: parsedMesh.physicsRestitution
  34863. }, scene);
  34864. }
  34865. // Instances
  34866. if (parsedMesh.instances) {
  34867. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34868. var parsedInstance = parsedMesh.instances[index];
  34869. var instance = mesh.createInstance(parsedInstance.name);
  34870. if (parsedInstance.id) {
  34871. instance.id = parsedInstance.id;
  34872. }
  34873. if (BABYLON.Tags) {
  34874. if (parsedInstance.tags) {
  34875. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34876. }
  34877. else {
  34878. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34879. }
  34880. }
  34881. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34882. if (parsedInstance.parentId) {
  34883. instance._waitingParentId = parsedInstance.parentId;
  34884. }
  34885. if (parsedInstance.rotationQuaternion) {
  34886. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34887. }
  34888. else if (parsedInstance.rotation) {
  34889. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34890. }
  34891. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34892. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34893. instance.checkCollisions = parsedInstance.checkCollisions;
  34894. }
  34895. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34896. instance.isPickable = parsedInstance.pickable;
  34897. }
  34898. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34899. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34900. }
  34901. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34902. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34903. }
  34904. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34905. instance.alphaIndex = parsedInstance.alphaIndex;
  34906. }
  34907. // Physics
  34908. if (parsedInstance.physicsImpostor) {
  34909. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34910. mass: parsedInstance.physicsMass,
  34911. friction: parsedInstance.physicsFriction,
  34912. restitution: parsedInstance.physicsRestitution
  34913. }, scene);
  34914. }
  34915. // Animation
  34916. if (parsedInstance.animations) {
  34917. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34918. parsedAnimation = parsedInstance.animations[animationIndex];
  34919. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34920. }
  34921. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34922. if (parsedInstance.autoAnimate) {
  34923. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34924. }
  34925. }
  34926. }
  34927. }
  34928. return mesh;
  34929. };
  34930. /**
  34931. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34932. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34933. * @param name defines the name of the mesh to create
  34934. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34935. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34936. * @param closePath creates a seam between the first and the last points of each path of the path array
  34937. * @param offset is taken in account only if the `pathArray` is containing a single path
  34938. * @param scene defines the hosting scene
  34939. * @param updatable defines if the mesh must be flagged as updatable
  34940. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34941. * @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)
  34942. * @returns a new Mesh
  34943. */
  34944. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34945. if (closeArray === void 0) { closeArray = false; }
  34946. if (updatable === void 0) { updatable = false; }
  34947. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34948. pathArray: pathArray,
  34949. closeArray: closeArray,
  34950. closePath: closePath,
  34951. offset: offset,
  34952. updatable: updatable,
  34953. sideOrientation: sideOrientation,
  34954. instance: instance
  34955. }, scene);
  34956. };
  34957. /**
  34958. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34959. * @param name defines the name of the mesh to create
  34960. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34961. * @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
  34962. * @param scene defines the hosting scene
  34963. * @param updatable defines if the mesh must be flagged as updatable
  34964. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34965. * @returns a new Mesh
  34966. */
  34967. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34968. if (scene === void 0) { scene = null; }
  34969. var options = {
  34970. radius: radius,
  34971. tessellation: tessellation,
  34972. sideOrientation: sideOrientation,
  34973. updatable: updatable
  34974. };
  34975. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34976. };
  34977. /**
  34978. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34979. * @param name defines the name of the mesh to create
  34980. * @param size sets the size (float) of each box side (default 1)
  34981. * @param scene defines the hosting scene
  34982. * @param updatable defines if the mesh must be flagged as updatable
  34983. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34984. * @returns a new Mesh
  34985. */
  34986. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34987. if (scene === void 0) { scene = null; }
  34988. var options = {
  34989. size: size,
  34990. sideOrientation: sideOrientation,
  34991. updatable: updatable
  34992. };
  34993. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34994. };
  34995. /**
  34996. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34997. * @param name defines the name of the mesh to create
  34998. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34999. * @param diameter sets the diameter size (float) of the sphere (default 1)
  35000. * @param scene defines the hosting scene
  35001. * @param updatable defines if the mesh must be flagged as updatable
  35002. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35003. * @returns a new Mesh
  35004. */
  35005. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  35006. var options = {
  35007. segments: segments,
  35008. diameterX: diameter,
  35009. diameterY: diameter,
  35010. diameterZ: diameter,
  35011. sideOrientation: sideOrientation,
  35012. updatable: updatable
  35013. };
  35014. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  35015. };
  35016. /**
  35017. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  35018. * @param name defines the name of the mesh to create
  35019. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  35020. * @param diameterTop set the top cap diameter (floats, default 1)
  35021. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  35022. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  35023. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  35024. * @param scene defines the hosting scene
  35025. * @param updatable defines if the mesh must be flagged as updatable
  35026. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35027. * @returns a new Mesh
  35028. */
  35029. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  35030. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  35031. if (scene !== undefined) {
  35032. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  35033. updatable = scene;
  35034. }
  35035. scene = subdivisions;
  35036. subdivisions = 1;
  35037. }
  35038. var options = {
  35039. height: height,
  35040. diameterTop: diameterTop,
  35041. diameterBottom: diameterBottom,
  35042. tessellation: tessellation,
  35043. subdivisions: subdivisions,
  35044. sideOrientation: sideOrientation,
  35045. updatable: updatable
  35046. };
  35047. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  35048. };
  35049. // Torus (Code from SharpDX.org)
  35050. /**
  35051. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  35052. * @param name defines the name of the mesh to create
  35053. * @param diameter sets the diameter size (float) of the torus (default 1)
  35054. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  35055. * @param tessellation sets the number of torus sides (postive integer, default 16)
  35056. * @param scene defines the hosting scene
  35057. * @param updatable defines if the mesh must be flagged as updatable
  35058. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35059. * @returns a new Mesh
  35060. */
  35061. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  35062. var options = {
  35063. diameter: diameter,
  35064. thickness: thickness,
  35065. tessellation: tessellation,
  35066. sideOrientation: sideOrientation,
  35067. updatable: updatable
  35068. };
  35069. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  35070. };
  35071. /**
  35072. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  35073. * @param name defines the name of the mesh to create
  35074. * @param radius sets the global radius size (float) of the torus knot (default 2)
  35075. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  35076. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  35077. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  35078. * @param p the number of windings on X axis (positive integers, default 2)
  35079. * @param q the number of windings on Y axis (positive integers, default 3)
  35080. * @param scene defines the hosting scene
  35081. * @param updatable defines if the mesh must be flagged as updatable
  35082. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35083. * @returns a new Mesh
  35084. */
  35085. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  35086. var options = {
  35087. radius: radius,
  35088. tube: tube,
  35089. radialSegments: radialSegments,
  35090. tubularSegments: tubularSegments,
  35091. p: p,
  35092. q: q,
  35093. sideOrientation: sideOrientation,
  35094. updatable: updatable
  35095. };
  35096. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  35097. };
  35098. /**
  35099. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  35100. * @param name defines the name of the mesh to create
  35101. * @param points is an array successive Vector3
  35102. * @param scene defines the hosting scene
  35103. * @param updatable defines if the mesh must be flagged as updatable
  35104. * @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).
  35105. * @returns a new Mesh
  35106. */
  35107. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  35108. if (scene === void 0) { scene = null; }
  35109. if (updatable === void 0) { updatable = false; }
  35110. if (instance === void 0) { instance = null; }
  35111. var options = {
  35112. points: points,
  35113. updatable: updatable,
  35114. instance: instance
  35115. };
  35116. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  35117. };
  35118. /**
  35119. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  35120. * @param name defines the name of the mesh to create
  35121. * @param points is an array successive Vector3
  35122. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  35123. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  35124. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  35125. * @param scene defines the hosting scene
  35126. * @param updatable defines if the mesh must be flagged as updatable
  35127. * @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)
  35128. * @returns a new Mesh
  35129. */
  35130. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  35131. if (scene === void 0) { scene = null; }
  35132. var options = {
  35133. points: points,
  35134. dashSize: dashSize,
  35135. gapSize: gapSize,
  35136. dashNb: dashNb,
  35137. updatable: updatable,
  35138. instance: instance
  35139. };
  35140. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  35141. };
  35142. /**
  35143. * Creates a polygon mesh.
  35144. * Please consider using the same method from the MeshBuilder class instead.
  35145. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  35146. * 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.
  35147. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  35149. * Remember you can only change the shape positions, not their number when updating a polygon.
  35150. */
  35151. /**
  35152. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  35153. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  35154. * @param name defines the name of the mesh to create
  35155. * @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
  35156. * @param scene defines the hosting scene
  35157. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35158. * @param updatable defines if the mesh must be flagged as updatable
  35159. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35160. * @returns a new Mesh
  35161. */
  35162. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  35163. var options = {
  35164. shape: shape,
  35165. holes: holes,
  35166. updatable: updatable,
  35167. sideOrientation: sideOrientation
  35168. };
  35169. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  35170. };
  35171. /**
  35172. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  35173. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  35174. * @param name defines the name of the mesh to create
  35175. * @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
  35176. * @param depth defines the height of extrusion
  35177. * @param scene defines the hosting scene
  35178. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35179. * @param updatable defines if the mesh must be flagged as updatable
  35180. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35181. * @returns a new Mesh
  35182. */
  35183. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  35184. var options = {
  35185. shape: shape,
  35186. holes: holes,
  35187. depth: depth,
  35188. updatable: updatable,
  35189. sideOrientation: sideOrientation
  35190. };
  35191. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  35192. };
  35193. /**
  35194. * Creates an extruded shape mesh.
  35195. * 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
  35196. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35197. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35198. * @param name defines the name of the mesh to create
  35199. * @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
  35200. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35201. * @param scale is the value to scale the shape
  35202. * @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
  35203. * @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
  35204. * @param scene defines the hosting scene
  35205. * @param updatable defines if the mesh must be flagged as updatable
  35206. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35207. * @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)
  35208. * @returns a new Mesh
  35209. */
  35210. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  35211. if (scene === void 0) { scene = null; }
  35212. var options = {
  35213. shape: shape,
  35214. path: path,
  35215. scale: scale,
  35216. rotation: rotation,
  35217. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35218. sideOrientation: sideOrientation,
  35219. instance: instance,
  35220. updatable: updatable
  35221. };
  35222. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  35223. };
  35224. /**
  35225. * Creates an custom extruded shape mesh.
  35226. * The custom extrusion is a parametric shape.
  35227. * It has no predefined shape. Its final shape will depend on the input parameters.
  35228. * Please consider using the same method from the MeshBuilder class instead
  35229. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35230. * @param name defines the name of the mesh to create
  35231. * @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
  35232. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35233. * @param scaleFunction is a custom Javascript function called on each path point
  35234. * @param rotationFunction is a custom Javascript function called on each path point
  35235. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  35236. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  35237. * @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
  35238. * @param scene defines the hosting scene
  35239. * @param updatable defines if the mesh must be flagged as updatable
  35240. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35241. * @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)
  35242. * @returns a new Mesh
  35243. */
  35244. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  35245. var options = {
  35246. shape: shape,
  35247. path: path,
  35248. scaleFunction: scaleFunction,
  35249. rotationFunction: rotationFunction,
  35250. ribbonCloseArray: ribbonCloseArray,
  35251. ribbonClosePath: ribbonClosePath,
  35252. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35253. sideOrientation: sideOrientation,
  35254. instance: instance,
  35255. updatable: updatable
  35256. };
  35257. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  35258. };
  35259. /**
  35260. * Creates lathe mesh.
  35261. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  35262. * Please consider using the same method from the MeshBuilder class instead
  35263. * @param name defines the name of the mesh to create
  35264. * @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
  35265. * @param radius is the radius value of the lathe
  35266. * @param tessellation is the side number of the lathe.
  35267. * @param scene defines the hosting scene
  35268. * @param updatable defines if the mesh must be flagged as updatable
  35269. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35270. * @returns a new Mesh
  35271. */
  35272. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  35273. var options = {
  35274. shape: shape,
  35275. radius: radius,
  35276. tessellation: tessellation,
  35277. sideOrientation: sideOrientation,
  35278. updatable: updatable
  35279. };
  35280. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35281. };
  35282. /**
  35283. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35284. * @param name defines the name of the mesh to create
  35285. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35286. * @param scene defines the hosting scene
  35287. * @param updatable defines if the mesh must be flagged as updatable
  35288. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35289. * @returns a new Mesh
  35290. */
  35291. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35292. var options = {
  35293. size: size,
  35294. width: size,
  35295. height: size,
  35296. sideOrientation: sideOrientation,
  35297. updatable: updatable
  35298. };
  35299. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35300. };
  35301. /**
  35302. * Creates a ground mesh.
  35303. * Please consider using the same method from the MeshBuilder class instead
  35304. * @param name defines the name of the mesh to create
  35305. * @param width set the width of the ground
  35306. * @param height set the height of the ground
  35307. * @param subdivisions sets the number of subdivisions per side
  35308. * @param scene defines the hosting scene
  35309. * @param updatable defines if the mesh must be flagged as updatable
  35310. * @returns a new Mesh
  35311. */
  35312. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35313. var options = {
  35314. width: width,
  35315. height: height,
  35316. subdivisions: subdivisions,
  35317. updatable: updatable
  35318. };
  35319. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35320. };
  35321. /**
  35322. * Creates a tiled ground mesh.
  35323. * Please consider using the same method from the MeshBuilder class instead
  35324. * @param name defines the name of the mesh to create
  35325. * @param xmin set the ground minimum X coordinate
  35326. * @param zmin set the ground minimum Y coordinate
  35327. * @param xmax set the ground maximum X coordinate
  35328. * @param zmax set the ground maximum Z coordinate
  35329. * @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
  35330. * @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
  35331. * @param scene defines the hosting scene
  35332. * @param updatable defines if the mesh must be flagged as updatable
  35333. * @returns a new Mesh
  35334. */
  35335. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35336. var options = {
  35337. xmin: xmin,
  35338. zmin: zmin,
  35339. xmax: xmax,
  35340. zmax: zmax,
  35341. subdivisions: subdivisions,
  35342. precision: precision,
  35343. updatable: updatable
  35344. };
  35345. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35346. };
  35347. /**
  35348. * Creates a ground mesh from a height map.
  35349. * Please consider using the same method from the MeshBuilder class instead
  35350. * @see http://doc.babylonjs.com/babylon101/height_map
  35351. * @param name defines the name of the mesh to create
  35352. * @param url sets the URL of the height map image resource
  35353. * @param width set the ground width size
  35354. * @param height set the ground height size
  35355. * @param subdivisions sets the number of subdivision per side
  35356. * @param minHeight is the minimum altitude on the ground
  35357. * @param maxHeight is the maximum altitude on the ground
  35358. * @param scene defines the hosting scene
  35359. * @param updatable defines if the mesh must be flagged as updatable
  35360. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35361. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35362. * @returns a new Mesh
  35363. */
  35364. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35365. var options = {
  35366. width: width,
  35367. height: height,
  35368. subdivisions: subdivisions,
  35369. minHeight: minHeight,
  35370. maxHeight: maxHeight,
  35371. updatable: updatable,
  35372. onReady: onReady,
  35373. alphaFilter: alphaFilter
  35374. };
  35375. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35376. };
  35377. /**
  35378. * Creates a tube mesh.
  35379. * The tube is a parametric shape.
  35380. * It has no predefined shape. Its final shape will depend on the input parameters.
  35381. * Please consider using the same method from the MeshBuilder class instead
  35382. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35383. * @param name defines the name of the mesh to create
  35384. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35385. * @param radius sets the tube radius size
  35386. * @param tessellation is the number of sides on the tubular surface
  35387. * @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
  35388. * @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
  35389. * @param scene defines the hosting scene
  35390. * @param updatable defines if the mesh must be flagged as updatable
  35391. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35392. * @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)
  35393. * @returns a new Mesh
  35394. */
  35395. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35396. var options = {
  35397. path: path,
  35398. radius: radius,
  35399. tessellation: tessellation,
  35400. radiusFunction: radiusFunction,
  35401. arc: 1,
  35402. cap: cap,
  35403. updatable: updatable,
  35404. sideOrientation: sideOrientation,
  35405. instance: instance
  35406. };
  35407. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35408. };
  35409. /**
  35410. * Creates a polyhedron mesh.
  35411. * Please consider using the same method from the MeshBuilder class instead.
  35412. * * 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
  35413. * * The parameter `size` (positive float, default 1) sets the polygon size
  35414. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35415. * * 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`
  35416. * * 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
  35417. * * 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)`)
  35418. * * 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
  35419. * * 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
  35420. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35421. * * 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
  35422. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35423. * @param name defines the name of the mesh to create
  35424. * @param options defines the options used to create the mesh
  35425. * @param scene defines the hosting scene
  35426. * @returns a new Mesh
  35427. */
  35428. Mesh.CreatePolyhedron = function (name, options, scene) {
  35429. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35430. };
  35431. /**
  35432. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35433. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35434. * * 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`)
  35435. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35436. * * 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
  35437. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35438. * * 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
  35439. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35440. * @param name defines the name of the mesh
  35441. * @param options defines the options used to create the mesh
  35442. * @param scene defines the hosting scene
  35443. * @returns a new Mesh
  35444. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35445. */
  35446. Mesh.CreateIcoSphere = function (name, options, scene) {
  35447. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35448. };
  35449. /**
  35450. * Creates a decal mesh.
  35451. * Please consider using the same method from the MeshBuilder class instead.
  35452. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35453. * @param name defines the name of the mesh
  35454. * @param sourceMesh defines the mesh receiving the decal
  35455. * @param position sets the position of the decal in world coordinates
  35456. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35457. * @param size sets the decal scaling
  35458. * @param angle sets the angle to rotate the decal
  35459. * @returns a new Mesh
  35460. */
  35461. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35462. var options = {
  35463. position: position,
  35464. normal: normal,
  35465. size: size,
  35466. angle: angle
  35467. };
  35468. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35469. };
  35470. // Skeletons
  35471. /**
  35472. * Prepare internal position array for software CPU skinning
  35473. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35474. */
  35475. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35476. if (!this._sourcePositions) {
  35477. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35478. if (!source) {
  35479. return this._sourcePositions;
  35480. }
  35481. this._sourcePositions = new Float32Array(source);
  35482. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35483. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35484. }
  35485. }
  35486. return this._sourcePositions;
  35487. };
  35488. /**
  35489. * Prepare internal normal array for software CPU skinning
  35490. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35491. */
  35492. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35493. if (!this._sourceNormals) {
  35494. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35495. if (!source) {
  35496. return this._sourceNormals;
  35497. }
  35498. this._sourceNormals = new Float32Array(source);
  35499. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35500. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35501. }
  35502. }
  35503. return this._sourceNormals;
  35504. };
  35505. /**
  35506. * Updates the vertex buffer by applying transformation from the bones
  35507. * @param skeleton defines the skeleton to apply to current mesh
  35508. * @returns the current mesh
  35509. */
  35510. Mesh.prototype.applySkeleton = function (skeleton) {
  35511. if (!this.geometry) {
  35512. return this;
  35513. }
  35514. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35515. return this;
  35516. }
  35517. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35518. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35519. return this;
  35520. }
  35521. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35522. return this;
  35523. }
  35524. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35525. return this;
  35526. }
  35527. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35528. return this;
  35529. }
  35530. if (!this._sourcePositions) {
  35531. var submeshes = this.subMeshes.slice();
  35532. this.setPositionsForCPUSkinning();
  35533. this.subMeshes = submeshes;
  35534. }
  35535. if (!this._sourceNormals) {
  35536. this.setNormalsForCPUSkinning();
  35537. }
  35538. // positionsData checks for not being Float32Array will only pass at most once
  35539. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35540. if (!positionsData) {
  35541. return this;
  35542. }
  35543. if (!(positionsData instanceof Float32Array)) {
  35544. positionsData = new Float32Array(positionsData);
  35545. }
  35546. // normalsData checks for not being Float32Array will only pass at most once
  35547. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35548. if (!normalsData) {
  35549. return this;
  35550. }
  35551. if (!(normalsData instanceof Float32Array)) {
  35552. normalsData = new Float32Array(normalsData);
  35553. }
  35554. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35555. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35556. if (!matricesWeightsData || !matricesIndicesData) {
  35557. return this;
  35558. }
  35559. var needExtras = this.numBoneInfluencers > 4;
  35560. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35561. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35562. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35563. var tempVector3 = BABYLON.Vector3.Zero();
  35564. var finalMatrix = new BABYLON.Matrix();
  35565. var tempMatrix = new BABYLON.Matrix();
  35566. var matWeightIdx = 0;
  35567. var inf;
  35568. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35569. var weight;
  35570. for (inf = 0; inf < 4; inf++) {
  35571. weight = matricesWeightsData[matWeightIdx + inf];
  35572. if (weight > 0) {
  35573. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35574. finalMatrix.addToSelf(tempMatrix);
  35575. }
  35576. }
  35577. if (needExtras) {
  35578. for (inf = 0; inf < 4; inf++) {
  35579. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35580. if (weight > 0) {
  35581. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35582. finalMatrix.addToSelf(tempMatrix);
  35583. }
  35584. }
  35585. }
  35586. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35587. tempVector3.toArray(positionsData, index);
  35588. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35589. tempVector3.toArray(normalsData, index);
  35590. finalMatrix.reset();
  35591. }
  35592. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35593. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35594. return this;
  35595. };
  35596. // Tools
  35597. /**
  35598. * 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
  35599. * @param meshes defines the list of meshes to scan
  35600. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35601. */
  35602. Mesh.MinMax = function (meshes) {
  35603. var minVector = null;
  35604. var maxVector = null;
  35605. meshes.forEach(function (mesh, index, array) {
  35606. var boundingInfo = mesh.getBoundingInfo();
  35607. var boundingBox = boundingInfo.boundingBox;
  35608. if (!minVector || !maxVector) {
  35609. minVector = boundingBox.minimumWorld;
  35610. maxVector = boundingBox.maximumWorld;
  35611. }
  35612. else {
  35613. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35614. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35615. }
  35616. });
  35617. if (!minVector || !maxVector) {
  35618. return {
  35619. min: BABYLON.Vector3.Zero(),
  35620. max: BABYLON.Vector3.Zero()
  35621. };
  35622. }
  35623. return {
  35624. min: minVector,
  35625. max: maxVector
  35626. };
  35627. };
  35628. /**
  35629. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35630. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35631. * @returns a vector3
  35632. */
  35633. Mesh.Center = function (meshesOrMinMaxVector) {
  35634. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35635. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35636. };
  35637. /**
  35638. * Merge the array of meshes into a single mesh for performance reasons.
  35639. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35640. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35641. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35642. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35643. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35644. * @returns a new mesh
  35645. */
  35646. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35647. if (disposeSource === void 0) { disposeSource = true; }
  35648. var index;
  35649. if (!allow32BitsIndices) {
  35650. var totalVertices = 0;
  35651. // Counting vertices
  35652. for (index = 0; index < meshes.length; index++) {
  35653. if (meshes[index]) {
  35654. totalVertices += meshes[index].getTotalVertices();
  35655. if (totalVertices > 65536) {
  35656. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35657. return null;
  35658. }
  35659. }
  35660. }
  35661. }
  35662. // Merge
  35663. var vertexData = null;
  35664. var otherVertexData;
  35665. var indiceArray = new Array();
  35666. var source = null;
  35667. for (index = 0; index < meshes.length; index++) {
  35668. if (meshes[index]) {
  35669. var wm = meshes[index].computeWorldMatrix(true);
  35670. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35671. otherVertexData.transform(wm);
  35672. if (vertexData) {
  35673. vertexData.merge(otherVertexData, allow32BitsIndices);
  35674. }
  35675. else {
  35676. vertexData = otherVertexData;
  35677. source = meshes[index];
  35678. }
  35679. if (subdivideWithSubMeshes) {
  35680. indiceArray.push(meshes[index].getTotalIndices());
  35681. }
  35682. }
  35683. }
  35684. source = source;
  35685. if (!meshSubclass) {
  35686. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35687. }
  35688. vertexData.applyToMesh(meshSubclass);
  35689. // Setting properties
  35690. meshSubclass.material = source.material;
  35691. meshSubclass.checkCollisions = source.checkCollisions;
  35692. // Cleaning
  35693. if (disposeSource) {
  35694. for (index = 0; index < meshes.length; index++) {
  35695. if (meshes[index]) {
  35696. meshes[index].dispose();
  35697. }
  35698. }
  35699. }
  35700. // Subdivide
  35701. if (subdivideWithSubMeshes) {
  35702. //-- removal of global submesh
  35703. meshSubclass.releaseSubMeshes();
  35704. index = 0;
  35705. var offset = 0;
  35706. //-- apply subdivision according to index table
  35707. while (index < indiceArray.length) {
  35708. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35709. offset += indiceArray[index];
  35710. index++;
  35711. }
  35712. }
  35713. return meshSubclass;
  35714. };
  35715. /** @hidden */
  35716. Mesh.prototype.addInstance = function (instance) {
  35717. instance._indexInSourceMeshInstanceArray = this.instances.length;
  35718. this.instances.push(instance);
  35719. };
  35720. /** @hidden */
  35721. Mesh.prototype.removeInstance = function (instance) {
  35722. // Remove from mesh
  35723. var index = instance._indexInSourceMeshInstanceArray;
  35724. if (index != -1) {
  35725. if (index !== this.instances.length - 1) {
  35726. var last = this.instances[this.instances.length - 1];
  35727. this.instances[index] = last;
  35728. last._indexInSourceMeshInstanceArray = index;
  35729. }
  35730. instance._indexInSourceMeshInstanceArray = -1;
  35731. this.instances.pop();
  35732. }
  35733. };
  35734. // Consts
  35735. /**
  35736. * Mesh side orientation : usually the external or front surface
  35737. */
  35738. Mesh.FRONTSIDE = 0;
  35739. /**
  35740. * Mesh side orientation : usually the internal or back surface
  35741. */
  35742. Mesh.BACKSIDE = 1;
  35743. /**
  35744. * Mesh side orientation : both internal and external or front and back surfaces
  35745. */
  35746. Mesh.DOUBLESIDE = 2;
  35747. /**
  35748. * Mesh side orientation : by default, `FRONTSIDE`
  35749. */
  35750. Mesh.DEFAULTSIDE = 0;
  35751. /**
  35752. * Mesh cap setting : no cap
  35753. */
  35754. Mesh.NO_CAP = 0;
  35755. /**
  35756. * Mesh cap setting : one cap at the beginning of the mesh
  35757. */
  35758. Mesh.CAP_START = 1;
  35759. /**
  35760. * Mesh cap setting : one cap at the end of the mesh
  35761. */
  35762. Mesh.CAP_END = 2;
  35763. /**
  35764. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35765. */
  35766. Mesh.CAP_ALL = 3;
  35767. return Mesh;
  35768. }(BABYLON.AbstractMesh));
  35769. BABYLON.Mesh = Mesh;
  35770. })(BABYLON || (BABYLON = {}));
  35771. //# sourceMappingURL=babylon.mesh.js.map
  35772. var BABYLON;
  35773. (function (BABYLON) {
  35774. /**
  35775. * Base class for submeshes
  35776. */
  35777. var BaseSubMesh = /** @class */ (function () {
  35778. function BaseSubMesh() {
  35779. }
  35780. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35781. /**
  35782. * Gets associated effect
  35783. */
  35784. get: function () {
  35785. return this._materialEffect;
  35786. },
  35787. enumerable: true,
  35788. configurable: true
  35789. });
  35790. /**
  35791. * Sets associated effect (effect used to render this submesh)
  35792. * @param effect defines the effect to associate with
  35793. * @param defines defines the set of defines used to compile this effect
  35794. */
  35795. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35796. if (defines === void 0) { defines = null; }
  35797. if (this._materialEffect === effect) {
  35798. if (!effect) {
  35799. this._materialDefines = null;
  35800. }
  35801. return;
  35802. }
  35803. this._materialDefines = defines;
  35804. this._materialEffect = effect;
  35805. };
  35806. return BaseSubMesh;
  35807. }());
  35808. BABYLON.BaseSubMesh = BaseSubMesh;
  35809. /**
  35810. * Defines a subdivision inside a mesh
  35811. */
  35812. var SubMesh = /** @class */ (function (_super) {
  35813. __extends(SubMesh, _super);
  35814. /**
  35815. * Creates a new submesh
  35816. * @param materialIndex defines the material index to use
  35817. * @param verticesStart defines vertex index start
  35818. * @param verticesCount defines vertices count
  35819. * @param indexStart defines index start
  35820. * @param indexCount defines indices count
  35821. * @param mesh defines the parent mesh
  35822. * @param renderingMesh defines an optional rendering mesh
  35823. * @param createBoundingBox defines if bounding box should be created for this submesh
  35824. */
  35825. function SubMesh(
  35826. /** the material index to use */
  35827. materialIndex,
  35828. /** vertex index start */
  35829. verticesStart,
  35830. /** vertices count */
  35831. verticesCount,
  35832. /** index start */
  35833. indexStart,
  35834. /** indices count */
  35835. indexCount, mesh, renderingMesh, createBoundingBox) {
  35836. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35837. var _this = _super.call(this) || this;
  35838. _this.materialIndex = materialIndex;
  35839. _this.verticesStart = verticesStart;
  35840. _this.verticesCount = verticesCount;
  35841. _this.indexStart = indexStart;
  35842. _this.indexCount = indexCount;
  35843. /** @hidden */
  35844. _this._renderId = 0;
  35845. _this._mesh = mesh;
  35846. _this._renderingMesh = renderingMesh || mesh;
  35847. mesh.subMeshes.push(_this);
  35848. _this._trianglePlanes = [];
  35849. _this._id = mesh.subMeshes.length - 1;
  35850. if (createBoundingBox) {
  35851. _this.refreshBoundingInfo();
  35852. mesh.computeWorldMatrix(true);
  35853. }
  35854. return _this;
  35855. }
  35856. /**
  35857. * Add a new submesh to a mesh
  35858. * @param materialIndex defines the material index to use
  35859. * @param verticesStart defines vertex index start
  35860. * @param verticesCount defines vertices count
  35861. * @param indexStart defines index start
  35862. * @param indexCount defines indices count
  35863. * @param mesh defines the parent mesh
  35864. * @param renderingMesh defines an optional rendering mesh
  35865. * @param createBoundingBox defines if bounding box should be created for this submesh
  35866. * @returns the new submesh
  35867. */
  35868. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35869. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35870. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35871. };
  35872. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35873. /**
  35874. * Returns true if this submesh covers the entire parent mesh
  35875. * @ignorenaming
  35876. */
  35877. get: function () {
  35878. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35879. },
  35880. enumerable: true,
  35881. configurable: true
  35882. });
  35883. /**
  35884. * Returns the submesh BoudingInfo object
  35885. * @returns current bounding info (or mesh's one if the submesh is global)
  35886. */
  35887. SubMesh.prototype.getBoundingInfo = function () {
  35888. if (this.IsGlobal) {
  35889. return this._mesh.getBoundingInfo();
  35890. }
  35891. return this._boundingInfo;
  35892. };
  35893. /**
  35894. * Sets the submesh BoundingInfo
  35895. * @param boundingInfo defines the new bounding info to use
  35896. * @returns the SubMesh
  35897. */
  35898. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35899. this._boundingInfo = boundingInfo;
  35900. return this;
  35901. };
  35902. /**
  35903. * Returns the mesh of the current submesh
  35904. * @return the parent mesh
  35905. */
  35906. SubMesh.prototype.getMesh = function () {
  35907. return this._mesh;
  35908. };
  35909. /**
  35910. * Returns the rendering mesh of the submesh
  35911. * @returns the rendering mesh (could be different from parent mesh)
  35912. */
  35913. SubMesh.prototype.getRenderingMesh = function () {
  35914. return this._renderingMesh;
  35915. };
  35916. /**
  35917. * Returns the submesh material
  35918. * @returns null or the current material
  35919. */
  35920. SubMesh.prototype.getMaterial = function () {
  35921. var rootMaterial = this._renderingMesh.material;
  35922. if (rootMaterial === null || rootMaterial === undefined) {
  35923. return this._mesh.getScene().defaultMaterial;
  35924. }
  35925. else if (rootMaterial.getSubMaterial) {
  35926. var multiMaterial = rootMaterial;
  35927. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35928. if (this._currentMaterial !== effectiveMaterial) {
  35929. this._currentMaterial = effectiveMaterial;
  35930. this._materialDefines = null;
  35931. }
  35932. return effectiveMaterial;
  35933. }
  35934. return rootMaterial;
  35935. };
  35936. // Methods
  35937. /**
  35938. * Sets a new updated BoundingInfo object to the submesh
  35939. * @returns the SubMesh
  35940. */
  35941. SubMesh.prototype.refreshBoundingInfo = function () {
  35942. this._lastColliderWorldVertices = null;
  35943. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35944. return this;
  35945. }
  35946. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35947. if (!data) {
  35948. this._boundingInfo = this._mesh.getBoundingInfo();
  35949. return this;
  35950. }
  35951. var indices = this._renderingMesh.getIndices();
  35952. var extend;
  35953. //is this the only submesh?
  35954. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35955. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35956. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35957. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35958. }
  35959. else {
  35960. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35961. }
  35962. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35963. return this;
  35964. };
  35965. /** @hidden */
  35966. SubMesh.prototype._checkCollision = function (collider) {
  35967. var boundingInfo = this.getBoundingInfo();
  35968. return boundingInfo._checkCollision(collider);
  35969. };
  35970. /**
  35971. * Updates the submesh BoundingInfo
  35972. * @param world defines the world matrix to use to update the bounding info
  35973. * @returns the submesh
  35974. */
  35975. SubMesh.prototype.updateBoundingInfo = function (world) {
  35976. var boundingInfo = this.getBoundingInfo();
  35977. if (!boundingInfo) {
  35978. this.refreshBoundingInfo();
  35979. boundingInfo = this.getBoundingInfo();
  35980. }
  35981. boundingInfo.update(world);
  35982. return this;
  35983. };
  35984. /**
  35985. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35986. * @param frustumPlanes defines the frustum planes
  35987. * @returns true if the submesh is intersecting with the frustum
  35988. */
  35989. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35990. var boundingInfo = this.getBoundingInfo();
  35991. if (!boundingInfo) {
  35992. return false;
  35993. }
  35994. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35995. };
  35996. /**
  35997. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35998. * @param frustumPlanes defines the frustum planes
  35999. * @returns true if the submesh is inside the frustum
  36000. */
  36001. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  36002. var boundingInfo = this.getBoundingInfo();
  36003. if (!boundingInfo) {
  36004. return false;
  36005. }
  36006. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  36007. };
  36008. /**
  36009. * Renders the submesh
  36010. * @param enableAlphaMode defines if alpha needs to be used
  36011. * @returns the submesh
  36012. */
  36013. SubMesh.prototype.render = function (enableAlphaMode) {
  36014. this._renderingMesh.render(this, enableAlphaMode);
  36015. return this;
  36016. };
  36017. /**
  36018. * @hidden
  36019. */
  36020. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  36021. if (!this._linesIndexBuffer) {
  36022. var linesIndices = [];
  36023. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36024. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  36025. }
  36026. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  36027. this._linesIndexCount = linesIndices.length;
  36028. }
  36029. return this._linesIndexBuffer;
  36030. };
  36031. /**
  36032. * Checks if the submesh intersects with a ray
  36033. * @param ray defines the ray to test
  36034. * @returns true is the passed ray intersects the submesh bounding box
  36035. */
  36036. SubMesh.prototype.canIntersects = function (ray) {
  36037. var boundingInfo = this.getBoundingInfo();
  36038. if (!boundingInfo) {
  36039. return false;
  36040. }
  36041. return ray.intersectsBox(boundingInfo.boundingBox);
  36042. };
  36043. /**
  36044. * Intersects current submesh with a ray
  36045. * @param ray defines the ray to test
  36046. * @param positions defines mesh's positions array
  36047. * @param indices defines mesh's indices array
  36048. * @param fastCheck defines if only bounding info should be used
  36049. * @returns intersection info or null if no intersection
  36050. */
  36051. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  36052. var material = this.getMaterial();
  36053. if (!material) {
  36054. return null;
  36055. }
  36056. switch (material.fillMode) {
  36057. case BABYLON.Material.PointListDrawMode:
  36058. case BABYLON.Material.LineListDrawMode:
  36059. case BABYLON.Material.LineLoopDrawMode:
  36060. case BABYLON.Material.LineStripDrawMode:
  36061. case BABYLON.Material.TriangleFanDrawMode:
  36062. case BABYLON.Material.TriangleStripDrawMode:
  36063. return null;
  36064. }
  36065. // LineMesh first as it's also a Mesh...
  36066. if (BABYLON.LinesMesh) {
  36067. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  36068. if (mesh instanceof BABYLON.LinesMesh) {
  36069. var linesMesh = mesh;
  36070. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  36071. }
  36072. }
  36073. return this._intersectTriangles(ray, positions, indices, fastCheck);
  36074. };
  36075. /** @hidden */
  36076. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  36077. var intersectInfo = null;
  36078. // Line test
  36079. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  36080. var p0 = positions[indices[index]];
  36081. var p1 = positions[indices[index + 1]];
  36082. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  36083. if (length < 0) {
  36084. continue;
  36085. }
  36086. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  36087. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  36088. if (fastCheck) {
  36089. break;
  36090. }
  36091. }
  36092. }
  36093. return intersectInfo;
  36094. };
  36095. /** @hidden */
  36096. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  36097. var intersectInfo = null;
  36098. // Triangles test
  36099. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36100. var p0 = positions[indices[index]];
  36101. var p1 = positions[indices[index + 1]];
  36102. var p2 = positions[indices[index + 2]];
  36103. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  36104. if (currentIntersectInfo) {
  36105. if (currentIntersectInfo.distance < 0) {
  36106. continue;
  36107. }
  36108. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  36109. intersectInfo = currentIntersectInfo;
  36110. intersectInfo.faceId = index / 3;
  36111. if (fastCheck) {
  36112. break;
  36113. }
  36114. }
  36115. }
  36116. }
  36117. return intersectInfo;
  36118. };
  36119. /** @hidden */
  36120. SubMesh.prototype._rebuild = function () {
  36121. if (this._linesIndexBuffer) {
  36122. this._linesIndexBuffer = null;
  36123. }
  36124. };
  36125. // Clone
  36126. /**
  36127. * Creates a new submesh from the passed mesh
  36128. * @param newMesh defines the new hosting mesh
  36129. * @param newRenderingMesh defines an optional rendering mesh
  36130. * @returns the new submesh
  36131. */
  36132. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  36133. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  36134. if (!this.IsGlobal) {
  36135. var boundingInfo = this.getBoundingInfo();
  36136. if (!boundingInfo) {
  36137. return result;
  36138. }
  36139. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  36140. }
  36141. return result;
  36142. };
  36143. // Dispose
  36144. /**
  36145. * Release associated resources
  36146. */
  36147. SubMesh.prototype.dispose = function () {
  36148. if (this._linesIndexBuffer) {
  36149. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  36150. this._linesIndexBuffer = null;
  36151. }
  36152. // Remove from mesh
  36153. var index = this._mesh.subMeshes.indexOf(this);
  36154. this._mesh.subMeshes.splice(index, 1);
  36155. };
  36156. // Statics
  36157. /**
  36158. * Creates a new submesh from indices data
  36159. * @param materialIndex the index of the main mesh material
  36160. * @param startIndex the index where to start the copy in the mesh indices array
  36161. * @param indexCount the number of indices to copy then from the startIndex
  36162. * @param mesh the main mesh to create the submesh from
  36163. * @param renderingMesh the optional rendering mesh
  36164. * @returns a new submesh
  36165. */
  36166. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  36167. var minVertexIndex = Number.MAX_VALUE;
  36168. var maxVertexIndex = -Number.MAX_VALUE;
  36169. renderingMesh = (renderingMesh || mesh);
  36170. var indices = renderingMesh.getIndices();
  36171. for (var index = startIndex; index < startIndex + indexCount; index++) {
  36172. var vertexIndex = indices[index];
  36173. if (vertexIndex < minVertexIndex) {
  36174. minVertexIndex = vertexIndex;
  36175. }
  36176. if (vertexIndex > maxVertexIndex) {
  36177. maxVertexIndex = vertexIndex;
  36178. }
  36179. }
  36180. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  36181. };
  36182. return SubMesh;
  36183. }(BaseSubMesh));
  36184. BABYLON.SubMesh = SubMesh;
  36185. })(BABYLON || (BABYLON = {}));
  36186. //# sourceMappingURL=babylon.subMesh.js.map
  36187. var __assign = (this && this.__assign) || function () {
  36188. __assign = Object.assign || function(t) {
  36189. for (var s, i = 1, n = arguments.length; i < n; i++) {
  36190. s = arguments[i];
  36191. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  36192. t[p] = s[p];
  36193. }
  36194. return t;
  36195. };
  36196. return __assign.apply(this, arguments);
  36197. };
  36198. var BABYLON;
  36199. (function (BABYLON) {
  36200. /**
  36201. * Manages the defines for the Material
  36202. */
  36203. var MaterialDefines = /** @class */ (function () {
  36204. function MaterialDefines() {
  36205. this._isDirty = true;
  36206. /** @hidden */
  36207. this._areLightsDirty = true;
  36208. /** @hidden */
  36209. this._areAttributesDirty = true;
  36210. /** @hidden */
  36211. this._areTexturesDirty = true;
  36212. /** @hidden */
  36213. this._areFresnelDirty = true;
  36214. /** @hidden */
  36215. this._areMiscDirty = true;
  36216. /** @hidden */
  36217. this._areImageProcessingDirty = true;
  36218. /** @hidden */
  36219. this._normals = false;
  36220. /** @hidden */
  36221. this._uvs = false;
  36222. /** @hidden */
  36223. this._needNormals = false;
  36224. /** @hidden */
  36225. this._needUVs = false;
  36226. }
  36227. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  36228. /**
  36229. * Specifies if the material needs to be re-calculated
  36230. */
  36231. get: function () {
  36232. return this._isDirty;
  36233. },
  36234. enumerable: true,
  36235. configurable: true
  36236. });
  36237. /**
  36238. * Marks the material to indicate that it has been re-calculated
  36239. */
  36240. MaterialDefines.prototype.markAsProcessed = function () {
  36241. this._isDirty = false;
  36242. this._areAttributesDirty = false;
  36243. this._areTexturesDirty = false;
  36244. this._areFresnelDirty = false;
  36245. this._areLightsDirty = false;
  36246. this._areMiscDirty = false;
  36247. this._areImageProcessingDirty = false;
  36248. };
  36249. /**
  36250. * Marks the material to indicate that it needs to be re-calculated
  36251. */
  36252. MaterialDefines.prototype.markAsUnprocessed = function () {
  36253. this._isDirty = true;
  36254. };
  36255. /**
  36256. * Marks the material to indicate all of its defines need to be re-calculated
  36257. */
  36258. MaterialDefines.prototype.markAllAsDirty = function () {
  36259. this._areTexturesDirty = true;
  36260. this._areAttributesDirty = true;
  36261. this._areLightsDirty = true;
  36262. this._areFresnelDirty = true;
  36263. this._areMiscDirty = true;
  36264. this._areImageProcessingDirty = true;
  36265. this._isDirty = true;
  36266. };
  36267. /**
  36268. * Marks the material to indicate that image processing needs to be re-calculated
  36269. */
  36270. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  36271. this._areImageProcessingDirty = true;
  36272. this._isDirty = true;
  36273. };
  36274. /**
  36275. * Marks the material to indicate the lights need to be re-calculated
  36276. */
  36277. MaterialDefines.prototype.markAsLightDirty = function () {
  36278. this._areLightsDirty = true;
  36279. this._isDirty = true;
  36280. };
  36281. /**
  36282. * Marks the attribute state as changed
  36283. */
  36284. MaterialDefines.prototype.markAsAttributesDirty = function () {
  36285. this._areAttributesDirty = true;
  36286. this._isDirty = true;
  36287. };
  36288. /**
  36289. * Marks the texture state as changed
  36290. */
  36291. MaterialDefines.prototype.markAsTexturesDirty = function () {
  36292. this._areTexturesDirty = true;
  36293. this._isDirty = true;
  36294. };
  36295. /**
  36296. * Marks the fresnel state as changed
  36297. */
  36298. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36299. this._areFresnelDirty = true;
  36300. this._isDirty = true;
  36301. };
  36302. /**
  36303. * Marks the misc state as changed
  36304. */
  36305. MaterialDefines.prototype.markAsMiscDirty = function () {
  36306. this._areMiscDirty = true;
  36307. this._isDirty = true;
  36308. };
  36309. /**
  36310. * Rebuilds the material defines
  36311. */
  36312. MaterialDefines.prototype.rebuild = function () {
  36313. if (this._keys) {
  36314. delete this._keys;
  36315. }
  36316. this._keys = [];
  36317. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36318. var key = _a[_i];
  36319. if (key[0] === "_") {
  36320. continue;
  36321. }
  36322. this._keys.push(key);
  36323. }
  36324. };
  36325. /**
  36326. * Specifies if two material defines are equal
  36327. * @param other - A material define instance to compare to
  36328. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36329. */
  36330. MaterialDefines.prototype.isEqual = function (other) {
  36331. if (this._keys.length !== other._keys.length) {
  36332. return false;
  36333. }
  36334. for (var index = 0; index < this._keys.length; index++) {
  36335. var prop = this._keys[index];
  36336. if (this[prop] !== other[prop]) {
  36337. return false;
  36338. }
  36339. }
  36340. return true;
  36341. };
  36342. /**
  36343. * Clones this instance's defines to another instance
  36344. * @param other - material defines to clone values to
  36345. */
  36346. MaterialDefines.prototype.cloneTo = function (other) {
  36347. if (this._keys.length !== other._keys.length) {
  36348. other._keys = this._keys.slice(0);
  36349. }
  36350. for (var index = 0; index < this._keys.length; index++) {
  36351. var prop = this._keys[index];
  36352. other[prop] = this[prop];
  36353. }
  36354. };
  36355. /**
  36356. * Resets the material define values
  36357. */
  36358. MaterialDefines.prototype.reset = function () {
  36359. for (var index = 0; index < this._keys.length; index++) {
  36360. var prop = this._keys[index];
  36361. var type = typeof this[prop];
  36362. switch (type) {
  36363. case "number":
  36364. this[prop] = 0;
  36365. break;
  36366. case "string":
  36367. this[prop] = "";
  36368. break;
  36369. default:
  36370. this[prop] = false;
  36371. break;
  36372. }
  36373. }
  36374. };
  36375. /**
  36376. * Converts the material define values to a string
  36377. * @returns - String of material define information
  36378. */
  36379. MaterialDefines.prototype.toString = function () {
  36380. var result = "";
  36381. for (var index = 0; index < this._keys.length; index++) {
  36382. var prop = this._keys[index];
  36383. var value = this[prop];
  36384. var type = typeof value;
  36385. switch (type) {
  36386. case "number":
  36387. case "string":
  36388. result += "#define " + prop + " " + value + "\n";
  36389. break;
  36390. default:
  36391. if (value) {
  36392. result += "#define " + prop + "\n";
  36393. }
  36394. break;
  36395. }
  36396. }
  36397. return result;
  36398. };
  36399. return MaterialDefines;
  36400. }());
  36401. BABYLON.MaterialDefines = MaterialDefines;
  36402. /**
  36403. * Base class for the main features of a material in Babylon.js
  36404. */
  36405. var Material = /** @class */ (function () {
  36406. /**
  36407. * Creates a material instance
  36408. * @param name defines the name of the material
  36409. * @param scene defines the scene to reference
  36410. * @param doNotAdd specifies if the material should be added to the scene
  36411. */
  36412. function Material(name, scene, doNotAdd) {
  36413. /**
  36414. * Specifies if the ready state should be checked on each call
  36415. */
  36416. this.checkReadyOnEveryCall = false;
  36417. /**
  36418. * Specifies if the ready state should be checked once
  36419. */
  36420. this.checkReadyOnlyOnce = false;
  36421. /**
  36422. * The state of the material
  36423. */
  36424. this.state = "";
  36425. /**
  36426. * The alpha value of the material
  36427. */
  36428. this._alpha = 1.0;
  36429. /**
  36430. * Specifies if back face culling is enabled
  36431. */
  36432. this._backFaceCulling = true;
  36433. /**
  36434. * Specifies if the material should be serialized
  36435. */
  36436. this.doNotSerialize = false;
  36437. /**
  36438. * @hidden
  36439. */
  36440. this._storeEffectOnSubMeshes = false;
  36441. /**
  36442. * An event triggered when the material is disposed
  36443. */
  36444. this.onDisposeObservable = new BABYLON.Observable();
  36445. /**
  36446. * Stores the value of the alpha mode
  36447. */
  36448. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36449. /**
  36450. * Stores the state of the need depth pre-pass value
  36451. */
  36452. this._needDepthPrePass = false;
  36453. /**
  36454. * Specifies if depth writing should be disabled
  36455. */
  36456. this.disableDepthWrite = false;
  36457. /**
  36458. * Specifies if depth writing should be forced
  36459. */
  36460. this.forceDepthWrite = false;
  36461. /**
  36462. * Specifies if there should be a separate pass for culling
  36463. */
  36464. this.separateCullingPass = false;
  36465. /**
  36466. * Stores the state specifing if fog should be enabled
  36467. */
  36468. this._fogEnabled = true;
  36469. /**
  36470. * Stores the size of points
  36471. */
  36472. this.pointSize = 1.0;
  36473. /**
  36474. * Stores the z offset value
  36475. */
  36476. this.zOffset = 0;
  36477. /**
  36478. * @hidden
  36479. * Specifies if the material was previously ready
  36480. */
  36481. this._wasPreviouslyReady = false;
  36482. /**
  36483. * Stores the fill mode state
  36484. */
  36485. this._fillMode = Material.TriangleFillMode;
  36486. /** @hidden */
  36487. this._indexInSceneMaterialArray = -1;
  36488. this.name = name;
  36489. this.id = name || BABYLON.Tools.RandomId();
  36490. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36491. this.uniqueId = this._scene.getUniqueId();
  36492. if (this._scene.useRightHandedSystem) {
  36493. this.sideOrientation = Material.ClockWiseSideOrientation;
  36494. }
  36495. else {
  36496. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36497. }
  36498. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36499. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36500. if (!doNotAdd) {
  36501. this._scene.addMaterial(this);
  36502. }
  36503. if (this._scene.useMaterialMeshMap) {
  36504. this.meshMap = {};
  36505. }
  36506. }
  36507. Object.defineProperty(Material, "TriangleFillMode", {
  36508. /**
  36509. * Returns the triangle fill mode
  36510. */
  36511. get: function () {
  36512. return Material._TriangleFillMode;
  36513. },
  36514. enumerable: true,
  36515. configurable: true
  36516. });
  36517. Object.defineProperty(Material, "WireFrameFillMode", {
  36518. /**
  36519. * Returns the wireframe mode
  36520. */
  36521. get: function () {
  36522. return Material._WireFrameFillMode;
  36523. },
  36524. enumerable: true,
  36525. configurable: true
  36526. });
  36527. Object.defineProperty(Material, "PointFillMode", {
  36528. /**
  36529. * Returns the point fill mode
  36530. */
  36531. get: function () {
  36532. return Material._PointFillMode;
  36533. },
  36534. enumerable: true,
  36535. configurable: true
  36536. });
  36537. Object.defineProperty(Material, "PointListDrawMode", {
  36538. /**
  36539. * Returns the point list draw mode
  36540. */
  36541. get: function () {
  36542. return Material._PointListDrawMode;
  36543. },
  36544. enumerable: true,
  36545. configurable: true
  36546. });
  36547. Object.defineProperty(Material, "LineListDrawMode", {
  36548. /**
  36549. * Returns the line list draw mode
  36550. */
  36551. get: function () {
  36552. return Material._LineListDrawMode;
  36553. },
  36554. enumerable: true,
  36555. configurable: true
  36556. });
  36557. Object.defineProperty(Material, "LineLoopDrawMode", {
  36558. /**
  36559. * Returns the line loop draw mode
  36560. */
  36561. get: function () {
  36562. return Material._LineLoopDrawMode;
  36563. },
  36564. enumerable: true,
  36565. configurable: true
  36566. });
  36567. Object.defineProperty(Material, "LineStripDrawMode", {
  36568. /**
  36569. * Returns the line strip draw mode
  36570. */
  36571. get: function () {
  36572. return Material._LineStripDrawMode;
  36573. },
  36574. enumerable: true,
  36575. configurable: true
  36576. });
  36577. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36578. /**
  36579. * Returns the triangle strip draw mode
  36580. */
  36581. get: function () {
  36582. return Material._TriangleStripDrawMode;
  36583. },
  36584. enumerable: true,
  36585. configurable: true
  36586. });
  36587. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36588. /**
  36589. * Returns the triangle fan draw mode
  36590. */
  36591. get: function () {
  36592. return Material._TriangleFanDrawMode;
  36593. },
  36594. enumerable: true,
  36595. configurable: true
  36596. });
  36597. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36598. /**
  36599. * Returns the clock-wise side orientation
  36600. */
  36601. get: function () {
  36602. return Material._ClockWiseSideOrientation;
  36603. },
  36604. enumerable: true,
  36605. configurable: true
  36606. });
  36607. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36608. /**
  36609. * Returns the counter clock-wise side orientation
  36610. */
  36611. get: function () {
  36612. return Material._CounterClockWiseSideOrientation;
  36613. },
  36614. enumerable: true,
  36615. configurable: true
  36616. });
  36617. Object.defineProperty(Material.prototype, "alpha", {
  36618. /**
  36619. * Gets the alpha value of the material
  36620. */
  36621. get: function () {
  36622. return this._alpha;
  36623. },
  36624. /**
  36625. * Sets the alpha value of the material
  36626. */
  36627. set: function (value) {
  36628. if (this._alpha === value) {
  36629. return;
  36630. }
  36631. this._alpha = value;
  36632. this.markAsDirty(Material.MiscDirtyFlag);
  36633. },
  36634. enumerable: true,
  36635. configurable: true
  36636. });
  36637. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36638. /**
  36639. * Gets the back-face culling state
  36640. */
  36641. get: function () {
  36642. return this._backFaceCulling;
  36643. },
  36644. /**
  36645. * Sets the back-face culling state
  36646. */
  36647. set: function (value) {
  36648. if (this._backFaceCulling === value) {
  36649. return;
  36650. }
  36651. this._backFaceCulling = value;
  36652. this.markAsDirty(Material.TextureDirtyFlag);
  36653. },
  36654. enumerable: true,
  36655. configurable: true
  36656. });
  36657. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36658. /**
  36659. * Gets a boolean indicating that current material needs to register RTT
  36660. */
  36661. get: function () {
  36662. return false;
  36663. },
  36664. enumerable: true,
  36665. configurable: true
  36666. });
  36667. Object.defineProperty(Material.prototype, "onDispose", {
  36668. /**
  36669. * Called during a dispose event
  36670. */
  36671. set: function (callback) {
  36672. if (this._onDisposeObserver) {
  36673. this.onDisposeObservable.remove(this._onDisposeObserver);
  36674. }
  36675. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36676. },
  36677. enumerable: true,
  36678. configurable: true
  36679. });
  36680. Object.defineProperty(Material.prototype, "onBindObservable", {
  36681. /**
  36682. * An event triggered when the material is bound
  36683. */
  36684. get: function () {
  36685. if (!this._onBindObservable) {
  36686. this._onBindObservable = new BABYLON.Observable();
  36687. }
  36688. return this._onBindObservable;
  36689. },
  36690. enumerable: true,
  36691. configurable: true
  36692. });
  36693. Object.defineProperty(Material.prototype, "onBind", {
  36694. /**
  36695. * Called during a bind event
  36696. */
  36697. set: function (callback) {
  36698. if (this._onBindObserver) {
  36699. this.onBindObservable.remove(this._onBindObserver);
  36700. }
  36701. this._onBindObserver = this.onBindObservable.add(callback);
  36702. },
  36703. enumerable: true,
  36704. configurable: true
  36705. });
  36706. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36707. /**
  36708. * An event triggered when the material is unbound
  36709. */
  36710. get: function () {
  36711. if (!this._onUnBindObservable) {
  36712. this._onUnBindObservable = new BABYLON.Observable();
  36713. }
  36714. return this._onUnBindObservable;
  36715. },
  36716. enumerable: true,
  36717. configurable: true
  36718. });
  36719. Object.defineProperty(Material.prototype, "alphaMode", {
  36720. /**
  36721. * Gets the value of the alpha mode
  36722. */
  36723. get: function () {
  36724. return this._alphaMode;
  36725. },
  36726. /**
  36727. * Sets the value of the alpha mode.
  36728. *
  36729. * | Value | Type | Description |
  36730. * | --- | --- | --- |
  36731. * | 0 | ALPHA_DISABLE | |
  36732. * | 1 | ALPHA_ADD | |
  36733. * | 2 | ALPHA_COMBINE | |
  36734. * | 3 | ALPHA_SUBTRACT | |
  36735. * | 4 | ALPHA_MULTIPLY | |
  36736. * | 5 | ALPHA_MAXIMIZED | |
  36737. * | 6 | ALPHA_ONEONE | |
  36738. * | 7 | ALPHA_PREMULTIPLIED | |
  36739. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36740. * | 9 | ALPHA_INTERPOLATE | |
  36741. * | 10 | ALPHA_SCREENMODE | |
  36742. *
  36743. */
  36744. set: function (value) {
  36745. if (this._alphaMode === value) {
  36746. return;
  36747. }
  36748. this._alphaMode = value;
  36749. this.markAsDirty(Material.TextureDirtyFlag);
  36750. },
  36751. enumerable: true,
  36752. configurable: true
  36753. });
  36754. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36755. /**
  36756. * Gets the depth pre-pass value
  36757. */
  36758. get: function () {
  36759. return this._needDepthPrePass;
  36760. },
  36761. /**
  36762. * Sets the need depth pre-pass value
  36763. */
  36764. set: function (value) {
  36765. if (this._needDepthPrePass === value) {
  36766. return;
  36767. }
  36768. this._needDepthPrePass = value;
  36769. if (this._needDepthPrePass) {
  36770. this.checkReadyOnEveryCall = true;
  36771. }
  36772. },
  36773. enumerable: true,
  36774. configurable: true
  36775. });
  36776. Object.defineProperty(Material.prototype, "fogEnabled", {
  36777. /**
  36778. * Gets the value of the fog enabled state
  36779. */
  36780. get: function () {
  36781. return this._fogEnabled;
  36782. },
  36783. /**
  36784. * Sets the state for enabling fog
  36785. */
  36786. set: function (value) {
  36787. if (this._fogEnabled === value) {
  36788. return;
  36789. }
  36790. this._fogEnabled = value;
  36791. this.markAsDirty(Material.MiscDirtyFlag);
  36792. },
  36793. enumerable: true,
  36794. configurable: true
  36795. });
  36796. Object.defineProperty(Material.prototype, "wireframe", {
  36797. /**
  36798. * Gets a value specifying if wireframe mode is enabled
  36799. */
  36800. get: function () {
  36801. switch (this._fillMode) {
  36802. case Material.WireFrameFillMode:
  36803. case Material.LineListDrawMode:
  36804. case Material.LineLoopDrawMode:
  36805. case Material.LineStripDrawMode:
  36806. return true;
  36807. }
  36808. return this._scene.forceWireframe;
  36809. },
  36810. /**
  36811. * Sets the state of wireframe mode
  36812. */
  36813. set: function (value) {
  36814. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36815. },
  36816. enumerable: true,
  36817. configurable: true
  36818. });
  36819. Object.defineProperty(Material.prototype, "pointsCloud", {
  36820. /**
  36821. * Gets the value specifying if point clouds are enabled
  36822. */
  36823. get: function () {
  36824. switch (this._fillMode) {
  36825. case Material.PointFillMode:
  36826. case Material.PointListDrawMode:
  36827. return true;
  36828. }
  36829. return this._scene.forcePointsCloud;
  36830. },
  36831. /**
  36832. * Sets the state of point cloud mode
  36833. */
  36834. set: function (value) {
  36835. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36836. },
  36837. enumerable: true,
  36838. configurable: true
  36839. });
  36840. Object.defineProperty(Material.prototype, "fillMode", {
  36841. /**
  36842. * Gets the material fill mode
  36843. */
  36844. get: function () {
  36845. return this._fillMode;
  36846. },
  36847. /**
  36848. * Sets the material fill mode
  36849. */
  36850. set: function (value) {
  36851. if (this._fillMode === value) {
  36852. return;
  36853. }
  36854. this._fillMode = value;
  36855. this.markAsDirty(Material.MiscDirtyFlag);
  36856. },
  36857. enumerable: true,
  36858. configurable: true
  36859. });
  36860. /**
  36861. * Returns a string representation of the current material
  36862. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36863. * @returns a string with material information
  36864. */
  36865. Material.prototype.toString = function (fullDetails) {
  36866. var ret = "Name: " + this.name;
  36867. if (fullDetails) {
  36868. }
  36869. return ret;
  36870. };
  36871. /**
  36872. * Gets the class name of the material
  36873. * @returns a string with the class name of the material
  36874. */
  36875. Material.prototype.getClassName = function () {
  36876. return "Material";
  36877. };
  36878. Object.defineProperty(Material.prototype, "isFrozen", {
  36879. /**
  36880. * Specifies if updates for the material been locked
  36881. */
  36882. get: function () {
  36883. return this.checkReadyOnlyOnce;
  36884. },
  36885. enumerable: true,
  36886. configurable: true
  36887. });
  36888. /**
  36889. * Locks updates for the material
  36890. */
  36891. Material.prototype.freeze = function () {
  36892. this.checkReadyOnlyOnce = true;
  36893. };
  36894. /**
  36895. * Unlocks updates for the material
  36896. */
  36897. Material.prototype.unfreeze = function () {
  36898. this.checkReadyOnlyOnce = false;
  36899. };
  36900. /**
  36901. * Specifies if the material is ready to be used
  36902. * @param mesh defines the mesh to check
  36903. * @param useInstances specifies if instances should be used
  36904. * @returns a boolean indicating if the material is ready to be used
  36905. */
  36906. Material.prototype.isReady = function (mesh, useInstances) {
  36907. return true;
  36908. };
  36909. /**
  36910. * Specifies that the submesh is ready to be used
  36911. * @param mesh defines the mesh to check
  36912. * @param subMesh defines which submesh to check
  36913. * @param useInstances specifies that instances should be used
  36914. * @returns a boolean indicating that the submesh is ready or not
  36915. */
  36916. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36917. return false;
  36918. };
  36919. /**
  36920. * Returns the material effect
  36921. * @returns the effect associated with the material
  36922. */
  36923. Material.prototype.getEffect = function () {
  36924. return this._effect;
  36925. };
  36926. /**
  36927. * Returns the current scene
  36928. * @returns a Scene
  36929. */
  36930. Material.prototype.getScene = function () {
  36931. return this._scene;
  36932. };
  36933. /**
  36934. * Specifies if the material will require alpha blending
  36935. * @returns a boolean specifying if alpha blending is needed
  36936. */
  36937. Material.prototype.needAlphaBlending = function () {
  36938. return (this.alpha < 1.0);
  36939. };
  36940. /**
  36941. * Specifies if the mesh will require alpha blending
  36942. * @param mesh defines the mesh to check
  36943. * @returns a boolean specifying if alpha blending is needed for the mesh
  36944. */
  36945. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36946. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36947. };
  36948. /**
  36949. * Specifies if this material should be rendered in alpha test mode
  36950. * @returns a boolean specifying if an alpha test is needed.
  36951. */
  36952. Material.prototype.needAlphaTesting = function () {
  36953. return false;
  36954. };
  36955. /**
  36956. * Gets the texture used for the alpha test
  36957. * @returns the texture to use for alpha testing
  36958. */
  36959. Material.prototype.getAlphaTestTexture = function () {
  36960. return null;
  36961. };
  36962. /**
  36963. * Marks the material to indicate that it needs to be re-calculated
  36964. */
  36965. Material.prototype.markDirty = function () {
  36966. this._wasPreviouslyReady = false;
  36967. };
  36968. /** @hidden */
  36969. Material.prototype._preBind = function (effect, overrideOrientation) {
  36970. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36971. var engine = this._scene.getEngine();
  36972. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36973. var reverse = orientation === Material.ClockWiseSideOrientation;
  36974. engine.enableEffect(effect ? effect : this._effect);
  36975. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36976. return reverse;
  36977. };
  36978. /**
  36979. * Binds the material to the mesh
  36980. * @param world defines the world transformation matrix
  36981. * @param mesh defines the mesh to bind the material to
  36982. */
  36983. Material.prototype.bind = function (world, mesh) {
  36984. };
  36985. /**
  36986. * Binds the submesh to the material
  36987. * @param world defines the world transformation matrix
  36988. * @param mesh defines the mesh containing the submesh
  36989. * @param subMesh defines the submesh to bind the material to
  36990. */
  36991. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36992. };
  36993. /**
  36994. * Binds the world matrix to the material
  36995. * @param world defines the world transformation matrix
  36996. */
  36997. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36998. };
  36999. /**
  37000. * Binds the scene's uniform buffer to the effect.
  37001. * @param effect defines the effect to bind to the scene uniform buffer
  37002. * @param sceneUbo defines the uniform buffer storing scene data
  37003. */
  37004. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  37005. sceneUbo.bindToEffect(effect, "Scene");
  37006. };
  37007. /**
  37008. * Binds the view matrix to the effect
  37009. * @param effect defines the effect to bind the view matrix to
  37010. */
  37011. Material.prototype.bindView = function (effect) {
  37012. if (!this._useUBO) {
  37013. effect.setMatrix("view", this.getScene().getViewMatrix());
  37014. }
  37015. else {
  37016. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37017. }
  37018. };
  37019. /**
  37020. * Binds the view projection matrix to the effect
  37021. * @param effect defines the effect to bind the view projection matrix to
  37022. */
  37023. Material.prototype.bindViewProjection = function (effect) {
  37024. if (!this._useUBO) {
  37025. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  37026. }
  37027. else {
  37028. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37029. }
  37030. };
  37031. /**
  37032. * Specifies if material alpha testing should be turned on for the mesh
  37033. * @param mesh defines the mesh to check
  37034. */
  37035. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  37036. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  37037. };
  37038. /**
  37039. * Processes to execute after binding the material to a mesh
  37040. * @param mesh defines the rendered mesh
  37041. */
  37042. Material.prototype._afterBind = function (mesh) {
  37043. this._scene._cachedMaterial = this;
  37044. if (mesh) {
  37045. this._scene._cachedVisibility = mesh.visibility;
  37046. }
  37047. else {
  37048. this._scene._cachedVisibility = 1;
  37049. }
  37050. if (this._onBindObservable && mesh) {
  37051. this._onBindObservable.notifyObservers(mesh);
  37052. }
  37053. if (this.disableDepthWrite) {
  37054. var engine = this._scene.getEngine();
  37055. this._cachedDepthWriteState = engine.getDepthWrite();
  37056. engine.setDepthWrite(false);
  37057. }
  37058. };
  37059. /**
  37060. * Unbinds the material from the mesh
  37061. */
  37062. Material.prototype.unbind = function () {
  37063. if (this._onUnBindObservable) {
  37064. this._onUnBindObservable.notifyObservers(this);
  37065. }
  37066. if (this.disableDepthWrite) {
  37067. var engine = this._scene.getEngine();
  37068. engine.setDepthWrite(this._cachedDepthWriteState);
  37069. }
  37070. };
  37071. /**
  37072. * Gets the active textures from the material
  37073. * @returns an array of textures
  37074. */
  37075. Material.prototype.getActiveTextures = function () {
  37076. return [];
  37077. };
  37078. /**
  37079. * Specifies if the material uses a texture
  37080. * @param texture defines the texture to check against the material
  37081. * @returns a boolean specifying if the material uses the texture
  37082. */
  37083. Material.prototype.hasTexture = function (texture) {
  37084. return false;
  37085. };
  37086. /**
  37087. * Makes a duplicate of the material, and gives it a new name
  37088. * @param name defines the new name for the duplicated material
  37089. * @returns the cloned material
  37090. */
  37091. Material.prototype.clone = function (name) {
  37092. return null;
  37093. };
  37094. /**
  37095. * Gets the meshes bound to the material
  37096. * @returns an array of meshes bound to the material
  37097. */
  37098. Material.prototype.getBindedMeshes = function () {
  37099. var _this = this;
  37100. if (this.meshMap) {
  37101. var result = new Array();
  37102. for (var meshId in this.meshMap) {
  37103. var mesh = this.meshMap[meshId];
  37104. if (mesh) {
  37105. result.push(mesh);
  37106. }
  37107. }
  37108. return result;
  37109. }
  37110. else {
  37111. var meshes = this._scene.meshes;
  37112. return meshes.filter(function (mesh) { return mesh.material === _this; });
  37113. }
  37114. };
  37115. /**
  37116. * Force shader compilation
  37117. * @param mesh defines the mesh associated with this material
  37118. * @param onCompiled defines a function to execute once the material is compiled
  37119. * @param options defines the options to configure the compilation
  37120. */
  37121. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  37122. var _this = this;
  37123. var localOptions = __assign({ clipPlane: false }, options);
  37124. var subMesh = new BABYLON.BaseSubMesh();
  37125. var scene = this.getScene();
  37126. var checkReady = function () {
  37127. if (!_this._scene || !_this._scene.getEngine()) {
  37128. return;
  37129. }
  37130. if (subMesh._materialDefines) {
  37131. subMesh._materialDefines._renderId = -1;
  37132. }
  37133. var clipPlaneState = scene.clipPlane;
  37134. if (localOptions.clipPlane) {
  37135. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  37136. }
  37137. if (_this._storeEffectOnSubMeshes) {
  37138. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  37139. if (onCompiled) {
  37140. onCompiled(_this);
  37141. }
  37142. }
  37143. else {
  37144. setTimeout(checkReady, 16);
  37145. }
  37146. }
  37147. else {
  37148. if (_this.isReady(mesh)) {
  37149. if (onCompiled) {
  37150. onCompiled(_this);
  37151. }
  37152. }
  37153. else {
  37154. setTimeout(checkReady, 16);
  37155. }
  37156. }
  37157. if (localOptions.clipPlane) {
  37158. scene.clipPlane = clipPlaneState;
  37159. }
  37160. };
  37161. checkReady();
  37162. };
  37163. /**
  37164. * Force shader compilation
  37165. * @param mesh defines the mesh that will use this material
  37166. * @param options defines additional options for compiling the shaders
  37167. * @returns a promise that resolves when the compilation completes
  37168. */
  37169. Material.prototype.forceCompilationAsync = function (mesh, options) {
  37170. var _this = this;
  37171. return new Promise(function (resolve) {
  37172. _this.forceCompilation(mesh, function () {
  37173. resolve();
  37174. }, options);
  37175. });
  37176. };
  37177. /**
  37178. * Marks a define in the material to indicate that it needs to be re-computed
  37179. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  37180. */
  37181. Material.prototype.markAsDirty = function (flag) {
  37182. if (flag & Material.TextureDirtyFlag) {
  37183. this._markAllSubMeshesAsTexturesDirty();
  37184. }
  37185. if (flag & Material.LightDirtyFlag) {
  37186. this._markAllSubMeshesAsLightsDirty();
  37187. }
  37188. if (flag & Material.FresnelDirtyFlag) {
  37189. this._markAllSubMeshesAsFresnelDirty();
  37190. }
  37191. if (flag & Material.AttributesDirtyFlag) {
  37192. this._markAllSubMeshesAsAttributesDirty();
  37193. }
  37194. if (flag & Material.MiscDirtyFlag) {
  37195. this._markAllSubMeshesAsMiscDirty();
  37196. }
  37197. this.getScene().resetCachedMaterial();
  37198. };
  37199. /**
  37200. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  37201. * @param func defines a function which checks material defines against the submeshes
  37202. */
  37203. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  37204. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  37205. var mesh = _a[_i];
  37206. if (!mesh.subMeshes) {
  37207. continue;
  37208. }
  37209. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  37210. var subMesh = _c[_b];
  37211. if (subMesh.getMaterial() !== this) {
  37212. continue;
  37213. }
  37214. if (!subMesh._materialDefines) {
  37215. continue;
  37216. }
  37217. func(subMesh._materialDefines);
  37218. }
  37219. }
  37220. };
  37221. /**
  37222. * Indicates that image processing needs to be re-calculated for all submeshes
  37223. */
  37224. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  37225. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  37226. };
  37227. /**
  37228. * Indicates that textures need to be re-calculated for all submeshes
  37229. */
  37230. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  37231. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  37232. };
  37233. /**
  37234. * Indicates that fresnel needs to be re-calculated for all submeshes
  37235. */
  37236. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  37237. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  37238. };
  37239. /**
  37240. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  37241. */
  37242. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  37243. this._markAllSubMeshesAsDirty(function (defines) {
  37244. defines.markAsFresnelDirty();
  37245. defines.markAsMiscDirty();
  37246. });
  37247. };
  37248. /**
  37249. * Indicates that lights need to be re-calculated for all submeshes
  37250. */
  37251. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  37252. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  37253. };
  37254. /**
  37255. * Indicates that attributes need to be re-calculated for all submeshes
  37256. */
  37257. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  37258. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  37259. };
  37260. /**
  37261. * Indicates that misc needs to be re-calculated for all submeshes
  37262. */
  37263. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  37264. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  37265. };
  37266. /**
  37267. * Indicates that textures and misc need to be re-calculated for all submeshes
  37268. */
  37269. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  37270. this._markAllSubMeshesAsDirty(function (defines) {
  37271. defines.markAsTexturesDirty();
  37272. defines.markAsMiscDirty();
  37273. });
  37274. };
  37275. /**
  37276. * Disposes the material
  37277. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  37278. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  37279. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  37280. */
  37281. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  37282. var scene = this.getScene();
  37283. // Animations
  37284. scene.stopAnimation(this);
  37285. scene.freeProcessedMaterials();
  37286. // Remove from scene
  37287. scene.removeMaterial(this);
  37288. if (notBoundToMesh !== true) {
  37289. // Remove from meshes
  37290. if (this.meshMap) {
  37291. for (var meshId in this.meshMap) {
  37292. var mesh = this.meshMap[meshId];
  37293. if (mesh) {
  37294. mesh.material = null; // will set the entry in the map to undefined
  37295. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37296. }
  37297. }
  37298. }
  37299. else {
  37300. var meshes = scene.meshes;
  37301. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  37302. var mesh = meshes_1[_i];
  37303. if (mesh.material === this) {
  37304. mesh.material = null;
  37305. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37306. }
  37307. }
  37308. }
  37309. }
  37310. this._uniformBuffer.dispose();
  37311. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37312. if (forceDisposeEffect && this._effect) {
  37313. if (!this._storeEffectOnSubMeshes) {
  37314. scene.getEngine()._releaseEffect(this._effect);
  37315. }
  37316. this._effect = null;
  37317. }
  37318. // Callback
  37319. this.onDisposeObservable.notifyObservers(this);
  37320. this.onDisposeObservable.clear();
  37321. if (this._onBindObservable) {
  37322. this._onBindObservable.clear();
  37323. }
  37324. if (this._onUnBindObservable) {
  37325. this._onUnBindObservable.clear();
  37326. }
  37327. };
  37328. /** @hidden */
  37329. Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) {
  37330. if (mesh.geometry) {
  37331. var geometry = (mesh.geometry);
  37332. var scene = this.getScene();
  37333. if (this._storeEffectOnSubMeshes) {
  37334. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  37335. var subMesh = _a[_i];
  37336. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  37337. if (forceDisposeEffect && subMesh._materialEffect) {
  37338. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  37339. }
  37340. }
  37341. }
  37342. else {
  37343. geometry._releaseVertexArrayObject(this._effect);
  37344. }
  37345. }
  37346. };
  37347. /**
  37348. * Serializes this material
  37349. * @returns the serialized material object
  37350. */
  37351. Material.prototype.serialize = function () {
  37352. return BABYLON.SerializationHelper.Serialize(this);
  37353. };
  37354. /**
  37355. * Creates a MultiMaterial from parsed MultiMaterial data.
  37356. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37357. * @param scene defines the hosting scene
  37358. * @returns a new MultiMaterial
  37359. */
  37360. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37361. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37362. multiMaterial.id = parsedMultiMaterial.id;
  37363. if (BABYLON.Tags) {
  37364. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37365. }
  37366. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37367. var subMatId = parsedMultiMaterial.materials[matIndex];
  37368. if (subMatId) {
  37369. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37370. }
  37371. else {
  37372. multiMaterial.subMaterials.push(null);
  37373. }
  37374. }
  37375. return multiMaterial;
  37376. };
  37377. /**
  37378. * Creates a material from parsed material data
  37379. * @param parsedMaterial defines parsed material data
  37380. * @param scene defines the hosting scene
  37381. * @param rootUrl defines the root URL to use to load textures
  37382. * @returns a new material
  37383. */
  37384. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37385. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37386. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37387. }
  37388. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37389. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37390. if (!BABYLON.LegacyPBRMaterial) {
  37391. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37392. return;
  37393. }
  37394. }
  37395. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37396. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37397. };
  37398. // Triangle views
  37399. Material._TriangleFillMode = 0;
  37400. Material._WireFrameFillMode = 1;
  37401. Material._PointFillMode = 2;
  37402. // Draw modes
  37403. Material._PointListDrawMode = 3;
  37404. Material._LineListDrawMode = 4;
  37405. Material._LineLoopDrawMode = 5;
  37406. Material._LineStripDrawMode = 6;
  37407. Material._TriangleStripDrawMode = 7;
  37408. Material._TriangleFanDrawMode = 8;
  37409. /**
  37410. * Stores the clock-wise side orientation
  37411. */
  37412. Material._ClockWiseSideOrientation = 0;
  37413. /**
  37414. * Stores the counter clock-wise side orientation
  37415. */
  37416. Material._CounterClockWiseSideOrientation = 1;
  37417. /**
  37418. * The dirty texture flag value
  37419. */
  37420. Material.TextureDirtyFlag = 1;
  37421. /**
  37422. * The dirty light flag value
  37423. */
  37424. Material.LightDirtyFlag = 2;
  37425. /**
  37426. * The dirty fresnel flag value
  37427. */
  37428. Material.FresnelDirtyFlag = 4;
  37429. /**
  37430. * The dirty attribute flag value
  37431. */
  37432. Material.AttributesDirtyFlag = 8;
  37433. /**
  37434. * The dirty misc flag value
  37435. */
  37436. Material.MiscDirtyFlag = 16;
  37437. /**
  37438. * The all dirty flag value
  37439. */
  37440. Material.AllDirtyFlag = 31;
  37441. __decorate([
  37442. BABYLON.serialize()
  37443. ], Material.prototype, "id", void 0);
  37444. __decorate([
  37445. BABYLON.serialize()
  37446. ], Material.prototype, "uniqueId", void 0);
  37447. __decorate([
  37448. BABYLON.serialize()
  37449. ], Material.prototype, "name", void 0);
  37450. __decorate([
  37451. BABYLON.serialize()
  37452. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37453. __decorate([
  37454. BABYLON.serialize()
  37455. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37456. __decorate([
  37457. BABYLON.serialize()
  37458. ], Material.prototype, "state", void 0);
  37459. __decorate([
  37460. BABYLON.serialize("alpha")
  37461. ], Material.prototype, "_alpha", void 0);
  37462. __decorate([
  37463. BABYLON.serialize("backFaceCulling")
  37464. ], Material.prototype, "_backFaceCulling", void 0);
  37465. __decorate([
  37466. BABYLON.serialize()
  37467. ], Material.prototype, "sideOrientation", void 0);
  37468. __decorate([
  37469. BABYLON.serialize("alphaMode")
  37470. ], Material.prototype, "_alphaMode", void 0);
  37471. __decorate([
  37472. BABYLON.serialize()
  37473. ], Material.prototype, "_needDepthPrePass", void 0);
  37474. __decorate([
  37475. BABYLON.serialize()
  37476. ], Material.prototype, "disableDepthWrite", void 0);
  37477. __decorate([
  37478. BABYLON.serialize()
  37479. ], Material.prototype, "forceDepthWrite", void 0);
  37480. __decorate([
  37481. BABYLON.serialize()
  37482. ], Material.prototype, "separateCullingPass", void 0);
  37483. __decorate([
  37484. BABYLON.serialize("fogEnabled")
  37485. ], Material.prototype, "_fogEnabled", void 0);
  37486. __decorate([
  37487. BABYLON.serialize()
  37488. ], Material.prototype, "pointSize", void 0);
  37489. __decorate([
  37490. BABYLON.serialize()
  37491. ], Material.prototype, "zOffset", void 0);
  37492. __decorate([
  37493. BABYLON.serialize()
  37494. ], Material.prototype, "wireframe", null);
  37495. __decorate([
  37496. BABYLON.serialize()
  37497. ], Material.prototype, "pointsCloud", null);
  37498. __decorate([
  37499. BABYLON.serialize()
  37500. ], Material.prototype, "fillMode", null);
  37501. return Material;
  37502. }());
  37503. BABYLON.Material = Material;
  37504. })(BABYLON || (BABYLON = {}));
  37505. //# sourceMappingURL=babylon.material.js.map
  37506. var BABYLON;
  37507. (function (BABYLON) {
  37508. /**
  37509. * Uniform buffer objects.
  37510. *
  37511. * Handles blocks of uniform on the GPU.
  37512. *
  37513. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37514. *
  37515. * For more information, please refer to :
  37516. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37517. */
  37518. var UniformBuffer = /** @class */ (function () {
  37519. /**
  37520. * Instantiates a new Uniform buffer objects.
  37521. *
  37522. * Handles blocks of uniform on the GPU.
  37523. *
  37524. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37525. *
  37526. * For more information, please refer to :
  37527. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37528. * @param engine Define the engine the buffer is associated with
  37529. * @param data Define the data contained in the buffer
  37530. * @param dynamic Define if the buffer is updatable
  37531. */
  37532. function UniformBuffer(engine, data, dynamic) {
  37533. this._engine = engine;
  37534. this._noUBO = !engine.supportsUniformBuffers;
  37535. this._dynamic = dynamic;
  37536. this._data = data || [];
  37537. this._uniformLocations = {};
  37538. this._uniformSizes = {};
  37539. this._uniformLocationPointer = 0;
  37540. this._needSync = false;
  37541. if (this._noUBO) {
  37542. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37543. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37544. this.updateFloat = this._updateFloatForEffect;
  37545. this.updateFloat2 = this._updateFloat2ForEffect;
  37546. this.updateFloat3 = this._updateFloat3ForEffect;
  37547. this.updateFloat4 = this._updateFloat4ForEffect;
  37548. this.updateMatrix = this._updateMatrixForEffect;
  37549. this.updateVector3 = this._updateVector3ForEffect;
  37550. this.updateVector4 = this._updateVector4ForEffect;
  37551. this.updateColor3 = this._updateColor3ForEffect;
  37552. this.updateColor4 = this._updateColor4ForEffect;
  37553. }
  37554. else {
  37555. this._engine._uniformBuffers.push(this);
  37556. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37557. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37558. this.updateFloat = this._updateFloatForUniform;
  37559. this.updateFloat2 = this._updateFloat2ForUniform;
  37560. this.updateFloat3 = this._updateFloat3ForUniform;
  37561. this.updateFloat4 = this._updateFloat4ForUniform;
  37562. this.updateMatrix = this._updateMatrixForUniform;
  37563. this.updateVector3 = this._updateVector3ForUniform;
  37564. this.updateVector4 = this._updateVector4ForUniform;
  37565. this.updateColor3 = this._updateColor3ForUniform;
  37566. this.updateColor4 = this._updateColor4ForUniform;
  37567. }
  37568. }
  37569. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37570. /**
  37571. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37572. * or just falling back on setUniformXXX calls.
  37573. */
  37574. get: function () {
  37575. return !this._noUBO;
  37576. },
  37577. enumerable: true,
  37578. configurable: true
  37579. });
  37580. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37581. /**
  37582. * Indicates if the WebGL underlying uniform buffer is in sync
  37583. * with the javascript cache data.
  37584. */
  37585. get: function () {
  37586. return !this._needSync;
  37587. },
  37588. enumerable: true,
  37589. configurable: true
  37590. });
  37591. /**
  37592. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37593. * Also, a dynamic UniformBuffer will disable cache verification and always
  37594. * update the underlying WebGL uniform buffer to the GPU.
  37595. * @returns if Dynamic, otherwise false
  37596. */
  37597. UniformBuffer.prototype.isDynamic = function () {
  37598. return this._dynamic !== undefined;
  37599. };
  37600. /**
  37601. * The data cache on JS side.
  37602. * @returns the underlying data as a float array
  37603. */
  37604. UniformBuffer.prototype.getData = function () {
  37605. return this._bufferData;
  37606. };
  37607. /**
  37608. * The underlying WebGL Uniform buffer.
  37609. * @returns the webgl buffer
  37610. */
  37611. UniformBuffer.prototype.getBuffer = function () {
  37612. return this._buffer;
  37613. };
  37614. /**
  37615. * std140 layout specifies how to align data within an UBO structure.
  37616. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37617. * for specs.
  37618. */
  37619. UniformBuffer.prototype._fillAlignment = function (size) {
  37620. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37621. // and 4x4 matrices
  37622. // TODO : change if other types are used
  37623. var alignment;
  37624. if (size <= 2) {
  37625. alignment = size;
  37626. }
  37627. else {
  37628. alignment = 4;
  37629. }
  37630. if ((this._uniformLocationPointer % alignment) !== 0) {
  37631. var oldPointer = this._uniformLocationPointer;
  37632. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37633. var diff = this._uniformLocationPointer - oldPointer;
  37634. for (var i = 0; i < diff; i++) {
  37635. this._data.push(0);
  37636. }
  37637. }
  37638. };
  37639. /**
  37640. * Adds an uniform in the buffer.
  37641. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37642. * for the layout to be correct !
  37643. * @param name Name of the uniform, as used in the uniform block in the shader.
  37644. * @param size Data size, or data directly.
  37645. */
  37646. UniformBuffer.prototype.addUniform = function (name, size) {
  37647. if (this._noUBO) {
  37648. return;
  37649. }
  37650. if (this._uniformLocations[name] !== undefined) {
  37651. // Already existing uniform
  37652. return;
  37653. }
  37654. // This function must be called in the order of the shader layout !
  37655. // size can be the size of the uniform, or data directly
  37656. var data;
  37657. if (size instanceof Array) {
  37658. data = size;
  37659. size = data.length;
  37660. }
  37661. else {
  37662. size = size;
  37663. data = [];
  37664. // Fill with zeros
  37665. for (var i = 0; i < size; i++) {
  37666. data.push(0);
  37667. }
  37668. }
  37669. this._fillAlignment(size);
  37670. this._uniformSizes[name] = size;
  37671. this._uniformLocations[name] = this._uniformLocationPointer;
  37672. this._uniformLocationPointer += size;
  37673. for (var i = 0; i < size; i++) {
  37674. this._data.push(data[i]);
  37675. }
  37676. this._needSync = true;
  37677. };
  37678. /**
  37679. * Adds a Matrix 4x4 to the uniform buffer.
  37680. * @param name Name of the uniform, as used in the uniform block in the shader.
  37681. * @param mat A 4x4 matrix.
  37682. */
  37683. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37684. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37685. };
  37686. /**
  37687. * Adds a vec2 to the uniform buffer.
  37688. * @param name Name of the uniform, as used in the uniform block in the shader.
  37689. * @param x Define the x component value of the vec2
  37690. * @param y Define the y component value of the vec2
  37691. */
  37692. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37693. var temp = [x, y];
  37694. this.addUniform(name, temp);
  37695. };
  37696. /**
  37697. * Adds a vec3 to the uniform buffer.
  37698. * @param name Name of the uniform, as used in the uniform block in the shader.
  37699. * @param x Define the x component value of the vec3
  37700. * @param y Define the y component value of the vec3
  37701. * @param z Define the z component value of the vec3
  37702. */
  37703. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37704. var temp = [x, y, z];
  37705. this.addUniform(name, temp);
  37706. };
  37707. /**
  37708. * Adds a vec3 to the uniform buffer.
  37709. * @param name Name of the uniform, as used in the uniform block in the shader.
  37710. * @param color Define the vec3 from a Color
  37711. */
  37712. UniformBuffer.prototype.addColor3 = function (name, color) {
  37713. var temp = new Array();
  37714. color.toArray(temp);
  37715. this.addUniform(name, temp);
  37716. };
  37717. /**
  37718. * Adds a vec4 to the uniform buffer.
  37719. * @param name Name of the uniform, as used in the uniform block in the shader.
  37720. * @param color Define the rgb components from a Color
  37721. * @param alpha Define the a component of the vec4
  37722. */
  37723. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37724. var temp = new Array();
  37725. color.toArray(temp);
  37726. temp.push(alpha);
  37727. this.addUniform(name, temp);
  37728. };
  37729. /**
  37730. * Adds a vec3 to the uniform buffer.
  37731. * @param name Name of the uniform, as used in the uniform block in the shader.
  37732. * @param vector Define the vec3 components from a Vector
  37733. */
  37734. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37735. var temp = new Array();
  37736. vector.toArray(temp);
  37737. this.addUniform(name, temp);
  37738. };
  37739. /**
  37740. * Adds a Matrix 3x3 to the uniform buffer.
  37741. * @param name Name of the uniform, as used in the uniform block in the shader.
  37742. */
  37743. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37744. this.addUniform(name, 12);
  37745. };
  37746. /**
  37747. * Adds a Matrix 2x2 to the uniform buffer.
  37748. * @param name Name of the uniform, as used in the uniform block in the shader.
  37749. */
  37750. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37751. this.addUniform(name, 8);
  37752. };
  37753. /**
  37754. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37755. */
  37756. UniformBuffer.prototype.create = function () {
  37757. if (this._noUBO) {
  37758. return;
  37759. }
  37760. if (this._buffer) {
  37761. return; // nothing to do
  37762. }
  37763. // See spec, alignment must be filled as a vec4
  37764. this._fillAlignment(4);
  37765. this._bufferData = new Float32Array(this._data);
  37766. this._rebuild();
  37767. this._needSync = true;
  37768. };
  37769. /** @hidden */
  37770. UniformBuffer.prototype._rebuild = function () {
  37771. if (this._noUBO) {
  37772. return;
  37773. }
  37774. if (this._dynamic) {
  37775. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37776. }
  37777. else {
  37778. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37779. }
  37780. };
  37781. /**
  37782. * Updates the WebGL Uniform Buffer on the GPU.
  37783. * If the `dynamic` flag is set to true, no cache comparison is done.
  37784. * Otherwise, the buffer will be updated only if the cache differs.
  37785. */
  37786. UniformBuffer.prototype.update = function () {
  37787. if (!this._buffer) {
  37788. this.create();
  37789. return;
  37790. }
  37791. if (!this._dynamic && !this._needSync) {
  37792. return;
  37793. }
  37794. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37795. this._needSync = false;
  37796. };
  37797. /**
  37798. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37799. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37800. * @param data Define the flattened data
  37801. * @param size Define the size of the data.
  37802. */
  37803. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37804. var location = this._uniformLocations[uniformName];
  37805. if (location === undefined) {
  37806. if (this._buffer) {
  37807. // Cannot add an uniform if the buffer is already created
  37808. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37809. return;
  37810. }
  37811. this.addUniform(uniformName, size);
  37812. location = this._uniformLocations[uniformName];
  37813. }
  37814. if (!this._buffer) {
  37815. this.create();
  37816. }
  37817. if (!this._dynamic) {
  37818. // Cache for static uniform buffers
  37819. var changed = false;
  37820. for (var i = 0; i < size; i++) {
  37821. if (this._bufferData[location + i] !== data[i]) {
  37822. changed = true;
  37823. this._bufferData[location + i] = data[i];
  37824. }
  37825. }
  37826. this._needSync = this._needSync || changed;
  37827. }
  37828. else {
  37829. // No cache for dynamic
  37830. for (var i = 0; i < size; i++) {
  37831. this._bufferData[location + i] = data[i];
  37832. }
  37833. }
  37834. };
  37835. // Update methods
  37836. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37837. // To match std140, matrix must be realigned
  37838. for (var i = 0; i < 3; i++) {
  37839. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37840. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37841. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37842. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37843. }
  37844. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37845. };
  37846. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37847. this._currentEffect.setMatrix3x3(name, matrix);
  37848. };
  37849. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37850. this._currentEffect.setMatrix2x2(name, matrix);
  37851. };
  37852. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37853. // To match std140, matrix must be realigned
  37854. for (var i = 0; i < 2; i++) {
  37855. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37856. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37857. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37858. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37859. }
  37860. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37861. };
  37862. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37863. this._currentEffect.setFloat(name, x);
  37864. };
  37865. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37866. UniformBuffer._tempBuffer[0] = x;
  37867. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37868. };
  37869. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37870. if (suffix === void 0) { suffix = ""; }
  37871. this._currentEffect.setFloat2(name + suffix, x, y);
  37872. };
  37873. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37874. if (suffix === void 0) { suffix = ""; }
  37875. UniformBuffer._tempBuffer[0] = x;
  37876. UniformBuffer._tempBuffer[1] = y;
  37877. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37878. };
  37879. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37880. if (suffix === void 0) { suffix = ""; }
  37881. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37882. };
  37883. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37884. if (suffix === void 0) { suffix = ""; }
  37885. UniformBuffer._tempBuffer[0] = x;
  37886. UniformBuffer._tempBuffer[1] = y;
  37887. UniformBuffer._tempBuffer[2] = z;
  37888. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37889. };
  37890. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37891. if (suffix === void 0) { suffix = ""; }
  37892. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37893. };
  37894. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37895. if (suffix === void 0) { suffix = ""; }
  37896. UniformBuffer._tempBuffer[0] = x;
  37897. UniformBuffer._tempBuffer[1] = y;
  37898. UniformBuffer._tempBuffer[2] = z;
  37899. UniformBuffer._tempBuffer[3] = w;
  37900. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37901. };
  37902. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37903. this._currentEffect.setMatrix(name, mat);
  37904. };
  37905. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37906. this.updateUniform(name, mat.toArray(), 16);
  37907. };
  37908. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37909. this._currentEffect.setVector3(name, vector);
  37910. };
  37911. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37912. vector.toArray(UniformBuffer._tempBuffer);
  37913. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37914. };
  37915. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37916. this._currentEffect.setVector4(name, vector);
  37917. };
  37918. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37919. vector.toArray(UniformBuffer._tempBuffer);
  37920. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37921. };
  37922. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37923. if (suffix === void 0) { suffix = ""; }
  37924. this._currentEffect.setColor3(name + suffix, color);
  37925. };
  37926. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37927. if (suffix === void 0) { suffix = ""; }
  37928. color.toArray(UniformBuffer._tempBuffer);
  37929. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37930. };
  37931. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37932. if (suffix === void 0) { suffix = ""; }
  37933. this._currentEffect.setColor4(name + suffix, color, alpha);
  37934. };
  37935. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37936. if (suffix === void 0) { suffix = ""; }
  37937. color.toArray(UniformBuffer._tempBuffer);
  37938. UniformBuffer._tempBuffer[3] = alpha;
  37939. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37940. };
  37941. /**
  37942. * Sets a sampler uniform on the effect.
  37943. * @param name Define the name of the sampler.
  37944. * @param texture Define the texture to set in the sampler
  37945. */
  37946. UniformBuffer.prototype.setTexture = function (name, texture) {
  37947. this._currentEffect.setTexture(name, texture);
  37948. };
  37949. /**
  37950. * Directly updates the value of the uniform in the cache AND on the GPU.
  37951. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37952. * @param data Define the flattened data
  37953. */
  37954. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37955. this.updateUniform(uniformName, data, data.length);
  37956. this.update();
  37957. };
  37958. /**
  37959. * Binds this uniform buffer to an effect.
  37960. * @param effect Define the effect to bind the buffer to
  37961. * @param name Name of the uniform block in the shader.
  37962. */
  37963. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37964. this._currentEffect = effect;
  37965. if (this._noUBO || !this._buffer) {
  37966. return;
  37967. }
  37968. effect.bindUniformBuffer(this._buffer, name);
  37969. };
  37970. /**
  37971. * Disposes the uniform buffer.
  37972. */
  37973. UniformBuffer.prototype.dispose = function () {
  37974. if (this._noUBO) {
  37975. return;
  37976. }
  37977. var uniformBuffers = this._engine._uniformBuffers;
  37978. var index = uniformBuffers.indexOf(this);
  37979. if (index !== -1) {
  37980. uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
  37981. uniformBuffers.pop();
  37982. }
  37983. if (!this._buffer) {
  37984. return;
  37985. }
  37986. if (this._engine._releaseBuffer(this._buffer)) {
  37987. this._buffer = null;
  37988. }
  37989. };
  37990. // Pool for avoiding memory leaks
  37991. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37992. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37993. return UniformBuffer;
  37994. }());
  37995. BABYLON.UniformBuffer = UniformBuffer;
  37996. })(BABYLON || (BABYLON = {}));
  37997. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37998. var BABYLON;
  37999. (function (BABYLON) {
  38000. /**
  38001. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  38002. */
  38003. var VertexData = /** @class */ (function () {
  38004. function VertexData() {
  38005. }
  38006. /**
  38007. * Uses the passed data array to set the set the values for the specified kind of data
  38008. * @param data a linear array of floating numbers
  38009. * @param kind the type of data that is being set, eg positions, colors etc
  38010. */
  38011. VertexData.prototype.set = function (data, kind) {
  38012. switch (kind) {
  38013. case BABYLON.VertexBuffer.PositionKind:
  38014. this.positions = data;
  38015. break;
  38016. case BABYLON.VertexBuffer.NormalKind:
  38017. this.normals = data;
  38018. break;
  38019. case BABYLON.VertexBuffer.TangentKind:
  38020. this.tangents = data;
  38021. break;
  38022. case BABYLON.VertexBuffer.UVKind:
  38023. this.uvs = data;
  38024. break;
  38025. case BABYLON.VertexBuffer.UV2Kind:
  38026. this.uvs2 = data;
  38027. break;
  38028. case BABYLON.VertexBuffer.UV3Kind:
  38029. this.uvs3 = data;
  38030. break;
  38031. case BABYLON.VertexBuffer.UV4Kind:
  38032. this.uvs4 = data;
  38033. break;
  38034. case BABYLON.VertexBuffer.UV5Kind:
  38035. this.uvs5 = data;
  38036. break;
  38037. case BABYLON.VertexBuffer.UV6Kind:
  38038. this.uvs6 = data;
  38039. break;
  38040. case BABYLON.VertexBuffer.ColorKind:
  38041. this.colors = data;
  38042. break;
  38043. case BABYLON.VertexBuffer.MatricesIndicesKind:
  38044. this.matricesIndices = data;
  38045. break;
  38046. case BABYLON.VertexBuffer.MatricesWeightsKind:
  38047. this.matricesWeights = data;
  38048. break;
  38049. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  38050. this.matricesIndicesExtra = data;
  38051. break;
  38052. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  38053. this.matricesWeightsExtra = data;
  38054. break;
  38055. }
  38056. };
  38057. /**
  38058. * Associates the vertexData to the passed Mesh.
  38059. * Sets it as updatable or not (default `false`)
  38060. * @param mesh the mesh the vertexData is applied to
  38061. * @param updatable when used and having the value true allows new data to update the vertexData
  38062. * @returns the VertexData
  38063. */
  38064. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  38065. this._applyTo(mesh, updatable);
  38066. return this;
  38067. };
  38068. /**
  38069. * Associates the vertexData to the passed Geometry.
  38070. * Sets it as updatable or not (default `false`)
  38071. * @param geometry the geometry the vertexData is applied to
  38072. * @param updatable when used and having the value true allows new data to update the vertexData
  38073. * @returns VertexData
  38074. */
  38075. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38076. this._applyTo(geometry, updatable);
  38077. return this;
  38078. };
  38079. /**
  38080. * Updates the associated mesh
  38081. * @param mesh the mesh to be updated
  38082. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38083. * @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
  38084. * @returns VertexData
  38085. */
  38086. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38087. this._update(mesh);
  38088. return this;
  38089. };
  38090. /**
  38091. * Updates the associated geometry
  38092. * @param geometry the geometry to be updated
  38093. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38094. * @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
  38095. * @returns VertexData.
  38096. */
  38097. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38098. this._update(geometry);
  38099. return this;
  38100. };
  38101. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38102. if (updatable === void 0) { updatable = false; }
  38103. if (this.positions) {
  38104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38105. }
  38106. if (this.normals) {
  38107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38108. }
  38109. if (this.tangents) {
  38110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38111. }
  38112. if (this.uvs) {
  38113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38114. }
  38115. if (this.uvs2) {
  38116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38117. }
  38118. if (this.uvs3) {
  38119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38120. }
  38121. if (this.uvs4) {
  38122. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38123. }
  38124. if (this.uvs5) {
  38125. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38126. }
  38127. if (this.uvs6) {
  38128. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38129. }
  38130. if (this.colors) {
  38131. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38132. }
  38133. if (this.matricesIndices) {
  38134. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38135. }
  38136. if (this.matricesWeights) {
  38137. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38138. }
  38139. if (this.matricesIndicesExtra) {
  38140. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38141. }
  38142. if (this.matricesWeightsExtra) {
  38143. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38144. }
  38145. if (this.indices) {
  38146. meshOrGeometry.setIndices(this.indices, null, updatable);
  38147. }
  38148. else {
  38149. meshOrGeometry.setIndices([], null);
  38150. }
  38151. return this;
  38152. };
  38153. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38154. if (this.positions) {
  38155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38156. }
  38157. if (this.normals) {
  38158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38159. }
  38160. if (this.tangents) {
  38161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38162. }
  38163. if (this.uvs) {
  38164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38165. }
  38166. if (this.uvs2) {
  38167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38168. }
  38169. if (this.uvs3) {
  38170. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38171. }
  38172. if (this.uvs4) {
  38173. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38174. }
  38175. if (this.uvs5) {
  38176. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38177. }
  38178. if (this.uvs6) {
  38179. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38180. }
  38181. if (this.colors) {
  38182. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38183. }
  38184. if (this.matricesIndices) {
  38185. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38186. }
  38187. if (this.matricesWeights) {
  38188. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38189. }
  38190. if (this.matricesIndicesExtra) {
  38191. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38192. }
  38193. if (this.matricesWeightsExtra) {
  38194. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38195. }
  38196. if (this.indices) {
  38197. meshOrGeometry.setIndices(this.indices, null);
  38198. }
  38199. return this;
  38200. };
  38201. /**
  38202. * Transforms each position and each normal of the vertexData according to the passed Matrix
  38203. * @param matrix the transforming matrix
  38204. * @returns the VertexData
  38205. */
  38206. VertexData.prototype.transform = function (matrix) {
  38207. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  38208. var transformed = BABYLON.Vector3.Zero();
  38209. var index;
  38210. if (this.positions) {
  38211. var position = BABYLON.Vector3.Zero();
  38212. for (index = 0; index < this.positions.length; index += 3) {
  38213. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38214. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38215. this.positions[index] = transformed.x;
  38216. this.positions[index + 1] = transformed.y;
  38217. this.positions[index + 2] = transformed.z;
  38218. }
  38219. }
  38220. if (this.normals) {
  38221. var normal = BABYLON.Vector3.Zero();
  38222. for (index = 0; index < this.normals.length; index += 3) {
  38223. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38224. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38225. this.normals[index] = transformed.x;
  38226. this.normals[index + 1] = transformed.y;
  38227. this.normals[index + 2] = transformed.z;
  38228. }
  38229. }
  38230. if (this.tangents) {
  38231. var tangent = BABYLON.Vector4.Zero();
  38232. var tangentTransformed = BABYLON.Vector4.Zero();
  38233. for (index = 0; index < this.tangents.length; index += 4) {
  38234. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38235. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38236. this.tangents[index] = tangentTransformed.x;
  38237. this.tangents[index + 1] = tangentTransformed.y;
  38238. this.tangents[index + 2] = tangentTransformed.z;
  38239. this.tangents[index + 3] = tangentTransformed.w;
  38240. }
  38241. }
  38242. if (flip && this.indices) {
  38243. for (index = 0; index < this.indices.length; index += 3) {
  38244. var tmp = this.indices[index + 1];
  38245. this.indices[index + 1] = this.indices[index + 2];
  38246. this.indices[index + 2] = tmp;
  38247. }
  38248. }
  38249. return this;
  38250. };
  38251. /**
  38252. * Merges the passed VertexData into the current one
  38253. * @param other the VertexData to be merged into the current one
  38254. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  38255. * @returns the modified VertexData
  38256. */
  38257. VertexData.prototype.merge = function (other, use32BitsIndices) {
  38258. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  38259. this._validate();
  38260. other._validate();
  38261. if (!this.normals !== !other.normals ||
  38262. !this.tangents !== !other.tangents ||
  38263. !this.uvs !== !other.uvs ||
  38264. !this.uvs2 !== !other.uvs2 ||
  38265. !this.uvs3 !== !other.uvs3 ||
  38266. !this.uvs4 !== !other.uvs4 ||
  38267. !this.uvs5 !== !other.uvs5 ||
  38268. !this.uvs6 !== !other.uvs6 ||
  38269. !this.colors !== !other.colors ||
  38270. !this.matricesIndices !== !other.matricesIndices ||
  38271. !this.matricesWeights !== !other.matricesWeights ||
  38272. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  38273. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  38274. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  38275. }
  38276. if (other.indices) {
  38277. if (!this.indices) {
  38278. this.indices = [];
  38279. }
  38280. var offset = this.positions ? this.positions.length / 3 : 0;
  38281. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  38282. if (isSrcTypedArray) {
  38283. var len = this.indices.length + other.indices.length;
  38284. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  38285. temp.set(this.indices);
  38286. var decal = this.indices.length;
  38287. for (var index = 0; index < other.indices.length; index++) {
  38288. temp[decal + index] = other.indices[index] + offset;
  38289. }
  38290. this.indices = temp;
  38291. }
  38292. else {
  38293. for (var index = 0; index < other.indices.length; index++) {
  38294. this.indices.push(other.indices[index] + offset);
  38295. }
  38296. }
  38297. }
  38298. this.positions = this._mergeElement(this.positions, other.positions);
  38299. this.normals = this._mergeElement(this.normals, other.normals);
  38300. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38301. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38302. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38303. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38304. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38305. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38306. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38307. this.colors = this._mergeElement(this.colors, other.colors);
  38308. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38309. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38310. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38311. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38312. return this;
  38313. };
  38314. VertexData.prototype._mergeElement = function (source, other) {
  38315. if (!source) {
  38316. return other;
  38317. }
  38318. if (!other) {
  38319. return source;
  38320. }
  38321. var len = other.length + source.length;
  38322. var isSrcTypedArray = source instanceof Float32Array;
  38323. var isOthTypedArray = other instanceof Float32Array;
  38324. // use non-loop method when the source is Float32Array
  38325. if (isSrcTypedArray) {
  38326. var ret32 = new Float32Array(len);
  38327. ret32.set(source);
  38328. ret32.set(other, source.length);
  38329. return ret32;
  38330. // source is number[], when other is also use concat
  38331. }
  38332. else if (!isOthTypedArray) {
  38333. return source.concat(other);
  38334. // source is a number[], but other is a Float32Array, loop required
  38335. }
  38336. else {
  38337. var ret = source.slice(0); // copy source to a separate array
  38338. for (var i = 0, len = other.length; i < len; i++) {
  38339. ret.push(other[i]);
  38340. }
  38341. return ret;
  38342. }
  38343. };
  38344. VertexData.prototype._validate = function () {
  38345. if (!this.positions) {
  38346. throw new Error("Positions are required");
  38347. }
  38348. var getElementCount = function (kind, values) {
  38349. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38350. if ((values.length % stride) !== 0) {
  38351. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38352. }
  38353. return values.length / stride;
  38354. };
  38355. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38356. var validateElementCount = function (kind, values) {
  38357. var elementCount = getElementCount(kind, values);
  38358. if (elementCount !== positionsElementCount) {
  38359. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38360. }
  38361. };
  38362. if (this.normals) {
  38363. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38364. }
  38365. if (this.tangents) {
  38366. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38367. }
  38368. if (this.uvs) {
  38369. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38370. }
  38371. if (this.uvs2) {
  38372. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38373. }
  38374. if (this.uvs3) {
  38375. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38376. }
  38377. if (this.uvs4) {
  38378. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38379. }
  38380. if (this.uvs5) {
  38381. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38382. }
  38383. if (this.uvs6) {
  38384. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38385. }
  38386. if (this.colors) {
  38387. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38388. }
  38389. if (this.matricesIndices) {
  38390. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38391. }
  38392. if (this.matricesWeights) {
  38393. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38394. }
  38395. if (this.matricesIndicesExtra) {
  38396. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38397. }
  38398. if (this.matricesWeightsExtra) {
  38399. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38400. }
  38401. };
  38402. /**
  38403. * Serializes the VertexData
  38404. * @returns a serialized object
  38405. */
  38406. VertexData.prototype.serialize = function () {
  38407. var serializationObject = this.serialize();
  38408. if (this.positions) {
  38409. serializationObject.positions = this.positions;
  38410. }
  38411. if (this.normals) {
  38412. serializationObject.normals = this.normals;
  38413. }
  38414. if (this.tangents) {
  38415. serializationObject.tangents = this.tangents;
  38416. }
  38417. if (this.uvs) {
  38418. serializationObject.uvs = this.uvs;
  38419. }
  38420. if (this.uvs2) {
  38421. serializationObject.uvs2 = this.uvs2;
  38422. }
  38423. if (this.uvs3) {
  38424. serializationObject.uvs3 = this.uvs3;
  38425. }
  38426. if (this.uvs4) {
  38427. serializationObject.uvs4 = this.uvs4;
  38428. }
  38429. if (this.uvs5) {
  38430. serializationObject.uvs5 = this.uvs5;
  38431. }
  38432. if (this.uvs6) {
  38433. serializationObject.uvs6 = this.uvs6;
  38434. }
  38435. if (this.colors) {
  38436. serializationObject.colors = this.colors;
  38437. }
  38438. if (this.matricesIndices) {
  38439. serializationObject.matricesIndices = this.matricesIndices;
  38440. serializationObject.matricesIndices._isExpanded = true;
  38441. }
  38442. if (this.matricesWeights) {
  38443. serializationObject.matricesWeights = this.matricesWeights;
  38444. }
  38445. if (this.matricesIndicesExtra) {
  38446. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38447. serializationObject.matricesIndicesExtra._isExpanded = true;
  38448. }
  38449. if (this.matricesWeightsExtra) {
  38450. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38451. }
  38452. serializationObject.indices = this.indices;
  38453. return serializationObject;
  38454. };
  38455. // Statics
  38456. /**
  38457. * Extracts the vertexData from a mesh
  38458. * @param mesh the mesh from which to extract the VertexData
  38459. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38460. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38461. * @returns the object VertexData associated to the passed mesh
  38462. */
  38463. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38464. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38465. };
  38466. /**
  38467. * Extracts the vertexData from the geometry
  38468. * @param geometry the geometry from which to extract the VertexData
  38469. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38470. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38471. * @returns the object VertexData associated to the passed mesh
  38472. */
  38473. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38474. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38475. };
  38476. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38477. var result = new VertexData();
  38478. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38479. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38480. }
  38481. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38482. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38483. }
  38484. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38485. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38486. }
  38487. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38488. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38489. }
  38490. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38491. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38492. }
  38493. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38494. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38495. }
  38496. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38497. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38498. }
  38499. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38500. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38501. }
  38502. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38503. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38504. }
  38505. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38506. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38507. }
  38508. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38509. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38510. }
  38511. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38512. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38513. }
  38514. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38515. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38516. }
  38517. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38518. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38519. }
  38520. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38521. return result;
  38522. };
  38523. /**
  38524. * Creates the VertexData for a Ribbon
  38525. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38526. * * pathArray array of paths, each of which an array of successive Vector3
  38527. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38528. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38529. * * 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
  38530. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38531. * * 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)
  38532. * * 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)
  38533. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38534. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38535. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38536. * @returns the VertexData of the ribbon
  38537. */
  38538. VertexData.CreateRibbon = function (options) {
  38539. var pathArray = options.pathArray;
  38540. var closeArray = options.closeArray || false;
  38541. var closePath = options.closePath || false;
  38542. var invertUV = options.invertUV || false;
  38543. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38544. var offset = options.offset || defaultOffset;
  38545. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38546. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38547. var customUV = options.uvs;
  38548. var customColors = options.colors;
  38549. var positions = [];
  38550. var indices = [];
  38551. var normals = [];
  38552. var uvs = [];
  38553. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38554. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38555. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38556. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38557. var minlg; // minimal length among all paths from pathArray
  38558. var lg = []; // array of path lengths : nb of vertex per path
  38559. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38560. var p; // path iterator
  38561. var i; // point iterator
  38562. var j; // point iterator
  38563. // if single path in pathArray
  38564. if (pathArray.length < 2) {
  38565. var ar1 = [];
  38566. var ar2 = [];
  38567. for (i = 0; i < pathArray[0].length - offset; i++) {
  38568. ar1.push(pathArray[0][i]);
  38569. ar2.push(pathArray[0][i + offset]);
  38570. }
  38571. pathArray = [ar1, ar2];
  38572. }
  38573. // positions and horizontal distances (u)
  38574. var idc = 0;
  38575. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38576. var path;
  38577. var l;
  38578. minlg = pathArray[0].length;
  38579. var vectlg;
  38580. var dist;
  38581. for (p = 0; p < pathArray.length; p++) {
  38582. uTotalDistance[p] = 0;
  38583. us[p] = [0];
  38584. path = pathArray[p];
  38585. l = path.length;
  38586. minlg = (minlg < l) ? minlg : l;
  38587. j = 0;
  38588. while (j < l) {
  38589. positions.push(path[j].x, path[j].y, path[j].z);
  38590. if (j > 0) {
  38591. vectlg = path[j].subtract(path[j - 1]).length();
  38592. dist = vectlg + uTotalDistance[p];
  38593. us[p].push(dist);
  38594. uTotalDistance[p] = dist;
  38595. }
  38596. j++;
  38597. }
  38598. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38599. j--;
  38600. positions.push(path[0].x, path[0].y, path[0].z);
  38601. vectlg = path[j].subtract(path[0]).length();
  38602. dist = vectlg + uTotalDistance[p];
  38603. us[p].push(dist);
  38604. uTotalDistance[p] = dist;
  38605. }
  38606. lg[p] = l + closePathCorr;
  38607. idx[p] = idc;
  38608. idc += (l + closePathCorr);
  38609. }
  38610. // vertical distances (v)
  38611. var path1;
  38612. var path2;
  38613. var vertex1 = null;
  38614. var vertex2 = null;
  38615. for (i = 0; i < minlg + closePathCorr; i++) {
  38616. vTotalDistance[i] = 0;
  38617. vs[i] = [0];
  38618. for (p = 0; p < pathArray.length - 1; p++) {
  38619. path1 = pathArray[p];
  38620. path2 = pathArray[p + 1];
  38621. if (i === minlg) { // closePath
  38622. vertex1 = path1[0];
  38623. vertex2 = path2[0];
  38624. }
  38625. else {
  38626. vertex1 = path1[i];
  38627. vertex2 = path2[i];
  38628. }
  38629. vectlg = vertex2.subtract(vertex1).length();
  38630. dist = vectlg + vTotalDistance[i];
  38631. vs[i].push(dist);
  38632. vTotalDistance[i] = dist;
  38633. }
  38634. if (closeArray && vertex2 && vertex1) {
  38635. path1 = pathArray[p];
  38636. path2 = pathArray[0];
  38637. if (i === minlg) { // closePath
  38638. vertex2 = path2[0];
  38639. }
  38640. vectlg = vertex2.subtract(vertex1).length();
  38641. dist = vectlg + vTotalDistance[i];
  38642. vTotalDistance[i] = dist;
  38643. }
  38644. }
  38645. // uvs
  38646. var u;
  38647. var v;
  38648. if (customUV) {
  38649. for (p = 0; p < customUV.length; p++) {
  38650. uvs.push(customUV[p].x, customUV[p].y);
  38651. }
  38652. }
  38653. else {
  38654. for (p = 0; p < pathArray.length; p++) {
  38655. for (i = 0; i < minlg + closePathCorr; i++) {
  38656. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38657. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38658. if (invertUV) {
  38659. uvs.push(v, u);
  38660. }
  38661. else {
  38662. uvs.push(u, v);
  38663. }
  38664. }
  38665. }
  38666. }
  38667. // indices
  38668. p = 0; // path index
  38669. var pi = 0; // positions array index
  38670. var l1 = lg[p] - 1; // path1 length
  38671. var l2 = lg[p + 1] - 1; // path2 length
  38672. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38673. var shft = idx[1] - idx[0]; // shift
  38674. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38675. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38676. // 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
  38677. indices.push(pi, pi + shft, pi + 1);
  38678. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38679. pi += 1;
  38680. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38681. p++;
  38682. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38683. shft = idx[0] - idx[p];
  38684. l1 = lg[p] - 1;
  38685. l2 = lg[0] - 1;
  38686. }
  38687. else {
  38688. shft = idx[p + 1] - idx[p];
  38689. l1 = lg[p] - 1;
  38690. l2 = lg[p + 1] - 1;
  38691. }
  38692. pi = idx[p];
  38693. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38694. }
  38695. }
  38696. // normals
  38697. VertexData.ComputeNormals(positions, indices, normals);
  38698. if (closePath) { // update both the first and last vertex normals to their average value
  38699. var indexFirst = 0;
  38700. var indexLast = 0;
  38701. for (p = 0; p < pathArray.length; p++) {
  38702. indexFirst = idx[p] * 3;
  38703. if (p + 1 < pathArray.length) {
  38704. indexLast = (idx[p + 1] - 1) * 3;
  38705. }
  38706. else {
  38707. indexLast = normals.length - 3;
  38708. }
  38709. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38710. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38711. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38712. normals[indexLast] = normals[indexFirst];
  38713. normals[indexLast + 1] = normals[indexFirst + 1];
  38714. normals[indexLast + 2] = normals[indexFirst + 2];
  38715. }
  38716. }
  38717. // sides
  38718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38719. // Colors
  38720. var colors = null;
  38721. if (customColors) {
  38722. colors = new Float32Array(customColors.length * 4);
  38723. for (var c = 0; c < customColors.length; c++) {
  38724. colors[c * 4] = customColors[c].r;
  38725. colors[c * 4 + 1] = customColors[c].g;
  38726. colors[c * 4 + 2] = customColors[c].b;
  38727. colors[c * 4 + 3] = customColors[c].a;
  38728. }
  38729. }
  38730. // Result
  38731. var vertexData = new VertexData();
  38732. var positions32 = new Float32Array(positions);
  38733. var normals32 = new Float32Array(normals);
  38734. var uvs32 = new Float32Array(uvs);
  38735. vertexData.indices = indices;
  38736. vertexData.positions = positions32;
  38737. vertexData.normals = normals32;
  38738. vertexData.uvs = uvs32;
  38739. if (colors) {
  38740. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38741. }
  38742. if (closePath) {
  38743. vertexData._idx = idx;
  38744. }
  38745. return vertexData;
  38746. };
  38747. /**
  38748. * Creates the VertexData for a box
  38749. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38750. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38751. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38752. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38753. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38754. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38755. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38756. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38757. * * 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)
  38758. * * 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)
  38759. * @returns the VertexData of the box
  38760. */
  38761. VertexData.CreateBox = function (options) {
  38762. var normalsSource = [
  38763. new BABYLON.Vector3(0, 0, 1),
  38764. new BABYLON.Vector3(0, 0, -1),
  38765. new BABYLON.Vector3(1, 0, 0),
  38766. new BABYLON.Vector3(-1, 0, 0),
  38767. new BABYLON.Vector3(0, 1, 0),
  38768. new BABYLON.Vector3(0, -1, 0)
  38769. ];
  38770. var indices = [];
  38771. var positions = [];
  38772. var normals = [];
  38773. var uvs = [];
  38774. var width = options.width || options.size || 1;
  38775. var height = options.height || options.size || 1;
  38776. var depth = options.depth || options.size || 1;
  38777. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38778. var faceUV = options.faceUV || new Array(6);
  38779. var faceColors = options.faceColors;
  38780. var colors = [];
  38781. // default face colors and UV if undefined
  38782. for (var f = 0; f < 6; f++) {
  38783. if (faceUV[f] === undefined) {
  38784. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38785. }
  38786. if (faceColors && faceColors[f] === undefined) {
  38787. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38788. }
  38789. }
  38790. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38791. // Create each face in turn.
  38792. for (var index = 0; index < normalsSource.length; index++) {
  38793. var normal = normalsSource[index];
  38794. // Get two vectors perpendicular to the face normal and to each other.
  38795. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38796. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38797. // Six indices (two triangles) per face.
  38798. var verticesLength = positions.length / 3;
  38799. indices.push(verticesLength);
  38800. indices.push(verticesLength + 1);
  38801. indices.push(verticesLength + 2);
  38802. indices.push(verticesLength);
  38803. indices.push(verticesLength + 2);
  38804. indices.push(verticesLength + 3);
  38805. // Four vertices per face.
  38806. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38807. positions.push(vertex.x, vertex.y, vertex.z);
  38808. normals.push(normal.x, normal.y, normal.z);
  38809. uvs.push(faceUV[index].z, faceUV[index].w);
  38810. if (faceColors) {
  38811. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38812. }
  38813. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38814. positions.push(vertex.x, vertex.y, vertex.z);
  38815. normals.push(normal.x, normal.y, normal.z);
  38816. uvs.push(faceUV[index].x, faceUV[index].w);
  38817. if (faceColors) {
  38818. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38819. }
  38820. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38821. positions.push(vertex.x, vertex.y, vertex.z);
  38822. normals.push(normal.x, normal.y, normal.z);
  38823. uvs.push(faceUV[index].x, faceUV[index].y);
  38824. if (faceColors) {
  38825. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38826. }
  38827. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38828. positions.push(vertex.x, vertex.y, vertex.z);
  38829. normals.push(normal.x, normal.y, normal.z);
  38830. uvs.push(faceUV[index].z, faceUV[index].y);
  38831. if (faceColors) {
  38832. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38833. }
  38834. }
  38835. // sides
  38836. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38837. // Result
  38838. var vertexData = new VertexData();
  38839. vertexData.indices = indices;
  38840. vertexData.positions = positions;
  38841. vertexData.normals = normals;
  38842. vertexData.uvs = uvs;
  38843. if (faceColors) {
  38844. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38845. vertexData.colors = totalColors;
  38846. }
  38847. return vertexData;
  38848. };
  38849. /**
  38850. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38851. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38852. * * segments sets the number of horizontal strips optional, default 32
  38853. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38854. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38855. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38856. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38857. * * 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
  38858. * * 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
  38859. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38860. * * 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)
  38861. * * 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)
  38862. * @returns the VertexData of the ellipsoid
  38863. */
  38864. VertexData.CreateSphere = function (options) {
  38865. var segments = options.segments || 32;
  38866. var diameterX = options.diameterX || options.diameter || 1;
  38867. var diameterY = options.diameterY || options.diameter || 1;
  38868. var diameterZ = options.diameterZ || options.diameter || 1;
  38869. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38870. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38871. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38872. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38873. var totalZRotationSteps = 2 + segments;
  38874. var totalYRotationSteps = 2 * totalZRotationSteps;
  38875. var indices = [];
  38876. var positions = [];
  38877. var normals = [];
  38878. var uvs = [];
  38879. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38880. var normalizedZ = zRotationStep / totalZRotationSteps;
  38881. var angleZ = normalizedZ * Math.PI * slice;
  38882. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38883. var normalizedY = yRotationStep / totalYRotationSteps;
  38884. var angleY = normalizedY * Math.PI * 2 * arc;
  38885. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38886. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38887. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38888. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38889. var vertex = complete.multiply(radius);
  38890. var normal = complete.divide(radius).normalize();
  38891. positions.push(vertex.x, vertex.y, vertex.z);
  38892. normals.push(normal.x, normal.y, normal.z);
  38893. uvs.push(normalizedY, normalizedZ);
  38894. }
  38895. if (zRotationStep > 0) {
  38896. var verticesCount = positions.length / 3;
  38897. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38898. indices.push((firstIndex));
  38899. indices.push((firstIndex + 1));
  38900. indices.push(firstIndex + totalYRotationSteps + 1);
  38901. indices.push((firstIndex + totalYRotationSteps + 1));
  38902. indices.push((firstIndex + 1));
  38903. indices.push((firstIndex + totalYRotationSteps + 2));
  38904. }
  38905. }
  38906. }
  38907. // Sides
  38908. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38909. // Result
  38910. var vertexData = new VertexData();
  38911. vertexData.indices = indices;
  38912. vertexData.positions = positions;
  38913. vertexData.normals = normals;
  38914. vertexData.uvs = uvs;
  38915. return vertexData;
  38916. };
  38917. /**
  38918. * Creates the VertexData for a cylinder, cone or prism
  38919. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38920. * * height sets the height (y direction) of the cylinder, optional, default 2
  38921. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38922. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38923. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38924. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38925. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38926. * * 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
  38927. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38928. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38929. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38930. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38931. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38932. * * 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)
  38933. * * 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)
  38934. * @returns the VertexData of the cylinder, cone or prism
  38935. */
  38936. VertexData.CreateCylinder = function (options) {
  38937. var height = options.height || 2;
  38938. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38939. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38940. var tessellation = options.tessellation || 24;
  38941. var subdivisions = options.subdivisions || 1;
  38942. var hasRings = options.hasRings ? true : false;
  38943. var enclose = options.enclose ? true : false;
  38944. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38945. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38946. var faceUV = options.faceUV || new Array(3);
  38947. var faceColors = options.faceColors;
  38948. // default face colors and UV if undefined
  38949. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38950. var ringNb = (hasRings) ? subdivisions : 1;
  38951. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38952. var f;
  38953. for (f = 0; f < surfaceNb; f++) {
  38954. if (faceColors && faceColors[f] === undefined) {
  38955. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38956. }
  38957. }
  38958. for (f = 0; f < surfaceNb; f++) {
  38959. if (faceUV && faceUV[f] === undefined) {
  38960. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38961. }
  38962. }
  38963. var indices = new Array();
  38964. var positions = new Array();
  38965. var normals = new Array();
  38966. var uvs = new Array();
  38967. var colors = new Array();
  38968. var angle_step = Math.PI * 2 * arc / tessellation;
  38969. var angle;
  38970. var h;
  38971. var radius;
  38972. var tan = (diameterBottom - diameterTop) / 2 / height;
  38973. var ringVertex = BABYLON.Vector3.Zero();
  38974. var ringNormal = BABYLON.Vector3.Zero();
  38975. var ringFirstVertex = BABYLON.Vector3.Zero();
  38976. var ringFirstNormal = BABYLON.Vector3.Zero();
  38977. var quadNormal = BABYLON.Vector3.Zero();
  38978. var Y = BABYLON.Axis.Y;
  38979. // positions, normals, uvs
  38980. var i;
  38981. var j;
  38982. var r;
  38983. var ringIdx = 1;
  38984. var s = 1; // surface index
  38985. var cs = 0;
  38986. var v = 0;
  38987. for (i = 0; i <= subdivisions; i++) {
  38988. h = i / subdivisions;
  38989. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38990. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38991. for (r = 0; r < ringIdx; r++) {
  38992. if (hasRings) {
  38993. s += r;
  38994. }
  38995. if (enclose) {
  38996. s += 2 * r;
  38997. }
  38998. for (j = 0; j <= tessellation; j++) {
  38999. angle = j * angle_step;
  39000. // position
  39001. ringVertex.x = Math.cos(-angle) * radius;
  39002. ringVertex.y = -height / 2 + h * height;
  39003. ringVertex.z = Math.sin(-angle) * radius;
  39004. // normal
  39005. if (diameterTop === 0 && i === subdivisions) {
  39006. // if no top cap, reuse former normals
  39007. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  39008. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  39009. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  39010. }
  39011. else {
  39012. ringNormal.x = ringVertex.x;
  39013. ringNormal.z = ringVertex.z;
  39014. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  39015. ringNormal.normalize();
  39016. }
  39017. // keep first ring vertex values for enclose
  39018. if (j === 0) {
  39019. ringFirstVertex.copyFrom(ringVertex);
  39020. ringFirstNormal.copyFrom(ringNormal);
  39021. }
  39022. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39023. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  39024. if (hasRings) {
  39025. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  39026. }
  39027. else {
  39028. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  39029. }
  39030. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  39031. if (faceColors) {
  39032. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  39033. }
  39034. }
  39035. // if enclose, add four vertices and their dedicated normals
  39036. if (arc !== 1 && enclose) {
  39037. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39038. positions.push(0, ringVertex.y, 0);
  39039. positions.push(0, ringVertex.y, 0);
  39040. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  39041. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  39042. quadNormal.normalize();
  39043. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39044. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  39045. quadNormal.normalize();
  39046. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39047. if (hasRings) {
  39048. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  39049. }
  39050. else {
  39051. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  39052. }
  39053. uvs.push(faceUV[s + 1].x, v);
  39054. uvs.push(faceUV[s + 1].z, v);
  39055. if (hasRings) {
  39056. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  39057. }
  39058. else {
  39059. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  39060. }
  39061. uvs.push(faceUV[s + 2].x, v);
  39062. uvs.push(faceUV[s + 2].z, v);
  39063. if (faceColors) {
  39064. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39065. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39066. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39067. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39068. }
  39069. }
  39070. if (cs !== s) {
  39071. cs = s;
  39072. }
  39073. }
  39074. }
  39075. // indices
  39076. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  39077. var s;
  39078. i = 0;
  39079. for (s = 0; s < subdivisions; s++) {
  39080. var i0 = 0;
  39081. var i1 = 0;
  39082. var i2 = 0;
  39083. var i3 = 0;
  39084. for (j = 0; j < tessellation; j++) {
  39085. i0 = i * (e + 1) + j;
  39086. i1 = (i + 1) * (e + 1) + j;
  39087. i2 = i * (e + 1) + (j + 1);
  39088. i3 = (i + 1) * (e + 1) + (j + 1);
  39089. indices.push(i0, i1, i2);
  39090. indices.push(i3, i2, i1);
  39091. }
  39092. if (arc !== 1 && enclose) { // if enclose, add two quads
  39093. indices.push(i0 + 2, i1 + 2, i2 + 2);
  39094. indices.push(i3 + 2, i2 + 2, i1 + 2);
  39095. indices.push(i0 + 4, i1 + 4, i2 + 4);
  39096. indices.push(i3 + 4, i2 + 4, i1 + 4);
  39097. }
  39098. i = (hasRings) ? (i + 2) : (i + 1);
  39099. }
  39100. // Caps
  39101. var createCylinderCap = function (isTop) {
  39102. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  39103. if (radius === 0) {
  39104. return;
  39105. }
  39106. // Cap positions, normals & uvs
  39107. var angle;
  39108. var circleVector;
  39109. var i;
  39110. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  39111. var c = null;
  39112. if (faceColors) {
  39113. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  39114. }
  39115. // cap center
  39116. var vbase = positions.length / 3;
  39117. var offset = isTop ? height / 2 : -height / 2;
  39118. var center = new BABYLON.Vector3(0, offset, 0);
  39119. positions.push(center.x, center.y, center.z);
  39120. normals.push(0, isTop ? 1 : -1, 0);
  39121. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39122. if (c) {
  39123. colors.push(c.r, c.g, c.b, c.a);
  39124. }
  39125. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39126. for (i = 0; i <= tessellation; i++) {
  39127. angle = Math.PI * 2 * i * arc / tessellation;
  39128. var cos = Math.cos(-angle);
  39129. var sin = Math.sin(-angle);
  39130. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39131. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39132. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39133. normals.push(0, isTop ? 1 : -1, 0);
  39134. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39135. if (c) {
  39136. colors.push(c.r, c.g, c.b, c.a);
  39137. }
  39138. }
  39139. // Cap indices
  39140. for (i = 0; i < tessellation; i++) {
  39141. if (!isTop) {
  39142. indices.push(vbase);
  39143. indices.push(vbase + (i + 1));
  39144. indices.push(vbase + (i + 2));
  39145. }
  39146. else {
  39147. indices.push(vbase);
  39148. indices.push(vbase + (i + 2));
  39149. indices.push(vbase + (i + 1));
  39150. }
  39151. }
  39152. };
  39153. // add caps to geometry
  39154. createCylinderCap(false);
  39155. createCylinderCap(true);
  39156. // Sides
  39157. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39158. var vertexData = new VertexData();
  39159. vertexData.indices = indices;
  39160. vertexData.positions = positions;
  39161. vertexData.normals = normals;
  39162. vertexData.uvs = uvs;
  39163. if (faceColors) {
  39164. vertexData.colors = colors;
  39165. }
  39166. return vertexData;
  39167. };
  39168. /**
  39169. * Creates the VertexData for a torus
  39170. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39171. * * diameter the diameter of the torus, optional default 1
  39172. * * thickness the diameter of the tube forming the torus, optional default 0.5
  39173. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39174. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39175. * * 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)
  39176. * * 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)
  39177. * @returns the VertexData of the torus
  39178. */
  39179. VertexData.CreateTorus = function (options) {
  39180. var indices = [];
  39181. var positions = [];
  39182. var normals = [];
  39183. var uvs = [];
  39184. var diameter = options.diameter || 1;
  39185. var thickness = options.thickness || 0.5;
  39186. var tessellation = options.tessellation || 16;
  39187. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39188. var stride = tessellation + 1;
  39189. for (var i = 0; i <= tessellation; i++) {
  39190. var u = i / tessellation;
  39191. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39192. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39193. for (var j = 0; j <= tessellation; j++) {
  39194. var v = 1 - j / tessellation;
  39195. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39196. var dx = Math.cos(innerAngle);
  39197. var dy = Math.sin(innerAngle);
  39198. // Create a vertex.
  39199. var normal = new BABYLON.Vector3(dx, dy, 0);
  39200. var position = normal.scale(thickness / 2);
  39201. var textureCoordinate = new BABYLON.Vector2(u, v);
  39202. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39203. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39204. positions.push(position.x, position.y, position.z);
  39205. normals.push(normal.x, normal.y, normal.z);
  39206. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39207. // And create indices for two triangles.
  39208. var nextI = (i + 1) % stride;
  39209. var nextJ = (j + 1) % stride;
  39210. indices.push(i * stride + j);
  39211. indices.push(i * stride + nextJ);
  39212. indices.push(nextI * stride + j);
  39213. indices.push(i * stride + nextJ);
  39214. indices.push(nextI * stride + nextJ);
  39215. indices.push(nextI * stride + j);
  39216. }
  39217. }
  39218. // Sides
  39219. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39220. // Result
  39221. var vertexData = new VertexData();
  39222. vertexData.indices = indices;
  39223. vertexData.positions = positions;
  39224. vertexData.normals = normals;
  39225. vertexData.uvs = uvs;
  39226. return vertexData;
  39227. };
  39228. /**
  39229. * Creates the VertexData of the LineSystem
  39230. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  39231. * - lines an array of lines, each line being an array of successive Vector3
  39232. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  39233. * @returns the VertexData of the LineSystem
  39234. */
  39235. VertexData.CreateLineSystem = function (options) {
  39236. var indices = [];
  39237. var positions = [];
  39238. var lines = options.lines;
  39239. var colors = options.colors;
  39240. var vertexColors = [];
  39241. var idx = 0;
  39242. for (var l = 0; l < lines.length; l++) {
  39243. var points = lines[l];
  39244. for (var index = 0; index < points.length; index++) {
  39245. positions.push(points[index].x, points[index].y, points[index].z);
  39246. if (colors) {
  39247. var color = colors[l];
  39248. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  39249. }
  39250. if (index > 0) {
  39251. indices.push(idx - 1);
  39252. indices.push(idx);
  39253. }
  39254. idx++;
  39255. }
  39256. }
  39257. var vertexData = new VertexData();
  39258. vertexData.indices = indices;
  39259. vertexData.positions = positions;
  39260. if (colors) {
  39261. vertexData.colors = vertexColors;
  39262. }
  39263. return vertexData;
  39264. };
  39265. /**
  39266. * Create the VertexData for a DashedLines
  39267. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  39268. * - points an array successive Vector3
  39269. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  39270. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  39271. * - dashNb the intended total number of dashes, optional, default 200
  39272. * @returns the VertexData for the DashedLines
  39273. */
  39274. VertexData.CreateDashedLines = function (options) {
  39275. var dashSize = options.dashSize || 3;
  39276. var gapSize = options.gapSize || 1;
  39277. var dashNb = options.dashNb || 200;
  39278. var points = options.points;
  39279. var positions = new Array();
  39280. var indices = new Array();
  39281. var curvect = BABYLON.Vector3.Zero();
  39282. var lg = 0;
  39283. var nb = 0;
  39284. var shft = 0;
  39285. var dashshft = 0;
  39286. var curshft = 0;
  39287. var idx = 0;
  39288. var i = 0;
  39289. for (i = 0; i < points.length - 1; i++) {
  39290. points[i + 1].subtractToRef(points[i], curvect);
  39291. lg += curvect.length();
  39292. }
  39293. shft = lg / dashNb;
  39294. dashshft = dashSize * shft / (dashSize + gapSize);
  39295. for (i = 0; i < points.length - 1; i++) {
  39296. points[i + 1].subtractToRef(points[i], curvect);
  39297. nb = Math.floor(curvect.length() / shft);
  39298. curvect.normalize();
  39299. for (var j = 0; j < nb; j++) {
  39300. curshft = shft * j;
  39301. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39302. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39303. indices.push(idx, idx + 1);
  39304. idx += 2;
  39305. }
  39306. }
  39307. // Result
  39308. var vertexData = new VertexData();
  39309. vertexData.positions = positions;
  39310. vertexData.indices = indices;
  39311. return vertexData;
  39312. };
  39313. /**
  39314. * Creates the VertexData for a Ground
  39315. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39316. * - width the width (x direction) of the ground, optional, default 1
  39317. * - height the height (z direction) of the ground, optional, default 1
  39318. * - subdivisions the number of subdivisions per side, optional, default 1
  39319. * @returns the VertexData of the Ground
  39320. */
  39321. VertexData.CreateGround = function (options) {
  39322. var indices = [];
  39323. var positions = [];
  39324. var normals = [];
  39325. var uvs = [];
  39326. var row, col;
  39327. var width = options.width || 1;
  39328. var height = options.height || 1;
  39329. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39330. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39331. for (row = 0; row <= subdivisionsY; row++) {
  39332. for (col = 0; col <= subdivisionsX; col++) {
  39333. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39334. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39335. positions.push(position.x, position.y, position.z);
  39336. normals.push(normal.x, normal.y, normal.z);
  39337. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39338. }
  39339. }
  39340. for (row = 0; row < subdivisionsY; row++) {
  39341. for (col = 0; col < subdivisionsX; col++) {
  39342. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39343. indices.push(col + 1 + row * (subdivisionsX + 1));
  39344. indices.push(col + row * (subdivisionsX + 1));
  39345. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39346. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39347. indices.push(col + row * (subdivisionsX + 1));
  39348. }
  39349. }
  39350. // Result
  39351. var vertexData = new VertexData();
  39352. vertexData.indices = indices;
  39353. vertexData.positions = positions;
  39354. vertexData.normals = normals;
  39355. vertexData.uvs = uvs;
  39356. return vertexData;
  39357. };
  39358. /**
  39359. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39360. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39361. * * xmin the ground minimum X coordinate, optional, default -1
  39362. * * zmin the ground minimum Z coordinate, optional, default -1
  39363. * * xmax the ground maximum X coordinate, optional, default 1
  39364. * * zmax the ground maximum Z coordinate, optional, default 1
  39365. * * 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}
  39366. * * 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}
  39367. * @returns the VertexData of the TiledGround
  39368. */
  39369. VertexData.CreateTiledGround = function (options) {
  39370. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39371. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39372. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39373. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39374. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39375. var precision = options.precision || { w: 1, h: 1 };
  39376. var indices = new Array();
  39377. var positions = new Array();
  39378. var normals = new Array();
  39379. var uvs = new Array();
  39380. var row, col, tileRow, tileCol;
  39381. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39382. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39383. precision.w = (precision.w < 1) ? 1 : precision.w;
  39384. precision.h = (precision.h < 1) ? 1 : precision.h;
  39385. var tileSize = {
  39386. 'w': (xmax - xmin) / subdivisions.w,
  39387. 'h': (zmax - zmin) / subdivisions.h
  39388. };
  39389. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39390. // Indices
  39391. var base = positions.length / 3;
  39392. var rowLength = precision.w + 1;
  39393. for (row = 0; row < precision.h; row++) {
  39394. for (col = 0; col < precision.w; col++) {
  39395. var square = [
  39396. base + col + row * rowLength,
  39397. base + (col + 1) + row * rowLength,
  39398. base + (col + 1) + (row + 1) * rowLength,
  39399. base + col + (row + 1) * rowLength
  39400. ];
  39401. indices.push(square[1]);
  39402. indices.push(square[2]);
  39403. indices.push(square[3]);
  39404. indices.push(square[0]);
  39405. indices.push(square[1]);
  39406. indices.push(square[3]);
  39407. }
  39408. }
  39409. // Position, normals and uvs
  39410. var position = BABYLON.Vector3.Zero();
  39411. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39412. for (row = 0; row <= precision.h; row++) {
  39413. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39414. for (col = 0; col <= precision.w; col++) {
  39415. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39416. position.y = 0;
  39417. positions.push(position.x, position.y, position.z);
  39418. normals.push(normal.x, normal.y, normal.z);
  39419. uvs.push(col / precision.w, row / precision.h);
  39420. }
  39421. }
  39422. }
  39423. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39424. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39425. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39426. }
  39427. }
  39428. // Result
  39429. var vertexData = new VertexData();
  39430. vertexData.indices = indices;
  39431. vertexData.positions = positions;
  39432. vertexData.normals = normals;
  39433. vertexData.uvs = uvs;
  39434. return vertexData;
  39435. };
  39436. /**
  39437. * Creates the VertexData of the Ground designed from a heightmap
  39438. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39439. * * width the width (x direction) of the ground
  39440. * * height the height (z direction) of the ground
  39441. * * subdivisions the number of subdivisions per side
  39442. * * minHeight the minimum altitude on the ground, optional, default 0
  39443. * * maxHeight the maximum altitude on the ground, optional default 1
  39444. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39445. * * buffer the array holding the image color data
  39446. * * bufferWidth the width of image
  39447. * * bufferHeight the height of image
  39448. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39449. * @returns the VertexData of the Ground designed from a heightmap
  39450. */
  39451. VertexData.CreateGroundFromHeightMap = function (options) {
  39452. var indices = [];
  39453. var positions = [];
  39454. var normals = [];
  39455. var uvs = [];
  39456. var row, col;
  39457. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39458. var alphaFilter = options.alphaFilter || 0.0;
  39459. // Vertices
  39460. for (row = 0; row <= options.subdivisions; row++) {
  39461. for (col = 0; col <= options.subdivisions; col++) {
  39462. 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));
  39463. // Compute height
  39464. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39465. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39466. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39467. var r = options.buffer[pos] / 255.0;
  39468. var g = options.buffer[pos + 1] / 255.0;
  39469. var b = options.buffer[pos + 2] / 255.0;
  39470. var a = options.buffer[pos + 3] / 255.0;
  39471. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39472. // If our alpha channel is not within our filter then we will assign a 'special' height
  39473. // Then when building the indices, we will ignore any vertex that is using the special height
  39474. if (a >= alphaFilter) {
  39475. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39476. }
  39477. else {
  39478. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39479. }
  39480. // Add vertex
  39481. positions.push(position.x, position.y, position.z);
  39482. normals.push(0, 0, 0);
  39483. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39484. }
  39485. }
  39486. // Indices
  39487. for (row = 0; row < options.subdivisions; row++) {
  39488. for (col = 0; col < options.subdivisions; col++) {
  39489. // Calculate Indices
  39490. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39491. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39492. var idx3 = (col + row * (options.subdivisions + 1));
  39493. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39494. // Check that all indices are visible (based on our special height)
  39495. // Only display the vertex if all Indices are visible
  39496. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39497. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39498. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39499. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39500. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39501. indices.push(idx1);
  39502. indices.push(idx2);
  39503. indices.push(idx3);
  39504. }
  39505. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39506. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39507. indices.push(idx4);
  39508. indices.push(idx1);
  39509. indices.push(idx3);
  39510. }
  39511. }
  39512. }
  39513. // Normals
  39514. VertexData.ComputeNormals(positions, indices, normals);
  39515. // Result
  39516. var vertexData = new VertexData();
  39517. vertexData.indices = indices;
  39518. vertexData.positions = positions;
  39519. vertexData.normals = normals;
  39520. vertexData.uvs = uvs;
  39521. return vertexData;
  39522. };
  39523. /**
  39524. * Creates the VertexData for a Plane
  39525. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39526. * * size sets the width and height of the plane to the value of size, optional default 1
  39527. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39528. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39529. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39530. * * 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)
  39531. * * 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)
  39532. * @returns the VertexData of the box
  39533. */
  39534. VertexData.CreatePlane = function (options) {
  39535. var indices = [];
  39536. var positions = [];
  39537. var normals = [];
  39538. var uvs = [];
  39539. var width = options.width || options.size || 1;
  39540. var height = options.height || options.size || 1;
  39541. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39542. // Vertices
  39543. var halfWidth = width / 2.0;
  39544. var halfHeight = height / 2.0;
  39545. positions.push(-halfWidth, -halfHeight, 0);
  39546. normals.push(0, 0, -1.0);
  39547. uvs.push(0.0, 0.0);
  39548. positions.push(halfWidth, -halfHeight, 0);
  39549. normals.push(0, 0, -1.0);
  39550. uvs.push(1.0, 0.0);
  39551. positions.push(halfWidth, halfHeight, 0);
  39552. normals.push(0, 0, -1.0);
  39553. uvs.push(1.0, 1.0);
  39554. positions.push(-halfWidth, halfHeight, 0);
  39555. normals.push(0, 0, -1.0);
  39556. uvs.push(0.0, 1.0);
  39557. // Indices
  39558. indices.push(0);
  39559. indices.push(1);
  39560. indices.push(2);
  39561. indices.push(0);
  39562. indices.push(2);
  39563. indices.push(3);
  39564. // Sides
  39565. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39566. // Result
  39567. var vertexData = new VertexData();
  39568. vertexData.indices = indices;
  39569. vertexData.positions = positions;
  39570. vertexData.normals = normals;
  39571. vertexData.uvs = uvs;
  39572. return vertexData;
  39573. };
  39574. /**
  39575. * Creates the VertexData of the Disc or regular Polygon
  39576. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39577. * * radius the radius of the disc, optional default 0.5
  39578. * * tessellation the number of polygon sides, optional, default 64
  39579. * * 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
  39580. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39581. * * 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)
  39582. * * 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)
  39583. * @returns the VertexData of the box
  39584. */
  39585. VertexData.CreateDisc = function (options) {
  39586. var positions = new Array();
  39587. var indices = new Array();
  39588. var normals = new Array();
  39589. var uvs = new Array();
  39590. var radius = options.radius || 0.5;
  39591. var tessellation = options.tessellation || 64;
  39592. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39593. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39594. // positions and uvs
  39595. positions.push(0, 0, 0); // disc center first
  39596. uvs.push(0.5, 0.5);
  39597. var theta = Math.PI * 2 * arc;
  39598. var step = theta / tessellation;
  39599. for (var a = 0; a < theta; a += step) {
  39600. var x = Math.cos(a);
  39601. var y = Math.sin(a);
  39602. var u = (x + 1) / 2;
  39603. var v = (1 - y) / 2;
  39604. positions.push(radius * x, radius * y, 0);
  39605. uvs.push(u, v);
  39606. }
  39607. if (arc === 1) {
  39608. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39609. uvs.push(uvs[2], uvs[3]);
  39610. }
  39611. //indices
  39612. var vertexNb = positions.length / 3;
  39613. for (var i = 1; i < vertexNb - 1; i++) {
  39614. indices.push(i + 1, 0, i);
  39615. }
  39616. // result
  39617. VertexData.ComputeNormals(positions, indices, normals);
  39618. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39619. var vertexData = new VertexData();
  39620. vertexData.indices = indices;
  39621. vertexData.positions = positions;
  39622. vertexData.normals = normals;
  39623. vertexData.uvs = uvs;
  39624. return vertexData;
  39625. };
  39626. /**
  39627. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39628. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39629. * @param polygon a mesh built from polygonTriangulation.build()
  39630. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39631. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39632. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39633. * @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)
  39634. * @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)
  39635. * @returns the VertexData of the Polygon
  39636. */
  39637. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39638. var faceUV = fUV || new Array(3);
  39639. var faceColors = fColors;
  39640. var colors = [];
  39641. // default face colors and UV if undefined
  39642. for (var f = 0; f < 3; f++) {
  39643. if (faceUV[f] === undefined) {
  39644. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39645. }
  39646. if (faceColors && faceColors[f] === undefined) {
  39647. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39648. }
  39649. }
  39650. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39651. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39652. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39653. var indices = polygon.getIndices();
  39654. // set face colours and textures
  39655. var idx = 0;
  39656. var face = 0;
  39657. for (var index = 0; index < normals.length; index += 3) {
  39658. //Edge Face no. 1
  39659. if (Math.abs(normals[index + 1]) < 0.001) {
  39660. face = 1;
  39661. }
  39662. //Top Face no. 0
  39663. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39664. face = 0;
  39665. }
  39666. //Bottom Face no. 2
  39667. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39668. face = 2;
  39669. }
  39670. idx = index / 3;
  39671. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39672. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39673. if (faceColors) {
  39674. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39675. }
  39676. }
  39677. // sides
  39678. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39679. // Result
  39680. var vertexData = new VertexData();
  39681. vertexData.indices = indices;
  39682. vertexData.positions = positions;
  39683. vertexData.normals = normals;
  39684. vertexData.uvs = uvs;
  39685. if (faceColors) {
  39686. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39687. vertexData.colors = totalColors;
  39688. }
  39689. return vertexData;
  39690. };
  39691. /**
  39692. * Creates the VertexData of the IcoSphere
  39693. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39694. * * radius the radius of the IcoSphere, optional default 1
  39695. * * radiusX allows stretching in the x direction, optional, default radius
  39696. * * radiusY allows stretching in the y direction, optional, default radius
  39697. * * radiusZ allows stretching in the z direction, optional, default radius
  39698. * * flat when true creates a flat shaded mesh, optional, default true
  39699. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39700. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39701. * * 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)
  39702. * * 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)
  39703. * @returns the VertexData of the IcoSphere
  39704. */
  39705. VertexData.CreateIcoSphere = function (options) {
  39706. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39707. var radius = options.radius || 1;
  39708. var flat = (options.flat === undefined) ? true : options.flat;
  39709. var subdivisions = options.subdivisions || 4;
  39710. var radiusX = options.radiusX || radius;
  39711. var radiusY = options.radiusY || radius;
  39712. var radiusZ = options.radiusZ || radius;
  39713. var t = (1 + Math.sqrt(5)) / 2;
  39714. // 12 vertex x,y,z
  39715. var ico_vertices = [
  39716. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39717. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39718. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39719. ];
  39720. // index of 3 vertex makes a face of icopshere
  39721. var ico_indices = [
  39722. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39723. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39724. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39725. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39726. ];
  39727. // vertex for uv have aliased position, not for UV
  39728. var vertices_unalias_id = [
  39729. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39730. // vertex alias
  39731. 0,
  39732. 2,
  39733. 3,
  39734. 3,
  39735. 3,
  39736. 4,
  39737. 7,
  39738. 8,
  39739. 9,
  39740. 9,
  39741. 10,
  39742. 11 // 23: B + 12
  39743. ];
  39744. // uv as integer step (not pixels !)
  39745. var ico_vertexuv = [
  39746. 5, 1, 3, 1, 6, 4, 0, 0,
  39747. 5, 3, 4, 2, 2, 2, 4, 0,
  39748. 2, 0, 1, 1, 6, 0, 6, 2,
  39749. // vertex alias (for same vertex on different faces)
  39750. 0, 4,
  39751. 3, 3,
  39752. 4, 4,
  39753. 3, 1,
  39754. 4, 2,
  39755. 4, 4,
  39756. 0, 2,
  39757. 1, 1,
  39758. 2, 2,
  39759. 3, 3,
  39760. 1, 3,
  39761. 2, 4 // 23: B + 12
  39762. ];
  39763. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39764. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39765. // First island of uv mapping
  39766. // v = 4h 3+ 2
  39767. // v = 3h 9+ 4
  39768. // v = 2h 9+ 5 B
  39769. // v = 1h 9 1 0
  39770. // v = 0h 3 8 7 A
  39771. // u = 0 1 2 3 4 5 6 *a
  39772. // Second island of uv mapping
  39773. // v = 4h 0+ B+ 4+
  39774. // v = 3h A+ 2+
  39775. // v = 2h 7+ 6 3+
  39776. // v = 1h 8+ 3+
  39777. // v = 0h
  39778. // u = 0 1 2 3 4 5 6 *a
  39779. // Face layout on texture UV mapping
  39780. // ============
  39781. // \ 4 /\ 16 / ======
  39782. // \ / \ / /\ 11 /
  39783. // \/ 7 \/ / \ /
  39784. // ======= / 10 \/
  39785. // /\ 17 /\ =======
  39786. // / \ / \ \ 15 /\
  39787. // / 8 \/ 12 \ \ / \
  39788. // ============ \/ 6 \
  39789. // \ 18 /\ ============
  39790. // \ / \ \ 5 /\ 0 /
  39791. // \/ 13 \ \ / \ /
  39792. // ======= \/ 1 \/
  39793. // =============
  39794. // /\ 19 /\ 2 /\
  39795. // / \ / \ / \
  39796. // / 14 \/ 9 \/ 3 \
  39797. // ===================
  39798. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39799. var ustep = 138 / 1024;
  39800. var vstep = 239 / 1024;
  39801. var uoffset = 60 / 1024;
  39802. var voffset = 26 / 1024;
  39803. // Second island should have margin, not to touch the first island
  39804. // avoid any borderline artefact in pixel rounding
  39805. var island_u_offset = -40 / 1024;
  39806. var island_v_offset = +20 / 1024;
  39807. // face is either island 0 or 1 :
  39808. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39809. var island = [
  39810. 0, 0, 0, 0, 1,
  39811. 0, 0, 1, 1, 0,
  39812. 0, 0, 1, 1, 0,
  39813. 0, 1, 1, 1, 0 // 15 - 19
  39814. ];
  39815. var indices = new Array();
  39816. var positions = new Array();
  39817. var normals = new Array();
  39818. var uvs = new Array();
  39819. var current_indice = 0;
  39820. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39821. var face_vertex_pos = new Array(3);
  39822. var face_vertex_uv = new Array(3);
  39823. var v012;
  39824. for (v012 = 0; v012 < 3; v012++) {
  39825. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39826. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39827. }
  39828. // create all with normals
  39829. for (var face = 0; face < 20; face++) {
  39830. // 3 vertex per face
  39831. for (v012 = 0; v012 < 3; v012++) {
  39832. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39833. var v_id = ico_indices[3 * face + v012];
  39834. // vertex have 3D position (x,y,z)
  39835. 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]);
  39836. // Normalize to get normal, then scale to radius
  39837. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39838. // uv Coordinates from vertex ID
  39839. 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);
  39840. }
  39841. // Subdivide the face (interpolate pos, norm, uv)
  39842. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39843. // - norm is linear interpolation of vertex corner normal
  39844. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39845. // - uv is linear interpolation
  39846. //
  39847. // Topology is as below for sub-divide by 2
  39848. // vertex shown as v0,v1,v2
  39849. // interp index is i1 to progress in range [v0,v1[
  39850. // interp index is i2 to progress in range [v0,v2[
  39851. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39852. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39853. //
  39854. //
  39855. // i2 v2
  39856. // ^ ^
  39857. // / / \
  39858. // / / \
  39859. // / / \
  39860. // / / (0,1) \
  39861. // / #---------\
  39862. // / / \ (0,0)'/ \
  39863. // / / \ / \
  39864. // / / \ / \
  39865. // / / (0,0) \ / (1,0) \
  39866. // / #---------#---------\
  39867. // v0 v1
  39868. //
  39869. // --------------------> i1
  39870. //
  39871. // interp of (i1,i2):
  39872. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39873. // along i1 : lerp(x0,x1, i1/(S-i2))
  39874. //
  39875. // centroid of triangle is needed to get help normal computation
  39876. // (c1,c2) are used for centroid location
  39877. var interp_vertex = function (i1, i2, c1, c2) {
  39878. // vertex is interpolated from
  39879. // - face_vertex_pos[0..2]
  39880. // - face_vertex_uv[0..2]
  39881. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39882. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39883. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39884. pos_interp.normalize();
  39885. var vertex_normal;
  39886. if (flat) {
  39887. // in flat mode, recalculate normal as face centroid normal
  39888. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39889. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39890. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39891. }
  39892. else {
  39893. // in smooth mode, recalculate normal from each single vertex position
  39894. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39895. }
  39896. // Vertex normal need correction due to X,Y,Z radius scaling
  39897. vertex_normal.x /= radiusX;
  39898. vertex_normal.y /= radiusY;
  39899. vertex_normal.z /= radiusZ;
  39900. vertex_normal.normalize();
  39901. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39902. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39903. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39904. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39905. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39906. uvs.push(uv_interp.x, uv_interp.y);
  39907. // push each vertex has member of a face
  39908. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39909. indices.push(current_indice);
  39910. current_indice++;
  39911. };
  39912. for (var i2 = 0; i2 < subdivisions; i2++) {
  39913. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39914. // face : (i1,i2) for /\ :
  39915. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39916. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39917. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39918. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39919. if (i1 + i2 + 1 < subdivisions) {
  39920. // face : (i1,i2)' for \/ :
  39921. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39922. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39923. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39924. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39925. }
  39926. }
  39927. }
  39928. }
  39929. // Sides
  39930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39931. // Result
  39932. var vertexData = new VertexData();
  39933. vertexData.indices = indices;
  39934. vertexData.positions = positions;
  39935. vertexData.normals = normals;
  39936. vertexData.uvs = uvs;
  39937. return vertexData;
  39938. };
  39939. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39940. /**
  39941. * Creates the VertexData for a Polyhedron
  39942. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39943. * * type provided types are:
  39944. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39945. * * 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)
  39946. * * size the size of the IcoSphere, optional default 1
  39947. * * sizeX allows stretching in the x direction, optional, default size
  39948. * * sizeY allows stretching in the y direction, optional, default size
  39949. * * sizeZ allows stretching in the z direction, optional, default size
  39950. * * 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
  39951. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39952. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39953. * * flat when true creates a flat shaded mesh, optional, default true
  39954. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39955. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39956. * * 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)
  39957. * * 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)
  39958. * @returns the VertexData of the Polyhedron
  39959. */
  39960. VertexData.CreatePolyhedron = function (options) {
  39961. // provided polyhedron types :
  39962. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39963. // 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)
  39964. var polyhedra = [];
  39965. 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]] };
  39966. 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]] };
  39967. polyhedra[2] = {
  39968. 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]],
  39969. 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]]
  39970. };
  39971. polyhedra[3] = {
  39972. 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]],
  39973. 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]]
  39974. };
  39975. polyhedra[4] = {
  39976. 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]],
  39977. 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]]
  39978. };
  39979. 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]] };
  39980. 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]] };
  39981. 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]] };
  39982. 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]] };
  39983. 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]] };
  39984. 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]] };
  39985. 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]] };
  39986. 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]] };
  39987. 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]] };
  39988. polyhedra[14] = {
  39989. 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]],
  39990. 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]]
  39991. };
  39992. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39993. var size = options.size;
  39994. var sizeX = options.sizeX || size || 1;
  39995. var sizeY = options.sizeY || size || 1;
  39996. var sizeZ = options.sizeZ || size || 1;
  39997. var data = options.custom || polyhedra[type];
  39998. var nbfaces = data.face.length;
  39999. var faceUV = options.faceUV || new Array(nbfaces);
  40000. var faceColors = options.faceColors;
  40001. var flat = (options.flat === undefined) ? true : options.flat;
  40002. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40003. var positions = new Array();
  40004. var indices = new Array();
  40005. var normals = new Array();
  40006. var uvs = new Array();
  40007. var colors = new Array();
  40008. var index = 0;
  40009. var faceIdx = 0; // face cursor in the array "indexes"
  40010. var indexes = new Array();
  40011. var i = 0;
  40012. var f = 0;
  40013. var u, v, ang, x, y, tmp;
  40014. // default face colors and UV if undefined
  40015. if (flat) {
  40016. for (f = 0; f < nbfaces; f++) {
  40017. if (faceColors && faceColors[f] === undefined) {
  40018. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  40019. }
  40020. if (faceUV && faceUV[f] === undefined) {
  40021. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  40022. }
  40023. }
  40024. }
  40025. if (!flat) {
  40026. for (i = 0; i < data.vertex.length; i++) {
  40027. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  40028. uvs.push(0, 0);
  40029. }
  40030. for (f = 0; f < nbfaces; f++) {
  40031. for (i = 0; i < data.face[f].length - 2; i++) {
  40032. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  40033. }
  40034. }
  40035. }
  40036. else {
  40037. for (f = 0; f < nbfaces; f++) {
  40038. var fl = data.face[f].length; // number of vertices of the current face
  40039. ang = 2 * Math.PI / fl;
  40040. x = 0.5 * Math.tan(ang / 2);
  40041. y = 0.5;
  40042. // positions, uvs, colors
  40043. for (i = 0; i < fl; i++) {
  40044. // positions
  40045. 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);
  40046. indexes.push(index);
  40047. index++;
  40048. // uvs
  40049. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  40050. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  40051. uvs.push(u, v);
  40052. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  40053. y = x * Math.sin(ang) + y * Math.cos(ang);
  40054. x = tmp;
  40055. // colors
  40056. if (faceColors) {
  40057. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  40058. }
  40059. }
  40060. // indices from indexes
  40061. for (i = 0; i < fl - 2; i++) {
  40062. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  40063. }
  40064. faceIdx += fl;
  40065. }
  40066. }
  40067. VertexData.ComputeNormals(positions, indices, normals);
  40068. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40069. var vertexData = new VertexData();
  40070. vertexData.positions = positions;
  40071. vertexData.indices = indices;
  40072. vertexData.normals = normals;
  40073. vertexData.uvs = uvs;
  40074. if (faceColors && flat) {
  40075. vertexData.colors = colors;
  40076. }
  40077. return vertexData;
  40078. };
  40079. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  40080. /**
  40081. * Creates the VertexData for a TorusKnot
  40082. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  40083. * * radius the radius of the torus knot, optional, default 2
  40084. * * tube the thickness of the tube, optional, default 0.5
  40085. * * radialSegments the number of sides on each tube segments, optional, default 32
  40086. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  40087. * * p the number of windings around the z axis, optional, default 2
  40088. * * q the number of windings around the x axis, optional, default 3
  40089. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40090. * * 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)
  40091. * * 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)
  40092. * @returns the VertexData of the Torus Knot
  40093. */
  40094. VertexData.CreateTorusKnot = function (options) {
  40095. var indices = new Array();
  40096. var positions = new Array();
  40097. var normals = new Array();
  40098. var uvs = new Array();
  40099. var radius = options.radius || 2;
  40100. var tube = options.tube || 0.5;
  40101. var radialSegments = options.radialSegments || 32;
  40102. var tubularSegments = options.tubularSegments || 32;
  40103. var p = options.p || 2;
  40104. var q = options.q || 3;
  40105. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40106. // Helper
  40107. var getPos = function (angle) {
  40108. var cu = Math.cos(angle);
  40109. var su = Math.sin(angle);
  40110. var quOverP = q / p * angle;
  40111. var cs = Math.cos(quOverP);
  40112. var tx = radius * (2 + cs) * 0.5 * cu;
  40113. var ty = radius * (2 + cs) * su * 0.5;
  40114. var tz = radius * Math.sin(quOverP) * 0.5;
  40115. return new BABYLON.Vector3(tx, ty, tz);
  40116. };
  40117. // Vertices
  40118. var i;
  40119. var j;
  40120. for (i = 0; i <= radialSegments; i++) {
  40121. var modI = i % radialSegments;
  40122. var u = modI / radialSegments * 2 * p * Math.PI;
  40123. var p1 = getPos(u);
  40124. var p2 = getPos(u + 0.01);
  40125. var tang = p2.subtract(p1);
  40126. var n = p2.add(p1);
  40127. var bitan = BABYLON.Vector3.Cross(tang, n);
  40128. n = BABYLON.Vector3.Cross(bitan, tang);
  40129. bitan.normalize();
  40130. n.normalize();
  40131. for (j = 0; j < tubularSegments; j++) {
  40132. var modJ = j % tubularSegments;
  40133. var v = modJ / tubularSegments * 2 * Math.PI;
  40134. var cx = -tube * Math.cos(v);
  40135. var cy = tube * Math.sin(v);
  40136. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40137. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40138. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40139. uvs.push(i / radialSegments);
  40140. uvs.push(j / tubularSegments);
  40141. }
  40142. }
  40143. for (i = 0; i < radialSegments; i++) {
  40144. for (j = 0; j < tubularSegments; j++) {
  40145. var jNext = (j + 1) % tubularSegments;
  40146. var a = i * tubularSegments + j;
  40147. var b = (i + 1) * tubularSegments + j;
  40148. var c = (i + 1) * tubularSegments + jNext;
  40149. var d = i * tubularSegments + jNext;
  40150. indices.push(d);
  40151. indices.push(b);
  40152. indices.push(a);
  40153. indices.push(d);
  40154. indices.push(c);
  40155. indices.push(b);
  40156. }
  40157. }
  40158. // Normals
  40159. VertexData.ComputeNormals(positions, indices, normals);
  40160. // Sides
  40161. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40162. // Result
  40163. var vertexData = new VertexData();
  40164. vertexData.indices = indices;
  40165. vertexData.positions = positions;
  40166. vertexData.normals = normals;
  40167. vertexData.uvs = uvs;
  40168. return vertexData;
  40169. };
  40170. // Tools
  40171. /**
  40172. * Compute normals for given positions and indices
  40173. * @param positions an array of vertex positions, [...., x, y, z, ......]
  40174. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  40175. * @param normals an array of vertex normals, [...., x, y, z, ......]
  40176. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  40177. * * facetNormals : optional array of facet normals (vector3)
  40178. * * facetPositions : optional array of facet positions (vector3)
  40179. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40180. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40181. * * bInfo : optional bounding info, required for facetPartitioning computation
  40182. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  40183. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40184. * * useRightHandedSystem: optional boolean to for right handed system computation
  40185. * * depthSort : optional boolean to enable the facet depth sort computation
  40186. * * distanceTo : optional Vector3 to compute the facet depth from this location
  40187. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  40188. */
  40189. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40190. // temporary scalar variables
  40191. var index = 0; // facet index
  40192. var p1p2x = 0.0; // p1p2 vector x coordinate
  40193. var p1p2y = 0.0; // p1p2 vector y coordinate
  40194. var p1p2z = 0.0; // p1p2 vector z coordinate
  40195. var p3p2x = 0.0; // p3p2 vector x coordinate
  40196. var p3p2y = 0.0; // p3p2 vector y coordinate
  40197. var p3p2z = 0.0; // p3p2 vector z coordinate
  40198. var faceNormalx = 0.0; // facet normal x coordinate
  40199. var faceNormaly = 0.0; // facet normal y coordinate
  40200. var faceNormalz = 0.0; // facet normal z coordinate
  40201. var length = 0.0; // facet normal length before normalization
  40202. var v1x = 0; // vector1 x index in the positions array
  40203. var v1y = 0; // vector1 y index in the positions array
  40204. var v1z = 0; // vector1 z index in the positions array
  40205. var v2x = 0; // vector2 x index in the positions array
  40206. var v2y = 0; // vector2 y index in the positions array
  40207. var v2z = 0; // vector2 z index in the positions array
  40208. var v3x = 0; // vector3 x index in the positions array
  40209. var v3y = 0; // vector3 y index in the positions array
  40210. var v3z = 0; // vector3 z index in the positions array
  40211. var computeFacetNormals = false;
  40212. var computeFacetPositions = false;
  40213. var computeFacetPartitioning = false;
  40214. var computeDepthSort = false;
  40215. var faceNormalSign = 1;
  40216. var ratio = 0;
  40217. var distanceTo = null;
  40218. if (options) {
  40219. computeFacetNormals = (options.facetNormals) ? true : false;
  40220. computeFacetPositions = (options.facetPositions) ? true : false;
  40221. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40222. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  40223. ratio = options.ratio || 0;
  40224. computeDepthSort = (options.depthSort) ? true : false;
  40225. distanceTo = (options.distanceTo);
  40226. if (computeDepthSort) {
  40227. if (distanceTo === undefined) {
  40228. distanceTo = BABYLON.Vector3.Zero();
  40229. }
  40230. var depthSortedFacets = options.depthSortedFacets;
  40231. }
  40232. }
  40233. // facetPartitioning reinit if needed
  40234. var xSubRatio = 0;
  40235. var ySubRatio = 0;
  40236. var zSubRatio = 0;
  40237. var subSq = 0;
  40238. if (computeFacetPartitioning && options && options.bbSize) {
  40239. var ox = 0; // X partitioning index for facet position
  40240. var oy = 0; // Y partinioning index for facet position
  40241. var oz = 0; // Z partinioning index for facet position
  40242. var b1x = 0; // X partitioning index for facet v1 vertex
  40243. var b1y = 0; // Y partitioning index for facet v1 vertex
  40244. var b1z = 0; // z partitioning index for facet v1 vertex
  40245. var b2x = 0; // X partitioning index for facet v2 vertex
  40246. var b2y = 0; // Y partitioning index for facet v2 vertex
  40247. var b2z = 0; // Z partitioning index for facet v2 vertex
  40248. var b3x = 0; // X partitioning index for facet v3 vertex
  40249. var b3y = 0; // Y partitioning index for facet v3 vertex
  40250. var b3z = 0; // Z partitioning index for facet v3 vertex
  40251. var block_idx_o = 0; // facet barycenter block index
  40252. var block_idx_v1 = 0; // v1 vertex block index
  40253. var block_idx_v2 = 0; // v2 vertex block index
  40254. var block_idx_v3 = 0; // v3 vertex block index
  40255. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40256. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40257. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  40258. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  40259. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  40260. subSq = options.subDiv.max * options.subDiv.max;
  40261. options.facetPartitioning.length = 0;
  40262. }
  40263. // reset the normals
  40264. for (index = 0; index < positions.length; index++) {
  40265. normals[index] = 0.0;
  40266. }
  40267. // Loop : 1 indice triplet = 1 facet
  40268. var nbFaces = (indices.length / 3) | 0;
  40269. for (index = 0; index < nbFaces; index++) {
  40270. // get the indexes of the coordinates of each vertex of the facet
  40271. v1x = indices[index * 3] * 3;
  40272. v1y = v1x + 1;
  40273. v1z = v1x + 2;
  40274. v2x = indices[index * 3 + 1] * 3;
  40275. v2y = v2x + 1;
  40276. v2z = v2x + 2;
  40277. v3x = indices[index * 3 + 2] * 3;
  40278. v3y = v3x + 1;
  40279. v3z = v3x + 2;
  40280. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40281. p1p2y = positions[v1y] - positions[v2y];
  40282. p1p2z = positions[v1z] - positions[v2z];
  40283. p3p2x = positions[v3x] - positions[v2x];
  40284. p3p2y = positions[v3y] - positions[v2y];
  40285. p3p2z = positions[v3z] - positions[v2z];
  40286. // compute the face normal with the cross product
  40287. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  40288. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  40289. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  40290. // normalize this normal and store it in the array facetData
  40291. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40292. length = (length === 0) ? 1.0 : length;
  40293. faceNormalx /= length;
  40294. faceNormaly /= length;
  40295. faceNormalz /= length;
  40296. if (computeFacetNormals && options) {
  40297. options.facetNormals[index].x = faceNormalx;
  40298. options.facetNormals[index].y = faceNormaly;
  40299. options.facetNormals[index].z = faceNormalz;
  40300. }
  40301. if (computeFacetPositions && options) {
  40302. // compute and the facet barycenter coordinates in the array facetPositions
  40303. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40304. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40305. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40306. }
  40307. if (computeFacetPartitioning && options) {
  40308. // store the facet indexes in arrays in the main facetPartitioning array :
  40309. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40310. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  40311. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  40312. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  40313. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40314. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40315. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40316. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40317. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40318. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40319. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40320. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40321. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40322. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40323. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40324. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40325. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40326. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40327. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40328. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40329. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40330. // push each facet index in each block containing the vertex
  40331. options.facetPartitioning[block_idx_v1].push(index);
  40332. if (block_idx_v2 != block_idx_v1) {
  40333. options.facetPartitioning[block_idx_v2].push(index);
  40334. }
  40335. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40336. options.facetPartitioning[block_idx_v3].push(index);
  40337. }
  40338. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40339. options.facetPartitioning[block_idx_o].push(index);
  40340. }
  40341. }
  40342. if (computeDepthSort && options && options.facetPositions) {
  40343. var dsf = depthSortedFacets[index];
  40344. dsf.ind = index * 3;
  40345. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40346. }
  40347. // compute the normals anyway
  40348. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40349. normals[v1y] += faceNormaly;
  40350. normals[v1z] += faceNormalz;
  40351. normals[v2x] += faceNormalx;
  40352. normals[v2y] += faceNormaly;
  40353. normals[v2z] += faceNormalz;
  40354. normals[v3x] += faceNormalx;
  40355. normals[v3y] += faceNormaly;
  40356. normals[v3z] += faceNormalz;
  40357. }
  40358. // last normalization of each normal
  40359. for (index = 0; index < normals.length / 3; index++) {
  40360. faceNormalx = normals[index * 3];
  40361. faceNormaly = normals[index * 3 + 1];
  40362. faceNormalz = normals[index * 3 + 2];
  40363. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40364. length = (length === 0) ? 1.0 : length;
  40365. faceNormalx /= length;
  40366. faceNormaly /= length;
  40367. faceNormalz /= length;
  40368. normals[index * 3] = faceNormalx;
  40369. normals[index * 3 + 1] = faceNormaly;
  40370. normals[index * 3 + 2] = faceNormalz;
  40371. }
  40372. };
  40373. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40374. var li = indices.length;
  40375. var ln = normals.length;
  40376. var i;
  40377. var n;
  40378. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40379. switch (sideOrientation) {
  40380. case BABYLON.Mesh.FRONTSIDE:
  40381. // nothing changed
  40382. break;
  40383. case BABYLON.Mesh.BACKSIDE:
  40384. var tmp;
  40385. // indices
  40386. for (i = 0; i < li; i += 3) {
  40387. tmp = indices[i];
  40388. indices[i] = indices[i + 2];
  40389. indices[i + 2] = tmp;
  40390. }
  40391. // normals
  40392. for (n = 0; n < ln; n++) {
  40393. normals[n] = -normals[n];
  40394. }
  40395. break;
  40396. case BABYLON.Mesh.DOUBLESIDE:
  40397. // positions
  40398. var lp = positions.length;
  40399. var l = lp / 3;
  40400. for (var p = 0; p < lp; p++) {
  40401. positions[lp + p] = positions[p];
  40402. }
  40403. // indices
  40404. for (i = 0; i < li; i += 3) {
  40405. indices[i + li] = indices[i + 2] + l;
  40406. indices[i + 1 + li] = indices[i + 1] + l;
  40407. indices[i + 2 + li] = indices[i] + l;
  40408. }
  40409. // normals
  40410. for (n = 0; n < ln; n++) {
  40411. normals[ln + n] = -normals[n];
  40412. }
  40413. // uvs
  40414. var lu = uvs.length;
  40415. var u = 0;
  40416. for (u = 0; u < lu; u++) {
  40417. uvs[u + lu] = uvs[u];
  40418. }
  40419. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40420. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40421. u = 0;
  40422. for (i = 0; i < lu / 2; i++) {
  40423. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40424. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40425. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40426. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40427. u += 2;
  40428. }
  40429. break;
  40430. }
  40431. };
  40432. /**
  40433. * Applies VertexData created from the imported parameters to the geometry
  40434. * @param parsedVertexData the parsed data from an imported file
  40435. * @param geometry the geometry to apply the VertexData to
  40436. */
  40437. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40438. var vertexData = new VertexData();
  40439. // positions
  40440. var positions = parsedVertexData.positions;
  40441. if (positions) {
  40442. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40443. }
  40444. // normals
  40445. var normals = parsedVertexData.normals;
  40446. if (normals) {
  40447. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40448. }
  40449. // tangents
  40450. var tangents = parsedVertexData.tangents;
  40451. if (tangents) {
  40452. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40453. }
  40454. // uvs
  40455. var uvs = parsedVertexData.uvs;
  40456. if (uvs) {
  40457. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40458. }
  40459. // uv2s
  40460. var uv2s = parsedVertexData.uv2s;
  40461. if (uv2s) {
  40462. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40463. }
  40464. // uv3s
  40465. var uv3s = parsedVertexData.uv3s;
  40466. if (uv3s) {
  40467. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40468. }
  40469. // uv4s
  40470. var uv4s = parsedVertexData.uv4s;
  40471. if (uv4s) {
  40472. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40473. }
  40474. // uv5s
  40475. var uv5s = parsedVertexData.uv5s;
  40476. if (uv5s) {
  40477. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40478. }
  40479. // uv6s
  40480. var uv6s = parsedVertexData.uv6s;
  40481. if (uv6s) {
  40482. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40483. }
  40484. // colors
  40485. var colors = parsedVertexData.colors;
  40486. if (colors) {
  40487. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40488. }
  40489. // matricesIndices
  40490. var matricesIndices = parsedVertexData.matricesIndices;
  40491. if (matricesIndices) {
  40492. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40493. }
  40494. // matricesWeights
  40495. var matricesWeights = parsedVertexData.matricesWeights;
  40496. if (matricesWeights) {
  40497. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40498. }
  40499. // indices
  40500. var indices = parsedVertexData.indices;
  40501. if (indices) {
  40502. vertexData.indices = indices;
  40503. }
  40504. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40505. };
  40506. return VertexData;
  40507. }());
  40508. BABYLON.VertexData = VertexData;
  40509. })(BABYLON || (BABYLON = {}));
  40510. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40511. var BABYLON;
  40512. (function (BABYLON) {
  40513. /**
  40514. * Class used to store geometry data (vertex buffers + index buffer)
  40515. */
  40516. var Geometry = /** @class */ (function () {
  40517. /**
  40518. * Creates a new geometry
  40519. * @param id defines the unique ID
  40520. * @param scene defines the hosting scene
  40521. * @param vertexData defines the VertexData used to get geometry data
  40522. * @param updatable defines if geometry must be updatable (false by default)
  40523. * @param mesh defines the mesh that will be associated with the geometry
  40524. */
  40525. function Geometry(id, scene, vertexData, updatable, mesh) {
  40526. if (updatable === void 0) { updatable = false; }
  40527. if (mesh === void 0) { mesh = null; }
  40528. /**
  40529. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40530. */
  40531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40532. this._totalVertices = 0;
  40533. this._isDisposed = false;
  40534. this._indexBufferIsUpdatable = false;
  40535. this.id = id;
  40536. this._engine = scene.getEngine();
  40537. this._meshes = [];
  40538. this._scene = scene;
  40539. //Init vertex buffer cache
  40540. this._vertexBuffers = {};
  40541. this._indices = [];
  40542. this._updatable = updatable;
  40543. // vertexData
  40544. if (vertexData) {
  40545. this.setAllVerticesData(vertexData, updatable);
  40546. }
  40547. else {
  40548. this._totalVertices = 0;
  40549. this._indices = [];
  40550. }
  40551. if (this._engine.getCaps().vertexArrayObject) {
  40552. this._vertexArrayObjects = {};
  40553. }
  40554. // applyToMesh
  40555. if (mesh) {
  40556. if (mesh.getClassName() === "LinesMesh") {
  40557. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40558. this._updateExtend();
  40559. }
  40560. this.applyToMesh(mesh);
  40561. mesh.computeWorldMatrix(true);
  40562. }
  40563. }
  40564. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40565. /**
  40566. * 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
  40567. */
  40568. get: function () {
  40569. return this._boundingBias;
  40570. },
  40571. /**
  40572. * 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
  40573. */
  40574. set: function (value) {
  40575. if (this._boundingBias) {
  40576. if (this._boundingBias.equals(value)) {
  40577. return;
  40578. }
  40579. this._boundingBias.copyFrom(value);
  40580. }
  40581. else {
  40582. this._boundingBias = value.clone();
  40583. }
  40584. this._updateBoundingInfo(true, null);
  40585. },
  40586. enumerable: true,
  40587. configurable: true
  40588. });
  40589. /**
  40590. * Static function used to attach a new empty geometry to a mesh
  40591. * @param mesh defines the mesh to attach the geometry to
  40592. * @returns the new Geometry
  40593. */
  40594. Geometry.CreateGeometryForMesh = function (mesh) {
  40595. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40596. geometry.applyToMesh(mesh);
  40597. return geometry;
  40598. };
  40599. Object.defineProperty(Geometry.prototype, "extend", {
  40600. /**
  40601. * Gets the current extend of the geometry
  40602. */
  40603. get: function () {
  40604. return this._extend;
  40605. },
  40606. enumerable: true,
  40607. configurable: true
  40608. });
  40609. /**
  40610. * Gets the hosting scene
  40611. * @returns the hosting Scene
  40612. */
  40613. Geometry.prototype.getScene = function () {
  40614. return this._scene;
  40615. };
  40616. /**
  40617. * Gets the hosting engine
  40618. * @returns the hosting Engine
  40619. */
  40620. Geometry.prototype.getEngine = function () {
  40621. return this._engine;
  40622. };
  40623. /**
  40624. * Defines if the geometry is ready to use
  40625. * @returns true if the geometry is ready to be used
  40626. */
  40627. Geometry.prototype.isReady = function () {
  40628. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40629. };
  40630. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40631. /**
  40632. * Gets a value indicating that the geometry should not be serialized
  40633. */
  40634. get: function () {
  40635. for (var index = 0; index < this._meshes.length; index++) {
  40636. if (!this._meshes[index].doNotSerialize) {
  40637. return false;
  40638. }
  40639. }
  40640. return true;
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. /** @hidden */
  40646. Geometry.prototype._rebuild = function () {
  40647. if (this._vertexArrayObjects) {
  40648. this._vertexArrayObjects = {};
  40649. }
  40650. // Index buffer
  40651. if (this._meshes.length !== 0 && this._indices) {
  40652. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40653. }
  40654. // Vertex buffers
  40655. for (var key in this._vertexBuffers) {
  40656. var vertexBuffer = this._vertexBuffers[key];
  40657. vertexBuffer._rebuild();
  40658. }
  40659. };
  40660. /**
  40661. * Affects all geometry data in one call
  40662. * @param vertexData defines the geometry data
  40663. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40664. */
  40665. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40666. vertexData.applyToGeometry(this, updatable);
  40667. this.notifyUpdate();
  40668. };
  40669. /**
  40670. * Set specific vertex data
  40671. * @param kind defines the data kind (Position, normal, etc...)
  40672. * @param data defines the vertex data to use
  40673. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40674. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40675. */
  40676. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40677. if (updatable === void 0) { updatable = false; }
  40678. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40679. this.setVerticesBuffer(buffer);
  40680. };
  40681. /**
  40682. * Removes a specific vertex data
  40683. * @param kind defines the data kind (Position, normal, etc...)
  40684. */
  40685. Geometry.prototype.removeVerticesData = function (kind) {
  40686. if (this._vertexBuffers[kind]) {
  40687. this._vertexBuffers[kind].dispose();
  40688. delete this._vertexBuffers[kind];
  40689. }
  40690. };
  40691. /**
  40692. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40693. * @param buffer defines the vertex buffer to use
  40694. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40695. */
  40696. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40697. if (totalVertices === void 0) { totalVertices = null; }
  40698. var kind = buffer.getKind();
  40699. if (this._vertexBuffers[kind]) {
  40700. this._vertexBuffers[kind].dispose();
  40701. }
  40702. this._vertexBuffers[kind] = buffer;
  40703. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40704. var data = buffer.getData();
  40705. if (totalVertices != null) {
  40706. this._totalVertices = totalVertices;
  40707. }
  40708. else {
  40709. if (data != null) {
  40710. this._totalVertices = data.length / (buffer.byteStride / 4);
  40711. }
  40712. }
  40713. this._updateExtend(data);
  40714. this._resetPointsArrayCache();
  40715. var meshes = this._meshes;
  40716. var numOfMeshes = meshes.length;
  40717. for (var index = 0; index < numOfMeshes; index++) {
  40718. var mesh = meshes[index];
  40719. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40720. mesh._createGlobalSubMesh(false);
  40721. mesh.computeWorldMatrix(true);
  40722. }
  40723. }
  40724. this.notifyUpdate(kind);
  40725. if (this._vertexArrayObjects) {
  40726. this._disposeVertexArrayObjects();
  40727. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40728. }
  40729. };
  40730. /**
  40731. * Update a specific vertex buffer
  40732. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40733. * It will do nothing if the buffer is not updatable
  40734. * @param kind defines the data kind (Position, normal, etc...)
  40735. * @param data defines the data to use
  40736. * @param offset defines the offset in the target buffer where to store the data
  40737. * @param useBytes set to true if the offset is in bytes
  40738. */
  40739. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40740. if (useBytes === void 0) { useBytes = false; }
  40741. var vertexBuffer = this.getVertexBuffer(kind);
  40742. if (!vertexBuffer) {
  40743. return;
  40744. }
  40745. vertexBuffer.updateDirectly(data, offset, useBytes);
  40746. this.notifyUpdate(kind);
  40747. };
  40748. /**
  40749. * Update a specific vertex buffer
  40750. * This function will create a new buffer if the current one is not updatable
  40751. * @param kind defines the data kind (Position, normal, etc...)
  40752. * @param data defines the data to use
  40753. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40754. */
  40755. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40756. if (updateExtends === void 0) { updateExtends = false; }
  40757. var vertexBuffer = this.getVertexBuffer(kind);
  40758. if (!vertexBuffer) {
  40759. return;
  40760. }
  40761. vertexBuffer.update(data);
  40762. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40763. this._updateBoundingInfo(updateExtends, data);
  40764. }
  40765. this.notifyUpdate(kind);
  40766. };
  40767. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40768. if (updateExtends) {
  40769. this._updateExtend(data);
  40770. }
  40771. var meshes = this._meshes;
  40772. var numOfMeshes = meshes.length;
  40773. this._resetPointsArrayCache();
  40774. for (var index = 0; index < numOfMeshes; index++) {
  40775. var mesh = meshes[index];
  40776. if (updateExtends) {
  40777. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40778. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40779. var subMesh = mesh.subMeshes[subIndex];
  40780. subMesh.refreshBoundingInfo();
  40781. }
  40782. }
  40783. }
  40784. };
  40785. /** @hidden */
  40786. Geometry.prototype._bind = function (effect, indexToBind) {
  40787. if (!effect) {
  40788. return;
  40789. }
  40790. if (indexToBind === undefined) {
  40791. indexToBind = this._indexBuffer;
  40792. }
  40793. var vbs = this.getVertexBuffers();
  40794. if (!vbs) {
  40795. return;
  40796. }
  40797. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40798. this._engine.bindBuffers(vbs, indexToBind, effect);
  40799. return;
  40800. }
  40801. // Using VAO
  40802. if (!this._vertexArrayObjects[effect.key]) {
  40803. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40804. }
  40805. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40806. };
  40807. /**
  40808. * Gets total number of vertices
  40809. * @returns the total number of vertices
  40810. */
  40811. Geometry.prototype.getTotalVertices = function () {
  40812. if (!this.isReady()) {
  40813. return 0;
  40814. }
  40815. return this._totalVertices;
  40816. };
  40817. /**
  40818. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40819. * @param kind defines the data kind (Position, normal, etc...)
  40820. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40821. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40822. * @returns a float array containing vertex data
  40823. */
  40824. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40825. var vertexBuffer = this.getVertexBuffer(kind);
  40826. if (!vertexBuffer) {
  40827. return null;
  40828. }
  40829. var data = vertexBuffer.getData();
  40830. if (!data) {
  40831. return null;
  40832. }
  40833. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40834. var count = this._totalVertices * vertexBuffer.getSize();
  40835. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40836. var copy_1 = [];
  40837. vertexBuffer.forEach(count, function (value) { return copy_1.push(value); });
  40838. return copy_1;
  40839. }
  40840. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40841. if (data instanceof Array) {
  40842. var offset = vertexBuffer.byteOffset / 4;
  40843. return BABYLON.Tools.Slice(data, offset, offset + count);
  40844. }
  40845. else if (data instanceof ArrayBuffer) {
  40846. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40847. }
  40848. else {
  40849. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40850. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40851. var result = new Float32Array(count);
  40852. var source = new Float32Array(data.buffer, offset, count);
  40853. result.set(source);
  40854. return result;
  40855. }
  40856. return new Float32Array(data.buffer, offset, count);
  40857. }
  40858. }
  40859. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40860. return BABYLON.Tools.Slice(data);
  40861. }
  40862. return data;
  40863. };
  40864. /**
  40865. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40866. * @param kind defines the data kind (Position, normal, etc...)
  40867. * @returns true if the vertex buffer with the specified kind is updatable
  40868. */
  40869. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40870. var vb = this._vertexBuffers[kind];
  40871. if (!vb) {
  40872. return false;
  40873. }
  40874. return vb.isUpdatable();
  40875. };
  40876. /**
  40877. * Gets a specific vertex buffer
  40878. * @param kind defines the data kind (Position, normal, etc...)
  40879. * @returns a VertexBuffer
  40880. */
  40881. Geometry.prototype.getVertexBuffer = function (kind) {
  40882. if (!this.isReady()) {
  40883. return null;
  40884. }
  40885. return this._vertexBuffers[kind];
  40886. };
  40887. /**
  40888. * Returns all vertex buffers
  40889. * @return an object holding all vertex buffers indexed by kind
  40890. */
  40891. Geometry.prototype.getVertexBuffers = function () {
  40892. if (!this.isReady()) {
  40893. return null;
  40894. }
  40895. return this._vertexBuffers;
  40896. };
  40897. /**
  40898. * Gets a boolean indicating if specific vertex buffer is present
  40899. * @param kind defines the data kind (Position, normal, etc...)
  40900. * @returns true if data is present
  40901. */
  40902. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40903. if (!this._vertexBuffers) {
  40904. if (this._delayInfo) {
  40905. return this._delayInfo.indexOf(kind) !== -1;
  40906. }
  40907. return false;
  40908. }
  40909. return this._vertexBuffers[kind] !== undefined;
  40910. };
  40911. /**
  40912. * Gets a list of all attached data kinds (Position, normal, etc...)
  40913. * @returns a list of string containing all kinds
  40914. */
  40915. Geometry.prototype.getVerticesDataKinds = function () {
  40916. var result = [];
  40917. var kind;
  40918. if (!this._vertexBuffers && this._delayInfo) {
  40919. for (kind in this._delayInfo) {
  40920. result.push(kind);
  40921. }
  40922. }
  40923. else {
  40924. for (kind in this._vertexBuffers) {
  40925. result.push(kind);
  40926. }
  40927. }
  40928. return result;
  40929. };
  40930. /**
  40931. * Update index buffer
  40932. * @param indices defines the indices to store in the index buffer
  40933. * @param offset defines the offset in the target buffer where to store the data
  40934. */
  40935. Geometry.prototype.updateIndices = function (indices, offset) {
  40936. if (!this._indexBuffer) {
  40937. return;
  40938. }
  40939. if (!this._indexBufferIsUpdatable) {
  40940. this.setIndices(indices, null, true);
  40941. }
  40942. else {
  40943. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40944. }
  40945. };
  40946. /**
  40947. * Creates a new index buffer
  40948. * @param indices defines the indices to store in the index buffer
  40949. * @param totalVertices defines the total number of vertices (could be null)
  40950. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40951. */
  40952. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40953. if (totalVertices === void 0) { totalVertices = null; }
  40954. if (updatable === void 0) { updatable = false; }
  40955. if (this._indexBuffer) {
  40956. this._engine._releaseBuffer(this._indexBuffer);
  40957. }
  40958. this._disposeVertexArrayObjects();
  40959. this._indices = indices;
  40960. this._indexBufferIsUpdatable = updatable;
  40961. if (this._meshes.length !== 0 && this._indices) {
  40962. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40963. }
  40964. if (totalVertices != undefined) { // including null and undefined
  40965. this._totalVertices = totalVertices;
  40966. }
  40967. var meshes = this._meshes;
  40968. var numOfMeshes = meshes.length;
  40969. for (var index = 0; index < numOfMeshes; index++) {
  40970. meshes[index]._createGlobalSubMesh(true);
  40971. }
  40972. this.notifyUpdate();
  40973. };
  40974. /**
  40975. * Return the total number of indices
  40976. * @returns the total number of indices
  40977. */
  40978. Geometry.prototype.getTotalIndices = function () {
  40979. if (!this.isReady()) {
  40980. return 0;
  40981. }
  40982. return this._indices.length;
  40983. };
  40984. /**
  40985. * Gets the index buffer array
  40986. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40987. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40988. * @returns the index buffer array
  40989. */
  40990. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40991. if (!this.isReady()) {
  40992. return null;
  40993. }
  40994. var orig = this._indices;
  40995. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40996. return orig;
  40997. }
  40998. else {
  40999. var len = orig.length;
  41000. var copy = [];
  41001. for (var i = 0; i < len; i++) {
  41002. copy.push(orig[i]);
  41003. }
  41004. return copy;
  41005. }
  41006. };
  41007. /**
  41008. * Gets the index buffer
  41009. * @return the index buffer
  41010. */
  41011. Geometry.prototype.getIndexBuffer = function () {
  41012. if (!this.isReady()) {
  41013. return null;
  41014. }
  41015. return this._indexBuffer;
  41016. };
  41017. /** @hidden */
  41018. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  41019. if (effect === void 0) { effect = null; }
  41020. if (!effect || !this._vertexArrayObjects) {
  41021. return;
  41022. }
  41023. if (this._vertexArrayObjects[effect.key]) {
  41024. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  41025. delete this._vertexArrayObjects[effect.key];
  41026. }
  41027. };
  41028. /**
  41029. * Release the associated resources for a specific mesh
  41030. * @param mesh defines the source mesh
  41031. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  41032. */
  41033. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  41034. var meshes = this._meshes;
  41035. var index = meshes.indexOf(mesh);
  41036. if (index === -1) {
  41037. return;
  41038. }
  41039. meshes.splice(index, 1);
  41040. mesh._geometry = null;
  41041. if (meshes.length === 0 && shouldDispose) {
  41042. this.dispose();
  41043. }
  41044. };
  41045. /**
  41046. * Apply current geometry to a given mesh
  41047. * @param mesh defines the mesh to apply geometry to
  41048. */
  41049. Geometry.prototype.applyToMesh = function (mesh) {
  41050. if (mesh._geometry === this) {
  41051. return;
  41052. }
  41053. var previousGeometry = mesh._geometry;
  41054. if (previousGeometry) {
  41055. previousGeometry.releaseForMesh(mesh);
  41056. }
  41057. var meshes = this._meshes;
  41058. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41059. mesh._geometry = this;
  41060. this._scene.pushGeometry(this);
  41061. meshes.push(mesh);
  41062. if (this.isReady()) {
  41063. this._applyToMesh(mesh);
  41064. }
  41065. else {
  41066. mesh._boundingInfo = this._boundingInfo;
  41067. }
  41068. };
  41069. Geometry.prototype._updateExtend = function (data) {
  41070. if (data === void 0) { data = null; }
  41071. if (!data) {
  41072. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41073. }
  41074. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  41075. };
  41076. Geometry.prototype._applyToMesh = function (mesh) {
  41077. var numOfMeshes = this._meshes.length;
  41078. // vertexBuffers
  41079. for (var kind in this._vertexBuffers) {
  41080. if (numOfMeshes === 1) {
  41081. this._vertexBuffers[kind].create();
  41082. }
  41083. var buffer = this._vertexBuffers[kind].getBuffer();
  41084. if (buffer) {
  41085. buffer.references = numOfMeshes;
  41086. }
  41087. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41088. if (!this._extend) {
  41089. this._updateExtend();
  41090. }
  41091. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41092. mesh._createGlobalSubMesh(false);
  41093. //bounding info was just created again, world matrix should be applied again.
  41094. mesh._updateBoundingInfo();
  41095. }
  41096. }
  41097. // indexBuffer
  41098. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41099. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41100. }
  41101. if (this._indexBuffer) {
  41102. this._indexBuffer.references = numOfMeshes;
  41103. }
  41104. // morphTargets
  41105. mesh._syncGeometryWithMorphTargetManager();
  41106. };
  41107. Geometry.prototype.notifyUpdate = function (kind) {
  41108. if (this.onGeometryUpdated) {
  41109. this.onGeometryUpdated(this, kind);
  41110. }
  41111. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41112. var mesh = _a[_i];
  41113. mesh._markSubMeshesAsAttributesDirty();
  41114. }
  41115. };
  41116. /**
  41117. * Load the geometry if it was flagged as delay loaded
  41118. * @param scene defines the hosting scene
  41119. * @param onLoaded defines a callback called when the geometry is loaded
  41120. */
  41121. Geometry.prototype.load = function (scene, onLoaded) {
  41122. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41123. return;
  41124. }
  41125. if (this.isReady()) {
  41126. if (onLoaded) {
  41127. onLoaded();
  41128. }
  41129. return;
  41130. }
  41131. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41132. this._queueLoad(scene, onLoaded);
  41133. };
  41134. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41135. var _this = this;
  41136. if (!this.delayLoadingFile) {
  41137. return;
  41138. }
  41139. scene._addPendingData(this);
  41140. scene._loadFile(this.delayLoadingFile, function (data) {
  41141. if (!_this._delayLoadingFunction) {
  41142. return;
  41143. }
  41144. _this._delayLoadingFunction(JSON.parse(data), _this);
  41145. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41146. _this._delayInfo = [];
  41147. scene._removePendingData(_this);
  41148. var meshes = _this._meshes;
  41149. var numOfMeshes = meshes.length;
  41150. for (var index = 0; index < numOfMeshes; index++) {
  41151. _this._applyToMesh(meshes[index]);
  41152. }
  41153. if (onLoaded) {
  41154. onLoaded();
  41155. }
  41156. }, undefined, true);
  41157. };
  41158. /**
  41159. * Invert the geometry to move from a right handed system to a left handed one.
  41160. */
  41161. Geometry.prototype.toLeftHanded = function () {
  41162. // Flip faces
  41163. var tIndices = this.getIndices(false);
  41164. if (tIndices != null && tIndices.length > 0) {
  41165. for (var i = 0; i < tIndices.length; i += 3) {
  41166. var tTemp = tIndices[i + 0];
  41167. tIndices[i + 0] = tIndices[i + 2];
  41168. tIndices[i + 2] = tTemp;
  41169. }
  41170. this.setIndices(tIndices);
  41171. }
  41172. // Negate position.z
  41173. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41174. if (tPositions != null && tPositions.length > 0) {
  41175. for (var i = 0; i < tPositions.length; i += 3) {
  41176. tPositions[i + 2] = -tPositions[i + 2];
  41177. }
  41178. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41179. }
  41180. // Negate normal.z
  41181. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41182. if (tNormals != null && tNormals.length > 0) {
  41183. for (var i = 0; i < tNormals.length; i += 3) {
  41184. tNormals[i + 2] = -tNormals[i + 2];
  41185. }
  41186. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41187. }
  41188. };
  41189. // Cache
  41190. /** @hidden */
  41191. Geometry.prototype._resetPointsArrayCache = function () {
  41192. this._positions = null;
  41193. };
  41194. /** @hidden */
  41195. Geometry.prototype._generatePointsArray = function () {
  41196. if (this._positions) {
  41197. return true;
  41198. }
  41199. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41200. if (!data || data.length === 0) {
  41201. return false;
  41202. }
  41203. this._positions = [];
  41204. for (var index = 0; index < data.length; index += 3) {
  41205. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  41206. }
  41207. return true;
  41208. };
  41209. /**
  41210. * Gets a value indicating if the geometry is disposed
  41211. * @returns true if the geometry was disposed
  41212. */
  41213. Geometry.prototype.isDisposed = function () {
  41214. return this._isDisposed;
  41215. };
  41216. Geometry.prototype._disposeVertexArrayObjects = function () {
  41217. if (this._vertexArrayObjects) {
  41218. for (var kind in this._vertexArrayObjects) {
  41219. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41220. }
  41221. this._vertexArrayObjects = {};
  41222. }
  41223. };
  41224. /**
  41225. * Free all associated resources
  41226. */
  41227. Geometry.prototype.dispose = function () {
  41228. var meshes = this._meshes;
  41229. var numOfMeshes = meshes.length;
  41230. var index;
  41231. for (index = 0; index < numOfMeshes; index++) {
  41232. this.releaseForMesh(meshes[index]);
  41233. }
  41234. this._meshes = [];
  41235. this._disposeVertexArrayObjects();
  41236. for (var kind in this._vertexBuffers) {
  41237. this._vertexBuffers[kind].dispose();
  41238. }
  41239. this._vertexBuffers = {};
  41240. this._totalVertices = 0;
  41241. if (this._indexBuffer) {
  41242. this._engine._releaseBuffer(this._indexBuffer);
  41243. }
  41244. this._indexBuffer = null;
  41245. this._indices = [];
  41246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41247. this.delayLoadingFile = null;
  41248. this._delayLoadingFunction = null;
  41249. this._delayInfo = [];
  41250. this._boundingInfo = null;
  41251. this._scene.removeGeometry(this);
  41252. this._isDisposed = true;
  41253. };
  41254. /**
  41255. * Clone the current geometry into a new geometry
  41256. * @param id defines the unique ID of the new geometry
  41257. * @returns a new geometry object
  41258. */
  41259. Geometry.prototype.copy = function (id) {
  41260. var vertexData = new BABYLON.VertexData();
  41261. vertexData.indices = [];
  41262. var indices = this.getIndices();
  41263. if (indices) {
  41264. for (var index = 0; index < indices.length; index++) {
  41265. vertexData.indices.push(indices[index]);
  41266. }
  41267. }
  41268. var updatable = false;
  41269. var stopChecking = false;
  41270. var kind;
  41271. for (kind in this._vertexBuffers) {
  41272. // using slice() to make a copy of the array and not just reference it
  41273. var data = this.getVerticesData(kind);
  41274. if (data instanceof Float32Array) {
  41275. vertexData.set(new Float32Array(data), kind);
  41276. }
  41277. else {
  41278. vertexData.set(data.slice(0), kind);
  41279. }
  41280. if (!stopChecking) {
  41281. var vb = this.getVertexBuffer(kind);
  41282. if (vb) {
  41283. updatable = vb.isUpdatable();
  41284. stopChecking = !updatable;
  41285. }
  41286. }
  41287. }
  41288. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  41289. geometry.delayLoadState = this.delayLoadState;
  41290. geometry.delayLoadingFile = this.delayLoadingFile;
  41291. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41292. for (kind in this._delayInfo) {
  41293. geometry._delayInfo = geometry._delayInfo || [];
  41294. geometry._delayInfo.push(kind);
  41295. }
  41296. // Bounding info
  41297. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41298. return geometry;
  41299. };
  41300. /**
  41301. * Serialize the current geometry info (and not the vertices data) into a JSON object
  41302. * @return a JSON representation of the current geometry data (without the vertices data)
  41303. */
  41304. Geometry.prototype.serialize = function () {
  41305. var serializationObject = {};
  41306. serializationObject.id = this.id;
  41307. serializationObject.updatable = this._updatable;
  41308. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  41309. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41310. }
  41311. return serializationObject;
  41312. };
  41313. Geometry.prototype.toNumberArray = function (origin) {
  41314. if (Array.isArray(origin)) {
  41315. return origin;
  41316. }
  41317. else {
  41318. return Array.prototype.slice.call(origin);
  41319. }
  41320. };
  41321. /**
  41322. * Serialize all vertices data into a JSON oject
  41323. * @returns a JSON representation of the current geometry data
  41324. */
  41325. Geometry.prototype.serializeVerticeData = function () {
  41326. var serializationObject = this.serialize();
  41327. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41328. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41329. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41330. serializationObject.positions._updatable = true;
  41331. }
  41332. }
  41333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41334. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41335. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41336. serializationObject.normals._updatable = true;
  41337. }
  41338. }
  41339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41340. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41341. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41342. serializationObject.tangets._updatable = true;
  41343. }
  41344. }
  41345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41346. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41347. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41348. serializationObject.uvs._updatable = true;
  41349. }
  41350. }
  41351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41352. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41353. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41354. serializationObject.uv2s._updatable = true;
  41355. }
  41356. }
  41357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41358. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41359. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41360. serializationObject.uv3s._updatable = true;
  41361. }
  41362. }
  41363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41364. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41365. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41366. serializationObject.uv4s._updatable = true;
  41367. }
  41368. }
  41369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41370. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41371. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41372. serializationObject.uv5s._updatable = true;
  41373. }
  41374. }
  41375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41376. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41377. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41378. serializationObject.uv6s._updatable = true;
  41379. }
  41380. }
  41381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41382. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41383. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41384. serializationObject.colors._updatable = true;
  41385. }
  41386. }
  41387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41388. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41389. serializationObject.matricesIndices._isExpanded = true;
  41390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41391. serializationObject.matricesIndices._updatable = true;
  41392. }
  41393. }
  41394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41395. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41397. serializationObject.matricesWeights._updatable = true;
  41398. }
  41399. }
  41400. serializationObject.indices = this.toNumberArray(this.getIndices());
  41401. return serializationObject;
  41402. };
  41403. // Statics
  41404. /**
  41405. * Extracts a clone of a mesh geometry
  41406. * @param mesh defines the source mesh
  41407. * @param id defines the unique ID of the new geometry object
  41408. * @returns the new geometry object
  41409. */
  41410. Geometry.ExtractFromMesh = function (mesh, id) {
  41411. var geometry = mesh._geometry;
  41412. if (!geometry) {
  41413. return null;
  41414. }
  41415. return geometry.copy(id);
  41416. };
  41417. /**
  41418. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41419. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41420. * Be aware Math.random() could cause collisions, but:
  41421. * "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"
  41422. * @returns a string containing a new GUID
  41423. */
  41424. Geometry.RandomId = function () {
  41425. return BABYLON.Tools.RandomId();
  41426. };
  41427. /** @hidden */
  41428. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41429. var scene = mesh.getScene();
  41430. // Geometry
  41431. var geometryId = parsedGeometry.geometryId;
  41432. if (geometryId) {
  41433. var geometry = scene.getGeometryByID(geometryId);
  41434. if (geometry) {
  41435. geometry.applyToMesh(mesh);
  41436. }
  41437. }
  41438. else if (parsedGeometry instanceof ArrayBuffer) {
  41439. var binaryInfo = mesh._binaryInfo;
  41440. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41441. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41442. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41443. }
  41444. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41445. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41446. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41447. }
  41448. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41449. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41450. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41451. }
  41452. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41453. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41454. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41455. }
  41456. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41457. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41458. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41459. }
  41460. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41461. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41462. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41463. }
  41464. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41465. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41466. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41467. }
  41468. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41469. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41470. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41471. }
  41472. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41473. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41474. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41475. }
  41476. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41477. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41478. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41479. }
  41480. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41481. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41482. var floatIndices = [];
  41483. for (var i = 0; i < matricesIndicesData.length; i++) {
  41484. var index = matricesIndicesData[i];
  41485. floatIndices.push(index & 0x000000FF);
  41486. floatIndices.push((index & 0x0000FF00) >> 8);
  41487. floatIndices.push((index & 0x00FF0000) >> 16);
  41488. floatIndices.push(index >> 24);
  41489. }
  41490. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41491. }
  41492. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41493. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41495. }
  41496. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41497. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41498. mesh.setIndices(indicesData, null);
  41499. }
  41500. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41501. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41502. mesh.subMeshes = [];
  41503. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41504. var materialIndex = subMeshesData[(i * 5) + 0];
  41505. var verticesStart = subMeshesData[(i * 5) + 1];
  41506. var verticesCount = subMeshesData[(i * 5) + 2];
  41507. var indexStart = subMeshesData[(i * 5) + 3];
  41508. var indexCount = subMeshesData[(i * 5) + 4];
  41509. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41510. }
  41511. }
  41512. }
  41513. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41514. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41515. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41516. if (parsedGeometry.tangents) {
  41517. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41518. }
  41519. if (parsedGeometry.uvs) {
  41520. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41521. }
  41522. if (parsedGeometry.uvs2) {
  41523. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41524. }
  41525. if (parsedGeometry.uvs3) {
  41526. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41527. }
  41528. if (parsedGeometry.uvs4) {
  41529. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41530. }
  41531. if (parsedGeometry.uvs5) {
  41532. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41533. }
  41534. if (parsedGeometry.uvs6) {
  41535. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41536. }
  41537. if (parsedGeometry.colors) {
  41538. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41539. }
  41540. if (parsedGeometry.matricesIndices) {
  41541. if (!parsedGeometry.matricesIndices._isExpanded) {
  41542. var floatIndices = [];
  41543. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41544. var matricesIndex = parsedGeometry.matricesIndices[i];
  41545. floatIndices.push(matricesIndex & 0x000000FF);
  41546. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41547. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41548. floatIndices.push(matricesIndex >> 24);
  41549. }
  41550. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41551. }
  41552. else {
  41553. delete parsedGeometry.matricesIndices._isExpanded;
  41554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41555. }
  41556. }
  41557. if (parsedGeometry.matricesIndicesExtra) {
  41558. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41559. var floatIndices = [];
  41560. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41561. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41562. floatIndices.push(matricesIndex & 0x000000FF);
  41563. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41564. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41565. floatIndices.push(matricesIndex >> 24);
  41566. }
  41567. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41568. }
  41569. else {
  41570. delete parsedGeometry.matricesIndices._isExpanded;
  41571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41572. }
  41573. }
  41574. if (parsedGeometry.matricesWeights) {
  41575. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41576. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41577. }
  41578. if (parsedGeometry.matricesWeightsExtra) {
  41579. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41580. }
  41581. mesh.setIndices(parsedGeometry.indices, null);
  41582. }
  41583. // SubMeshes
  41584. if (parsedGeometry.subMeshes) {
  41585. mesh.subMeshes = [];
  41586. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41587. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41588. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41589. }
  41590. }
  41591. // Flat shading
  41592. if (mesh._shouldGenerateFlatShading) {
  41593. mesh.convertToFlatShadedMesh();
  41594. delete mesh._shouldGenerateFlatShading;
  41595. }
  41596. // Update
  41597. mesh.computeWorldMatrix(true);
  41598. scene.onMeshImportedObservable.notifyObservers(mesh);
  41599. };
  41600. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41601. var epsilon = 1e-3;
  41602. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41603. return;
  41604. }
  41605. var noInfluenceBoneIndex = 0.0;
  41606. if (parsedGeometry.skeletonId > -1) {
  41607. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41608. if (!skeleton) {
  41609. return;
  41610. }
  41611. noInfluenceBoneIndex = skeleton.bones.length;
  41612. }
  41613. else {
  41614. return;
  41615. }
  41616. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41617. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41618. var matricesWeights = parsedGeometry.matricesWeights;
  41619. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41620. var influencers = parsedGeometry.numBoneInfluencer;
  41621. var size = matricesWeights.length;
  41622. for (var i = 0; i < size; i += 4) {
  41623. var weight = 0.0;
  41624. var firstZeroWeight = -1;
  41625. for (var j = 0; j < 4; j++) {
  41626. var w = matricesWeights[i + j];
  41627. weight += w;
  41628. if (w < epsilon && firstZeroWeight < 0) {
  41629. firstZeroWeight = j;
  41630. }
  41631. }
  41632. if (matricesWeightsExtra) {
  41633. for (var j = 0; j < 4; j++) {
  41634. var w = matricesWeightsExtra[i + j];
  41635. weight += w;
  41636. if (w < epsilon && firstZeroWeight < 0) {
  41637. firstZeroWeight = j + 4;
  41638. }
  41639. }
  41640. }
  41641. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41642. firstZeroWeight = influencers - 1;
  41643. }
  41644. if (weight > epsilon) {
  41645. var mweight = 1.0 / weight;
  41646. for (var j = 0; j < 4; j++) {
  41647. matricesWeights[i + j] *= mweight;
  41648. }
  41649. if (matricesWeightsExtra) {
  41650. for (var j = 0; j < 4; j++) {
  41651. matricesWeightsExtra[i + j] *= mweight;
  41652. }
  41653. }
  41654. }
  41655. else {
  41656. if (firstZeroWeight >= 4) {
  41657. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41658. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41659. }
  41660. else {
  41661. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41662. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41663. }
  41664. }
  41665. }
  41666. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41667. if (parsedGeometry.matricesWeightsExtra) {
  41668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41669. }
  41670. };
  41671. /**
  41672. * Create a new geometry from persisted data (Using .babylon file format)
  41673. * @param parsedVertexData defines the persisted data
  41674. * @param scene defines the hosting scene
  41675. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41676. * @returns the new geometry object
  41677. */
  41678. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41679. if (scene.getGeometryByID(parsedVertexData.id)) {
  41680. return null; // null since geometry could be something else than a box...
  41681. }
  41682. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41683. if (BABYLON.Tags) {
  41684. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41685. }
  41686. if (parsedVertexData.delayLoadingFile) {
  41687. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41688. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41689. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41690. geometry._delayInfo = [];
  41691. if (parsedVertexData.hasUVs) {
  41692. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41693. }
  41694. if (parsedVertexData.hasUVs2) {
  41695. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41696. }
  41697. if (parsedVertexData.hasUVs3) {
  41698. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41699. }
  41700. if (parsedVertexData.hasUVs4) {
  41701. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41702. }
  41703. if (parsedVertexData.hasUVs5) {
  41704. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41705. }
  41706. if (parsedVertexData.hasUVs6) {
  41707. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41708. }
  41709. if (parsedVertexData.hasColors) {
  41710. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41711. }
  41712. if (parsedVertexData.hasMatricesIndices) {
  41713. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41714. }
  41715. if (parsedVertexData.hasMatricesWeights) {
  41716. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41717. }
  41718. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41719. }
  41720. else {
  41721. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41722. }
  41723. scene.pushGeometry(geometry, true);
  41724. return geometry;
  41725. };
  41726. return Geometry;
  41727. }());
  41728. BABYLON.Geometry = Geometry;
  41729. // Primitives
  41730. /// Abstract class
  41731. /**
  41732. * Abstract class used to provide common services for all typed geometries
  41733. * @hidden
  41734. */
  41735. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41736. __extends(_PrimitiveGeometry, _super);
  41737. /**
  41738. * Creates a new typed geometry
  41739. * @param id defines the unique ID of the geometry
  41740. * @param scene defines the hosting scene
  41741. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41742. * @param mesh defines the hosting mesh (can be null)
  41743. */
  41744. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41745. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41746. if (mesh === void 0) { mesh = null; }
  41747. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41748. _this._canBeRegenerated = _canBeRegenerated;
  41749. _this._beingRegenerated = true;
  41750. _this.regenerate();
  41751. _this._beingRegenerated = false;
  41752. return _this;
  41753. }
  41754. /**
  41755. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41756. * @returns true if the geometry can be regenerated
  41757. */
  41758. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41759. return this._canBeRegenerated;
  41760. };
  41761. /**
  41762. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41763. */
  41764. _PrimitiveGeometry.prototype.regenerate = function () {
  41765. if (!this._canBeRegenerated) {
  41766. return;
  41767. }
  41768. this._beingRegenerated = true;
  41769. this.setAllVerticesData(this._regenerateVertexData(), false);
  41770. this._beingRegenerated = false;
  41771. };
  41772. /**
  41773. * Clone the geometry
  41774. * @param id defines the unique ID of the new geometry
  41775. * @returns the new geometry
  41776. */
  41777. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41778. return _super.prototype.copy.call(this, id);
  41779. };
  41780. // overrides
  41781. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41782. if (!this._beingRegenerated) {
  41783. return;
  41784. }
  41785. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41786. };
  41787. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41788. if (!this._beingRegenerated) {
  41789. return;
  41790. }
  41791. _super.prototype.setVerticesData.call(this, kind, data, false);
  41792. };
  41793. // to override
  41794. /** @hidden */
  41795. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41796. throw new Error("Abstract method");
  41797. };
  41798. _PrimitiveGeometry.prototype.copy = function (id) {
  41799. throw new Error("Must be overriden in sub-classes.");
  41800. };
  41801. _PrimitiveGeometry.prototype.serialize = function () {
  41802. var serializationObject = _super.prototype.serialize.call(this);
  41803. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41804. return serializationObject;
  41805. };
  41806. return _PrimitiveGeometry;
  41807. }(Geometry));
  41808. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41809. /**
  41810. * Creates a ribbon geometry
  41811. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41812. */
  41813. var RibbonGeometry = /** @class */ (function (_super) {
  41814. __extends(RibbonGeometry, _super);
  41815. /**
  41816. * Creates a ribbon geometry
  41817. * @param id defines the unique ID of the geometry
  41818. * @param scene defines the hosting scene
  41819. * @param pathArray defines the array of paths to use
  41820. * @param closeArray defines if the last path and the first path must be joined
  41821. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41822. * @param offset defines the offset between points
  41823. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41824. * @param mesh defines the hosting mesh (can be null)
  41825. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41826. */
  41827. function RibbonGeometry(id, scene,
  41828. /**
  41829. * Defines the array of paths to use
  41830. */
  41831. pathArray,
  41832. /**
  41833. * Defines if the last and first points of each path in your pathArray must be joined
  41834. */
  41835. closeArray,
  41836. /**
  41837. * Defines if the last and first points of each path in your pathArray must be joined
  41838. */
  41839. closePath,
  41840. /**
  41841. * Defines the offset between points
  41842. */
  41843. offset, canBeRegenerated, mesh,
  41844. /**
  41845. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41846. */
  41847. side) {
  41848. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41849. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41850. _this.pathArray = pathArray;
  41851. _this.closeArray = closeArray;
  41852. _this.closePath = closePath;
  41853. _this.offset = offset;
  41854. _this.side = side;
  41855. return _this;
  41856. }
  41857. /** @hidden */
  41858. RibbonGeometry.prototype._regenerateVertexData = function () {
  41859. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41860. };
  41861. RibbonGeometry.prototype.copy = function (id) {
  41862. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41863. };
  41864. return RibbonGeometry;
  41865. }(_PrimitiveGeometry));
  41866. BABYLON.RibbonGeometry = RibbonGeometry;
  41867. /**
  41868. * Creates a box geometry
  41869. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41870. */
  41871. var BoxGeometry = /** @class */ (function (_super) {
  41872. __extends(BoxGeometry, _super);
  41873. /**
  41874. * Creates a box geometry
  41875. * @param id defines the unique ID of the geometry
  41876. * @param scene defines the hosting scene
  41877. * @param size defines the zise of the box (width, height and depth are the same)
  41878. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41879. * @param mesh defines the hosting mesh (can be null)
  41880. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41881. */
  41882. function BoxGeometry(id, scene,
  41883. /**
  41884. * Defines the zise of the box (width, height and depth are the same)
  41885. */
  41886. size, canBeRegenerated, mesh,
  41887. /**
  41888. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41889. */
  41890. side) {
  41891. if (mesh === void 0) { mesh = null; }
  41892. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41893. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41894. _this.size = size;
  41895. _this.side = side;
  41896. return _this;
  41897. }
  41898. /** @hidden */
  41899. BoxGeometry.prototype._regenerateVertexData = function () {
  41900. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41901. };
  41902. BoxGeometry.prototype.copy = function (id) {
  41903. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41904. };
  41905. BoxGeometry.prototype.serialize = function () {
  41906. var serializationObject = _super.prototype.serialize.call(this);
  41907. serializationObject.size = this.size;
  41908. return serializationObject;
  41909. };
  41910. BoxGeometry.Parse = function (parsedBox, scene) {
  41911. if (scene.getGeometryByID(parsedBox.id)) {
  41912. return null; // null since geometry could be something else than a box...
  41913. }
  41914. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41915. if (BABYLON.Tags) {
  41916. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41917. }
  41918. scene.pushGeometry(box, true);
  41919. return box;
  41920. };
  41921. return BoxGeometry;
  41922. }(_PrimitiveGeometry));
  41923. BABYLON.BoxGeometry = BoxGeometry;
  41924. /**
  41925. * Creates a sphere geometry
  41926. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41927. */
  41928. var SphereGeometry = /** @class */ (function (_super) {
  41929. __extends(SphereGeometry, _super);
  41930. /**
  41931. * Create a new sphere geometry
  41932. * @param id defines the unique ID of the geometry
  41933. * @param scene defines the hosting scene
  41934. * @param segments defines the number of segments to use to create the sphere
  41935. * @param diameter defines the diameter of the sphere
  41936. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41937. * @param mesh defines the hosting mesh (can be null)
  41938. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41939. */
  41940. function SphereGeometry(id, scene,
  41941. /**
  41942. * Defines the number of segments to use to create the sphere
  41943. */
  41944. segments,
  41945. /**
  41946. * Defines the diameter of the sphere
  41947. */
  41948. diameter, canBeRegenerated, mesh,
  41949. /**
  41950. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41951. */
  41952. side) {
  41953. if (mesh === void 0) { mesh = null; }
  41954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41955. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41956. _this.segments = segments;
  41957. _this.diameter = diameter;
  41958. _this.side = side;
  41959. return _this;
  41960. }
  41961. /** @hidden */
  41962. SphereGeometry.prototype._regenerateVertexData = function () {
  41963. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41964. };
  41965. SphereGeometry.prototype.copy = function (id) {
  41966. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41967. };
  41968. SphereGeometry.prototype.serialize = function () {
  41969. var serializationObject = _super.prototype.serialize.call(this);
  41970. serializationObject.segments = this.segments;
  41971. serializationObject.diameter = this.diameter;
  41972. return serializationObject;
  41973. };
  41974. SphereGeometry.Parse = function (parsedSphere, scene) {
  41975. if (scene.getGeometryByID(parsedSphere.id)) {
  41976. return null; // null since geometry could be something else than a sphere...
  41977. }
  41978. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41979. if (BABYLON.Tags) {
  41980. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41981. }
  41982. scene.pushGeometry(sphere, true);
  41983. return sphere;
  41984. };
  41985. return SphereGeometry;
  41986. }(_PrimitiveGeometry));
  41987. BABYLON.SphereGeometry = SphereGeometry;
  41988. /**
  41989. * Creates a disc geometry
  41990. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41991. */
  41992. var DiscGeometry = /** @class */ (function (_super) {
  41993. __extends(DiscGeometry, _super);
  41994. /**
  41995. * Creates a new disc geometry
  41996. * @param id defines the unique ID of the geometry
  41997. * @param scene defines the hosting scene
  41998. * @param radius defines the radius of the disc
  41999. * @param tessellation defines the tesselation factor to apply to the disc
  42000. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42001. * @param mesh defines the hosting mesh (can be null)
  42002. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42003. */
  42004. function DiscGeometry(id, scene,
  42005. /**
  42006. * Defines the radius of the disc
  42007. */
  42008. radius,
  42009. /**
  42010. * Defines the tesselation factor to apply to the disc
  42011. */
  42012. tessellation, canBeRegenerated, mesh,
  42013. /**
  42014. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42015. */
  42016. side) {
  42017. if (mesh === void 0) { mesh = null; }
  42018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42019. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42020. _this.radius = radius;
  42021. _this.tessellation = tessellation;
  42022. _this.side = side;
  42023. return _this;
  42024. }
  42025. /** @hidden */
  42026. DiscGeometry.prototype._regenerateVertexData = function () {
  42027. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  42028. };
  42029. DiscGeometry.prototype.copy = function (id) {
  42030. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  42031. };
  42032. return DiscGeometry;
  42033. }(_PrimitiveGeometry));
  42034. BABYLON.DiscGeometry = DiscGeometry;
  42035. /**
  42036. * Creates a new cylinder geometry
  42037. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  42038. */
  42039. var CylinderGeometry = /** @class */ (function (_super) {
  42040. __extends(CylinderGeometry, _super);
  42041. /**
  42042. * Creates a new cylinder geometry
  42043. * @param id defines the unique ID of the geometry
  42044. * @param scene defines the hosting scene
  42045. * @param height defines the height of the cylinder
  42046. * @param diameterTop defines the diameter of the cylinder's top cap
  42047. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  42048. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  42049. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  42050. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42051. * @param mesh defines the hosting mesh (can be null)
  42052. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42053. */
  42054. function CylinderGeometry(id, scene,
  42055. /**
  42056. * Defines the height of the cylinder
  42057. */
  42058. height,
  42059. /**
  42060. * Defines the diameter of the cylinder's top cap
  42061. */
  42062. diameterTop,
  42063. /**
  42064. * Defines the diameter of the cylinder's bottom cap
  42065. */
  42066. diameterBottom,
  42067. /**
  42068. * Defines the tessellation factor to apply to the cylinder
  42069. */
  42070. tessellation,
  42071. /**
  42072. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  42073. */
  42074. subdivisions, canBeRegenerated, mesh,
  42075. /**
  42076. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42077. */
  42078. side) {
  42079. if (subdivisions === void 0) { subdivisions = 1; }
  42080. if (mesh === void 0) { mesh = null; }
  42081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42082. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42083. _this.height = height;
  42084. _this.diameterTop = diameterTop;
  42085. _this.diameterBottom = diameterBottom;
  42086. _this.tessellation = tessellation;
  42087. _this.subdivisions = subdivisions;
  42088. _this.side = side;
  42089. return _this;
  42090. }
  42091. /** @hidden */
  42092. CylinderGeometry.prototype._regenerateVertexData = function () {
  42093. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  42094. };
  42095. CylinderGeometry.prototype.copy = function (id) {
  42096. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  42097. };
  42098. CylinderGeometry.prototype.serialize = function () {
  42099. var serializationObject = _super.prototype.serialize.call(this);
  42100. serializationObject.height = this.height;
  42101. serializationObject.diameterTop = this.diameterTop;
  42102. serializationObject.diameterBottom = this.diameterBottom;
  42103. serializationObject.tessellation = this.tessellation;
  42104. return serializationObject;
  42105. };
  42106. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  42107. if (scene.getGeometryByID(parsedCylinder.id)) {
  42108. return null; // null since geometry could be something else than a cylinder...
  42109. }
  42110. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  42111. if (BABYLON.Tags) {
  42112. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  42113. }
  42114. scene.pushGeometry(cylinder, true);
  42115. return cylinder;
  42116. };
  42117. return CylinderGeometry;
  42118. }(_PrimitiveGeometry));
  42119. BABYLON.CylinderGeometry = CylinderGeometry;
  42120. /**
  42121. * Creates a new torus geometry
  42122. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  42123. */
  42124. var TorusGeometry = /** @class */ (function (_super) {
  42125. __extends(TorusGeometry, _super);
  42126. /**
  42127. * Creates a new torus geometry
  42128. * @param id defines the unique ID of the geometry
  42129. * @param scene defines the hosting scene
  42130. * @param diameter defines the diameter of the torus
  42131. * @param thickness defines the thickness of the torus (ie. internal diameter)
  42132. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  42133. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42134. * @param mesh defines the hosting mesh (can be null)
  42135. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42136. */
  42137. function TorusGeometry(id, scene,
  42138. /**
  42139. * Defines the diameter of the torus
  42140. */
  42141. diameter,
  42142. /**
  42143. * Defines the thickness of the torus (ie. internal diameter)
  42144. */
  42145. thickness,
  42146. /**
  42147. * Defines the tesselation factor to apply to the torus
  42148. */
  42149. tessellation, canBeRegenerated, mesh,
  42150. /**
  42151. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42152. */
  42153. side) {
  42154. if (mesh === void 0) { mesh = null; }
  42155. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42156. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42157. _this.diameter = diameter;
  42158. _this.thickness = thickness;
  42159. _this.tessellation = tessellation;
  42160. _this.side = side;
  42161. return _this;
  42162. }
  42163. /** @hidden */
  42164. TorusGeometry.prototype._regenerateVertexData = function () {
  42165. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42166. };
  42167. TorusGeometry.prototype.copy = function (id) {
  42168. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42169. };
  42170. TorusGeometry.prototype.serialize = function () {
  42171. var serializationObject = _super.prototype.serialize.call(this);
  42172. serializationObject.diameter = this.diameter;
  42173. serializationObject.thickness = this.thickness;
  42174. serializationObject.tessellation = this.tessellation;
  42175. return serializationObject;
  42176. };
  42177. TorusGeometry.Parse = function (parsedTorus, scene) {
  42178. if (scene.getGeometryByID(parsedTorus.id)) {
  42179. return null; // null since geometry could be something else than a torus...
  42180. }
  42181. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42182. if (BABYLON.Tags) {
  42183. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42184. }
  42185. scene.pushGeometry(torus, true);
  42186. return torus;
  42187. };
  42188. return TorusGeometry;
  42189. }(_PrimitiveGeometry));
  42190. BABYLON.TorusGeometry = TorusGeometry;
  42191. /**
  42192. * Creates a new ground geometry
  42193. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  42194. */
  42195. var GroundGeometry = /** @class */ (function (_super) {
  42196. __extends(GroundGeometry, _super);
  42197. /**
  42198. * Creates a new ground geometry
  42199. * @param id defines the unique ID of the geometry
  42200. * @param scene defines the hosting scene
  42201. * @param width defines the width of the ground
  42202. * @param height defines the height of the ground
  42203. * @param subdivisions defines the subdivisions to apply to the ground
  42204. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42205. * @param mesh defines the hosting mesh (can be null)
  42206. */
  42207. function GroundGeometry(id, scene,
  42208. /**
  42209. * Defines the width of the ground
  42210. */
  42211. width,
  42212. /**
  42213. * Defines the height of the ground
  42214. */
  42215. height,
  42216. /**
  42217. * Defines the subdivisions to apply to the ground
  42218. */
  42219. subdivisions, canBeRegenerated, mesh) {
  42220. if (mesh === void 0) { mesh = null; }
  42221. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42222. _this.width = width;
  42223. _this.height = height;
  42224. _this.subdivisions = subdivisions;
  42225. return _this;
  42226. }
  42227. /** @hidden */
  42228. GroundGeometry.prototype._regenerateVertexData = function () {
  42229. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42230. };
  42231. GroundGeometry.prototype.copy = function (id) {
  42232. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42233. };
  42234. GroundGeometry.prototype.serialize = function () {
  42235. var serializationObject = _super.prototype.serialize.call(this);
  42236. serializationObject.width = this.width;
  42237. serializationObject.height = this.height;
  42238. serializationObject.subdivisions = this.subdivisions;
  42239. return serializationObject;
  42240. };
  42241. GroundGeometry.Parse = function (parsedGround, scene) {
  42242. if (scene.getGeometryByID(parsedGround.id)) {
  42243. return null; // null since geometry could be something else than a ground...
  42244. }
  42245. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42246. if (BABYLON.Tags) {
  42247. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42248. }
  42249. scene.pushGeometry(ground, true);
  42250. return ground;
  42251. };
  42252. return GroundGeometry;
  42253. }(_PrimitiveGeometry));
  42254. BABYLON.GroundGeometry = GroundGeometry;
  42255. /**
  42256. * Creates a tiled ground geometry
  42257. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  42258. */
  42259. var TiledGroundGeometry = /** @class */ (function (_super) {
  42260. __extends(TiledGroundGeometry, _super);
  42261. /**
  42262. * Creates a tiled ground geometry
  42263. * @param id defines the unique ID of the geometry
  42264. * @param scene defines the hosting scene
  42265. * @param xmin defines the minimum value on X axis
  42266. * @param zmin defines the minimum value on Z axis
  42267. * @param xmax defines the maximum value on X axis
  42268. * @param zmax defines the maximum value on Z axis
  42269. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  42270. * @param precision defines the precision to use when computing the tiles
  42271. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42272. * @param mesh defines the hosting mesh (can be null)
  42273. */
  42274. function TiledGroundGeometry(id, scene,
  42275. /**
  42276. * Defines the minimum value on X axis
  42277. */
  42278. xmin,
  42279. /**
  42280. * Defines the minimum value on Z axis
  42281. */
  42282. zmin,
  42283. /**
  42284. * Defines the maximum value on X axis
  42285. */
  42286. xmax,
  42287. /**
  42288. * Defines the maximum value on Z axis
  42289. */
  42290. zmax,
  42291. /**
  42292. * Defines the subdivisions to apply to the ground
  42293. */
  42294. subdivisions,
  42295. /**
  42296. * Defines the precision to use when computing the tiles
  42297. */
  42298. precision, canBeRegenerated, mesh) {
  42299. if (mesh === void 0) { mesh = null; }
  42300. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42301. _this.xmin = xmin;
  42302. _this.zmin = zmin;
  42303. _this.xmax = xmax;
  42304. _this.zmax = zmax;
  42305. _this.subdivisions = subdivisions;
  42306. _this.precision = precision;
  42307. return _this;
  42308. }
  42309. /** @hidden */
  42310. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  42311. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42312. };
  42313. TiledGroundGeometry.prototype.copy = function (id) {
  42314. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42315. };
  42316. return TiledGroundGeometry;
  42317. }(_PrimitiveGeometry));
  42318. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  42319. /**
  42320. * Creates a plane geometry
  42321. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  42322. */
  42323. var PlaneGeometry = /** @class */ (function (_super) {
  42324. __extends(PlaneGeometry, _super);
  42325. /**
  42326. * Creates a plane geometry
  42327. * @param id defines the unique ID of the geometry
  42328. * @param scene defines the hosting scene
  42329. * @param size defines the size of the plane (width === height)
  42330. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42331. * @param mesh defines the hosting mesh (can be null)
  42332. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42333. */
  42334. function PlaneGeometry(id, scene,
  42335. /**
  42336. * Defines the size of the plane (width === height)
  42337. */
  42338. size, canBeRegenerated, mesh,
  42339. /**
  42340. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42341. */
  42342. side) {
  42343. if (mesh === void 0) { mesh = null; }
  42344. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42345. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42346. _this.size = size;
  42347. _this.side = side;
  42348. return _this;
  42349. }
  42350. /** @hidden */
  42351. PlaneGeometry.prototype._regenerateVertexData = function () {
  42352. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42353. };
  42354. PlaneGeometry.prototype.copy = function (id) {
  42355. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42356. };
  42357. PlaneGeometry.prototype.serialize = function () {
  42358. var serializationObject = _super.prototype.serialize.call(this);
  42359. serializationObject.size = this.size;
  42360. return serializationObject;
  42361. };
  42362. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42363. if (scene.getGeometryByID(parsedPlane.id)) {
  42364. return null; // null since geometry could be something else than a ground...
  42365. }
  42366. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42367. if (BABYLON.Tags) {
  42368. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42369. }
  42370. scene.pushGeometry(plane, true);
  42371. return plane;
  42372. };
  42373. return PlaneGeometry;
  42374. }(_PrimitiveGeometry));
  42375. BABYLON.PlaneGeometry = PlaneGeometry;
  42376. /**
  42377. * Creates a torus knot geometry
  42378. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42379. */
  42380. var TorusKnotGeometry = /** @class */ (function (_super) {
  42381. __extends(TorusKnotGeometry, _super);
  42382. /**
  42383. * Creates a torus knot geometry
  42384. * @param id defines the unique ID of the geometry
  42385. * @param scene defines the hosting scene
  42386. * @param radius defines the radius of the torus knot
  42387. * @param tube defines the thickness of the torus knot tube
  42388. * @param radialSegments defines the number of radial segments
  42389. * @param tubularSegments defines the number of tubular segments
  42390. * @param p defines the first number of windings
  42391. * @param q defines the second number of windings
  42392. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42393. * @param mesh defines the hosting mesh (can be null)
  42394. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42395. */
  42396. function TorusKnotGeometry(id, scene,
  42397. /**
  42398. * Defines the radius of the torus knot
  42399. */
  42400. radius,
  42401. /**
  42402. * Defines the thickness of the torus knot tube
  42403. */
  42404. tube,
  42405. /**
  42406. * Defines the number of radial segments
  42407. */
  42408. radialSegments,
  42409. /**
  42410. * Defines the number of tubular segments
  42411. */
  42412. tubularSegments,
  42413. /**
  42414. * Defines the first number of windings
  42415. */
  42416. p,
  42417. /**
  42418. * Defines the second number of windings
  42419. */
  42420. q, canBeRegenerated, mesh,
  42421. /**
  42422. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42423. */
  42424. side) {
  42425. if (mesh === void 0) { mesh = null; }
  42426. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42427. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42428. _this.radius = radius;
  42429. _this.tube = tube;
  42430. _this.radialSegments = radialSegments;
  42431. _this.tubularSegments = tubularSegments;
  42432. _this.p = p;
  42433. _this.q = q;
  42434. _this.side = side;
  42435. return _this;
  42436. }
  42437. /** @hidden */
  42438. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42439. 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 });
  42440. };
  42441. TorusKnotGeometry.prototype.copy = function (id) {
  42442. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42443. };
  42444. TorusKnotGeometry.prototype.serialize = function () {
  42445. var serializationObject = _super.prototype.serialize.call(this);
  42446. serializationObject.radius = this.radius;
  42447. serializationObject.tube = this.tube;
  42448. serializationObject.radialSegments = this.radialSegments;
  42449. serializationObject.tubularSegments = this.tubularSegments;
  42450. serializationObject.p = this.p;
  42451. serializationObject.q = this.q;
  42452. return serializationObject;
  42453. };
  42454. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42455. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42456. return null; // null since geometry could be something else than a ground...
  42457. }
  42458. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42459. if (BABYLON.Tags) {
  42460. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42461. }
  42462. scene.pushGeometry(torusKnot, true);
  42463. return torusKnot;
  42464. };
  42465. return TorusKnotGeometry;
  42466. }(_PrimitiveGeometry));
  42467. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42468. //}
  42469. })(BABYLON || (BABYLON = {}));
  42470. //# sourceMappingURL=babylon.geometry.js.map
  42471. var BABYLON;
  42472. (function (BABYLON) {
  42473. /**
  42474. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42475. */
  42476. var PerformanceMonitor = /** @class */ (function () {
  42477. /**
  42478. * constructor
  42479. * @param frameSampleSize The number of samples required to saturate the sliding window
  42480. */
  42481. function PerformanceMonitor(frameSampleSize) {
  42482. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42483. this._enabled = true;
  42484. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42485. }
  42486. /**
  42487. * Samples current frame
  42488. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42489. */
  42490. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42491. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42492. if (!this._enabled) {
  42493. return;
  42494. }
  42495. if (this._lastFrameTimeMs != null) {
  42496. var dt = timeMs - this._lastFrameTimeMs;
  42497. this._rollingFrameTime.add(dt);
  42498. }
  42499. this._lastFrameTimeMs = timeMs;
  42500. };
  42501. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42502. /**
  42503. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42504. */
  42505. get: function () {
  42506. return this._rollingFrameTime.average;
  42507. },
  42508. enumerable: true,
  42509. configurable: true
  42510. });
  42511. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42512. /**
  42513. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42514. */
  42515. get: function () {
  42516. return this._rollingFrameTime.variance;
  42517. },
  42518. enumerable: true,
  42519. configurable: true
  42520. });
  42521. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42522. /**
  42523. * Returns the frame time of the most recent frame
  42524. */
  42525. get: function () {
  42526. return this._rollingFrameTime.history(0);
  42527. },
  42528. enumerable: true,
  42529. configurable: true
  42530. });
  42531. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42532. /**
  42533. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42534. */
  42535. get: function () {
  42536. return 1000.0 / this._rollingFrameTime.average;
  42537. },
  42538. enumerable: true,
  42539. configurable: true
  42540. });
  42541. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42542. /**
  42543. * Returns the average framerate in frames per second using the most recent frame time
  42544. */
  42545. get: function () {
  42546. var history = this._rollingFrameTime.history(0);
  42547. if (history === 0) {
  42548. return 0;
  42549. }
  42550. return 1000.0 / history;
  42551. },
  42552. enumerable: true,
  42553. configurable: true
  42554. });
  42555. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42556. /**
  42557. * Returns true if enough samples have been taken to completely fill the sliding window
  42558. */
  42559. get: function () {
  42560. return this._rollingFrameTime.isSaturated();
  42561. },
  42562. enumerable: true,
  42563. configurable: true
  42564. });
  42565. /**
  42566. * Enables contributions to the sliding window sample set
  42567. */
  42568. PerformanceMonitor.prototype.enable = function () {
  42569. this._enabled = true;
  42570. };
  42571. /**
  42572. * Disables contributions to the sliding window sample set
  42573. * Samples will not be interpolated over the disabled period
  42574. */
  42575. PerformanceMonitor.prototype.disable = function () {
  42576. this._enabled = false;
  42577. //clear last sample to avoid interpolating over the disabled period when next enabled
  42578. this._lastFrameTimeMs = null;
  42579. };
  42580. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42581. /**
  42582. * Returns true if sampling is enabled
  42583. */
  42584. get: function () {
  42585. return this._enabled;
  42586. },
  42587. enumerable: true,
  42588. configurable: true
  42589. });
  42590. /**
  42591. * Resets performance monitor
  42592. */
  42593. PerformanceMonitor.prototype.reset = function () {
  42594. //clear last sample to avoid interpolating over the disabled period when next enabled
  42595. this._lastFrameTimeMs = null;
  42596. //wipe record
  42597. this._rollingFrameTime.reset();
  42598. };
  42599. return PerformanceMonitor;
  42600. }());
  42601. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42602. /**
  42603. * RollingAverage
  42604. *
  42605. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42606. */
  42607. var RollingAverage = /** @class */ (function () {
  42608. /**
  42609. * constructor
  42610. * @param length The number of samples required to saturate the sliding window
  42611. */
  42612. function RollingAverage(length) {
  42613. this._samples = new Array(length);
  42614. this.reset();
  42615. }
  42616. /**
  42617. * Adds a sample to the sample set
  42618. * @param v The sample value
  42619. */
  42620. RollingAverage.prototype.add = function (v) {
  42621. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42622. var delta;
  42623. //we need to check if we've already wrapped round
  42624. if (this.isSaturated()) {
  42625. //remove bottom of stack from mean
  42626. var bottomValue = this._samples[this._pos];
  42627. delta = bottomValue - this.average;
  42628. this.average -= delta / (this._sampleCount - 1);
  42629. this._m2 -= delta * (bottomValue - this.average);
  42630. }
  42631. else {
  42632. this._sampleCount++;
  42633. }
  42634. //add new value to mean
  42635. delta = v - this.average;
  42636. this.average += delta / (this._sampleCount);
  42637. this._m2 += delta * (v - this.average);
  42638. //set the new variance
  42639. this.variance = this._m2 / (this._sampleCount - 1);
  42640. this._samples[this._pos] = v;
  42641. this._pos++;
  42642. this._pos %= this._samples.length; //positive wrap around
  42643. };
  42644. /**
  42645. * Returns previously added values or null if outside of history or outside the sliding window domain
  42646. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42647. * @return Value previously recorded with add() or null if outside of range
  42648. */
  42649. RollingAverage.prototype.history = function (i) {
  42650. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42651. return 0;
  42652. }
  42653. var i0 = this._wrapPosition(this._pos - 1.0);
  42654. return this._samples[this._wrapPosition(i0 - i)];
  42655. };
  42656. /**
  42657. * Returns true if enough samples have been taken to completely fill the sliding window
  42658. * @return true if sample-set saturated
  42659. */
  42660. RollingAverage.prototype.isSaturated = function () {
  42661. return this._sampleCount >= this._samples.length;
  42662. };
  42663. /**
  42664. * Resets the rolling average (equivalent to 0 samples taken so far)
  42665. */
  42666. RollingAverage.prototype.reset = function () {
  42667. this.average = 0;
  42668. this.variance = 0;
  42669. this._sampleCount = 0;
  42670. this._pos = 0;
  42671. this._m2 = 0;
  42672. };
  42673. /**
  42674. * Wraps a value around the sample range boundaries
  42675. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42676. * @return Wrapped position in sample range
  42677. */
  42678. RollingAverage.prototype._wrapPosition = function (i) {
  42679. var max = this._samples.length;
  42680. return ((i % max) + max) % max;
  42681. };
  42682. return RollingAverage;
  42683. }());
  42684. BABYLON.RollingAverage = RollingAverage;
  42685. })(BABYLON || (BABYLON = {}));
  42686. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42687. var BABYLON;
  42688. (function (BABYLON) {
  42689. /**
  42690. * "Static Class" containing the most commonly used helper while dealing with material for
  42691. * rendering purpose.
  42692. *
  42693. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42694. *
  42695. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42696. */
  42697. var MaterialHelper = /** @class */ (function () {
  42698. function MaterialHelper() {
  42699. }
  42700. /**
  42701. * Bind the current view position to an effect.
  42702. * @param effect The effect to be bound
  42703. * @param scene The scene the eyes position is used from
  42704. */
  42705. MaterialHelper.BindEyePosition = function (effect, scene) {
  42706. if (scene._forcedViewPosition) {
  42707. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42708. return;
  42709. }
  42710. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42711. };
  42712. /**
  42713. * Helps preparing the defines values about the UVs in used in the effect.
  42714. * UVs are shared as much as we can accross channels in the shaders.
  42715. * @param texture The texture we are preparing the UVs for
  42716. * @param defines The defines to update
  42717. * @param key The channel key "diffuse", "specular"... used in the shader
  42718. */
  42719. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42720. defines._needUVs = true;
  42721. defines[key] = true;
  42722. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  42723. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42724. if (texture.coordinatesIndex === 0) {
  42725. defines["MAINUV1"] = true;
  42726. }
  42727. else {
  42728. defines["MAINUV2"] = true;
  42729. }
  42730. }
  42731. else {
  42732. defines[key + "DIRECTUV"] = 0;
  42733. }
  42734. };
  42735. /**
  42736. * Binds a texture matrix value to its corrsponding uniform
  42737. * @param texture The texture to bind the matrix for
  42738. * @param uniformBuffer The uniform buffer receivin the data
  42739. * @param key The channel key "diffuse", "specular"... used in the shader
  42740. */
  42741. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42742. var matrix = texture.getTextureMatrix();
  42743. if (!matrix.isIdentityAs3x2()) {
  42744. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42745. }
  42746. };
  42747. /**
  42748. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42749. * @param mesh defines the current mesh
  42750. * @param scene defines the current scene
  42751. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42752. * @param pointsCloud defines if point cloud rendering has to be turned on
  42753. * @param fogEnabled defines if fog has to be turned on
  42754. * @param alphaTest defines if alpha testing has to be turned on
  42755. * @param defines defines the current list of defines
  42756. */
  42757. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42758. if (defines._areMiscDirty) {
  42759. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42760. defines["POINTSIZE"] = pointsCloud;
  42761. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42762. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42763. defines["ALPHATEST"] = alphaTest;
  42764. }
  42765. };
  42766. /**
  42767. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42768. * @param scene defines the current scene
  42769. * @param engine defines the current engine
  42770. * @param defines specifies the list of active defines
  42771. * @param useInstances defines if instances have to be turned on
  42772. * @param useClipPlane defines if clip plane have to be turned on
  42773. */
  42774. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42775. if (useClipPlane === void 0) { useClipPlane = null; }
  42776. var changed = false;
  42777. var useClipPlane1 = false;
  42778. var useClipPlane2 = false;
  42779. var useClipPlane3 = false;
  42780. var useClipPlane4 = false;
  42781. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42782. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42783. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42784. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42785. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42786. defines["CLIPPLANE"] = useClipPlane1;
  42787. changed = true;
  42788. }
  42789. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42790. defines["CLIPPLANE2"] = useClipPlane2;
  42791. changed = true;
  42792. }
  42793. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42794. defines["CLIPPLANE3"] = useClipPlane3;
  42795. changed = true;
  42796. }
  42797. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42798. defines["CLIPPLANE4"] = useClipPlane4;
  42799. changed = true;
  42800. }
  42801. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42802. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42803. changed = true;
  42804. }
  42805. if (defines["INSTANCES"] !== useInstances) {
  42806. defines["INSTANCES"] = useInstances;
  42807. changed = true;
  42808. }
  42809. if (changed) {
  42810. defines.markAsUnprocessed();
  42811. }
  42812. };
  42813. /**
  42814. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42815. * @param mesh The mesh containing the geometry data we will draw
  42816. * @param defines The defines to update
  42817. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42818. * @param useBones Precise whether bones should be used or not (override mesh info)
  42819. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42820. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42821. * @returns false if defines are considered not dirty and have not been checked
  42822. */
  42823. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42824. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42825. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42826. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42827. return false;
  42828. }
  42829. defines._normals = defines._needNormals;
  42830. defines._uvs = defines._needUVs;
  42831. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42832. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42833. defines["TANGENT"] = true;
  42834. }
  42835. if (defines._needUVs) {
  42836. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42837. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42838. }
  42839. else {
  42840. defines["UV1"] = false;
  42841. defines["UV2"] = false;
  42842. }
  42843. if (useVertexColor) {
  42844. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42845. defines["VERTEXCOLOR"] = hasVertexColors;
  42846. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42847. }
  42848. if (useBones) {
  42849. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42850. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42851. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42852. }
  42853. else {
  42854. defines["NUM_BONE_INFLUENCERS"] = 0;
  42855. defines["BonesPerMesh"] = 0;
  42856. }
  42857. }
  42858. if (useMorphTargets) {
  42859. var manager = mesh.morphTargetManager;
  42860. if (manager) {
  42861. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42862. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42863. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42864. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42865. }
  42866. else {
  42867. defines["MORPHTARGETS_TANGENT"] = false;
  42868. defines["MORPHTARGETS_NORMAL"] = false;
  42869. defines["MORPHTARGETS"] = false;
  42870. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42871. }
  42872. }
  42873. return true;
  42874. };
  42875. /**
  42876. * Prepares the defines related to the light information passed in parameter
  42877. * @param scene The scene we are intending to draw
  42878. * @param mesh The mesh the effect is compiling for
  42879. * @param defines The defines to update
  42880. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42881. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42882. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42883. * @returns true if normals will be required for the rest of the effect
  42884. */
  42885. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42886. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42887. if (disableLighting === void 0) { disableLighting = false; }
  42888. if (!defines._areLightsDirty) {
  42889. return defines._needNormals;
  42890. }
  42891. var lightIndex = 0;
  42892. var needNormals = false;
  42893. var needRebuild = false;
  42894. var lightmapMode = false;
  42895. var shadowEnabled = false;
  42896. var specularEnabled = false;
  42897. if (scene.lightsEnabled && !disableLighting) {
  42898. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42899. var light = _a[_i];
  42900. needNormals = true;
  42901. if (defines["LIGHT" + lightIndex] === undefined) {
  42902. needRebuild = true;
  42903. }
  42904. defines["LIGHT" + lightIndex] = true;
  42905. defines["SPOTLIGHT" + lightIndex] = false;
  42906. defines["HEMILIGHT" + lightIndex] = false;
  42907. defines["POINTLIGHT" + lightIndex] = false;
  42908. defines["DIRLIGHT" + lightIndex] = false;
  42909. light.prepareLightSpecificDefines(defines, lightIndex);
  42910. // FallOff.
  42911. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42912. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42913. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42914. switch (light.falloffType) {
  42915. case BABYLON.Light.FALLOFF_GLTF:
  42916. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42917. break;
  42918. case BABYLON.Light.FALLOFF_PHYSICAL:
  42919. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42920. break;
  42921. case BABYLON.Light.FALLOFF_STANDARD:
  42922. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42923. break;
  42924. }
  42925. // Specular
  42926. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42927. specularEnabled = true;
  42928. }
  42929. // Shadows
  42930. defines["SHADOW" + lightIndex] = false;
  42931. defines["SHADOWPCF" + lightIndex] = false;
  42932. defines["SHADOWPCSS" + lightIndex] = false;
  42933. defines["SHADOWPOISSON" + lightIndex] = false;
  42934. defines["SHADOWESM" + lightIndex] = false;
  42935. defines["SHADOWCUBE" + lightIndex] = false;
  42936. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42937. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42938. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42939. var shadowGenerator = light.getShadowGenerator();
  42940. if (shadowGenerator) {
  42941. var shadowMap = shadowGenerator.getShadowMap();
  42942. if (shadowMap) {
  42943. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42944. shadowEnabled = true;
  42945. shadowGenerator.prepareDefines(defines, lightIndex);
  42946. }
  42947. }
  42948. }
  42949. }
  42950. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42951. lightmapMode = true;
  42952. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42953. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42954. }
  42955. else {
  42956. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42957. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42958. }
  42959. lightIndex++;
  42960. if (lightIndex === maxSimultaneousLights) {
  42961. break;
  42962. }
  42963. }
  42964. }
  42965. defines["SPECULARTERM"] = specularEnabled;
  42966. defines["SHADOWS"] = shadowEnabled;
  42967. // Resetting all other lights if any
  42968. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42969. if (defines["LIGHT" + index] !== undefined) {
  42970. defines["LIGHT" + index] = false;
  42971. defines["HEMILIGHT" + lightIndex] = false;
  42972. defines["POINTLIGHT" + lightIndex] = false;
  42973. defines["DIRLIGHT" + lightIndex] = false;
  42974. defines["SPOTLIGHT" + lightIndex] = false;
  42975. defines["SHADOW" + lightIndex] = false;
  42976. }
  42977. }
  42978. var caps = scene.getEngine().getCaps();
  42979. if (defines["SHADOWFLOAT"] === undefined) {
  42980. needRebuild = true;
  42981. }
  42982. defines["SHADOWFLOAT"] = shadowEnabled &&
  42983. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42984. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42985. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42986. if (needRebuild) {
  42987. defines.rebuild();
  42988. }
  42989. return needNormals;
  42990. };
  42991. /**
  42992. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42993. * that won t be acctive due to defines being turned off.
  42994. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42995. * @param samplersList The samplers list
  42996. * @param defines The defines helping in the list generation
  42997. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42998. */
  42999. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  43000. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43001. var uniformsList;
  43002. var uniformBuffersList = null;
  43003. if (uniformsListOrOptions.uniformsNames) {
  43004. var options = uniformsListOrOptions;
  43005. uniformsList = options.uniformsNames;
  43006. uniformBuffersList = options.uniformBuffersNames;
  43007. samplersList = options.samplers;
  43008. defines = options.defines;
  43009. maxSimultaneousLights = options.maxSimultaneousLights;
  43010. }
  43011. else {
  43012. uniformsList = uniformsListOrOptions;
  43013. if (!samplersList) {
  43014. samplersList = [];
  43015. }
  43016. }
  43017. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43018. if (!defines["LIGHT" + lightIndex]) {
  43019. break;
  43020. }
  43021. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  43022. if (uniformBuffersList) {
  43023. uniformBuffersList.push("Light" + lightIndex);
  43024. }
  43025. samplersList.push("shadowSampler" + lightIndex);
  43026. samplersList.push("depthSampler" + lightIndex);
  43027. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  43028. samplersList.push("projectionLightSampler" + lightIndex);
  43029. uniformsList.push("textureProjectionMatrix" + lightIndex);
  43030. }
  43031. }
  43032. if (defines["NUM_MORPH_INFLUENCERS"]) {
  43033. uniformsList.push("morphTargetInfluences");
  43034. }
  43035. };
  43036. /**
  43037. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  43038. * @param defines The defines to update while falling back
  43039. * @param fallbacks The authorized effect fallbacks
  43040. * @param maxSimultaneousLights The maximum number of lights allowed
  43041. * @param rank the current rank of the Effect
  43042. * @returns The newly affected rank
  43043. */
  43044. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  43045. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43046. if (rank === void 0) { rank = 0; }
  43047. var lightFallbackRank = 0;
  43048. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43049. if (!defines["LIGHT" + lightIndex]) {
  43050. break;
  43051. }
  43052. if (lightIndex > 0) {
  43053. lightFallbackRank = rank + lightIndex;
  43054. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  43055. }
  43056. if (!defines["SHADOWS"]) {
  43057. if (defines["SHADOW" + lightIndex]) {
  43058. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  43059. }
  43060. if (defines["SHADOWPCF" + lightIndex]) {
  43061. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  43062. }
  43063. if (defines["SHADOWPCSS" + lightIndex]) {
  43064. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  43065. }
  43066. if (defines["SHADOWPOISSON" + lightIndex]) {
  43067. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  43068. }
  43069. if (defines["SHADOWESM" + lightIndex]) {
  43070. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  43071. }
  43072. }
  43073. }
  43074. return lightFallbackRank++;
  43075. };
  43076. /**
  43077. * Prepares the list of attributes required for morph targets according to the effect defines.
  43078. * @param attribs The current list of supported attribs
  43079. * @param mesh The mesh to prepare the morph targets attributes for
  43080. * @param defines The current Defines of the effect
  43081. */
  43082. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  43083. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  43084. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  43085. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  43086. var manager = mesh.morphTargetManager;
  43087. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  43088. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  43089. for (var index = 0; index < influencers; index++) {
  43090. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  43091. if (normal) {
  43092. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  43093. }
  43094. if (tangent) {
  43095. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  43096. }
  43097. if (attribs.length > maxAttributesCount) {
  43098. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  43099. }
  43100. }
  43101. }
  43102. };
  43103. /**
  43104. * Prepares the list of attributes required for bones according to the effect defines.
  43105. * @param attribs The current list of supported attribs
  43106. * @param mesh The mesh to prepare the bones attributes for
  43107. * @param defines The current Defines of the effect
  43108. * @param fallbacks The current efffect fallback strategy
  43109. */
  43110. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  43111. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  43112. fallbacks.addCPUSkinningFallback(0, mesh);
  43113. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43114. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43115. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43116. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43117. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43118. }
  43119. }
  43120. };
  43121. /**
  43122. * Prepares the list of attributes required for instances according to the effect defines.
  43123. * @param attribs The current list of supported attribs
  43124. * @param defines The current Defines of the effect
  43125. */
  43126. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43127. if (defines["INSTANCES"]) {
  43128. attribs.push("world0");
  43129. attribs.push("world1");
  43130. attribs.push("world2");
  43131. attribs.push("world3");
  43132. }
  43133. };
  43134. /**
  43135. * Binds the light shadow information to the effect for the given mesh.
  43136. * @param light The light containing the generator
  43137. * @param scene The scene the lights belongs to
  43138. * @param mesh The mesh we are binding the information to render
  43139. * @param lightIndex The light index in the effect used to render the mesh
  43140. * @param effect The effect we are binding the data to
  43141. */
  43142. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43143. if (light.shadowEnabled && mesh.receiveShadows) {
  43144. var shadowGenerator = light.getShadowGenerator();
  43145. if (shadowGenerator) {
  43146. shadowGenerator.bindShadowLight(lightIndex, effect);
  43147. }
  43148. }
  43149. };
  43150. /**
  43151. * Binds the light information to the effect.
  43152. * @param light The light containing the generator
  43153. * @param effect The effect we are binding the data to
  43154. * @param lightIndex The light index in the effect used to render
  43155. */
  43156. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43157. light.transferToEffect(effect, lightIndex + "");
  43158. };
  43159. /**
  43160. * Binds the lights information from the scene to the effect for the given mesh.
  43161. * @param scene The scene the lights belongs to
  43162. * @param mesh The mesh we are binding the information to render
  43163. * @param effect The effect we are binding the data to
  43164. * @param defines The generated defines for the effect
  43165. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43166. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43167. */
  43168. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43169. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43170. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43171. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43172. for (var i = 0; i < len; i++) {
  43173. var light = mesh._lightSources[i];
  43174. var iAsString = i.toString();
  43175. var scaledIntensity = light.getScaledIntensity();
  43176. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43177. MaterialHelper.BindLightProperties(light, effect, i);
  43178. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43179. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43180. if (defines["SPECULARTERM"]) {
  43181. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43182. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43183. }
  43184. // Shadows
  43185. if (scene.shadowsEnabled) {
  43186. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43187. }
  43188. light._uniformBuffer.update();
  43189. }
  43190. };
  43191. /**
  43192. * Binds the fog information from the scene to the effect for the given mesh.
  43193. * @param scene The scene the lights belongs to
  43194. * @param mesh The mesh we are binding the information to render
  43195. * @param effect The effect we are binding the data to
  43196. * @param linearSpace Defines if the fog effect is applied in linear space
  43197. */
  43198. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  43199. if (linearSpace === void 0) { linearSpace = false; }
  43200. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43201. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43202. // Convert fog color to linear space if used in a linear space computed shader.
  43203. if (linearSpace) {
  43204. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  43205. effect.setColor3("vFogColor", this._tempFogColor);
  43206. }
  43207. else {
  43208. effect.setColor3("vFogColor", scene.fogColor);
  43209. }
  43210. }
  43211. };
  43212. /**
  43213. * Binds the bones information from the mesh to the effect.
  43214. * @param mesh The mesh we are binding the information to render
  43215. * @param effect The effect we are binding the data to
  43216. */
  43217. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43218. if (!effect || !mesh) {
  43219. return;
  43220. }
  43221. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43222. mesh.computeBonesUsingShaders = false;
  43223. }
  43224. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43225. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43226. if (matrices) {
  43227. effect.setMatrices("mBones", matrices);
  43228. }
  43229. }
  43230. };
  43231. /**
  43232. * Binds the morph targets information from the mesh to the effect.
  43233. * @param abstractMesh The mesh we are binding the information to render
  43234. * @param effect The effect we are binding the data to
  43235. */
  43236. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43237. var manager = abstractMesh.morphTargetManager;
  43238. if (!abstractMesh || !manager) {
  43239. return;
  43240. }
  43241. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43242. };
  43243. /**
  43244. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43245. * @param defines The generated defines used in the effect
  43246. * @param effect The effect we are binding the data to
  43247. * @param scene The scene we are willing to render with logarithmic scale for
  43248. */
  43249. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43250. if (defines["LOGARITHMICDEPTH"]) {
  43251. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43252. }
  43253. };
  43254. /**
  43255. * Binds the clip plane information from the scene to the effect.
  43256. * @param scene The scene the clip plane information are extracted from
  43257. * @param effect The effect we are binding the data to
  43258. */
  43259. MaterialHelper.BindClipPlane = function (effect, scene) {
  43260. if (scene.clipPlane) {
  43261. var clipPlane = scene.clipPlane;
  43262. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43263. }
  43264. if (scene.clipPlane2) {
  43265. var clipPlane = scene.clipPlane2;
  43266. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43267. }
  43268. if (scene.clipPlane3) {
  43269. var clipPlane = scene.clipPlane3;
  43270. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43271. }
  43272. if (scene.clipPlane4) {
  43273. var clipPlane = scene.clipPlane4;
  43274. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43275. }
  43276. };
  43277. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  43278. return MaterialHelper;
  43279. }());
  43280. BABYLON.MaterialHelper = MaterialHelper;
  43281. })(BABYLON || (BABYLON = {}));
  43282. //# sourceMappingURL=babylon.materialHelper.js.map
  43283. var BABYLON;
  43284. (function (BABYLON) {
  43285. /**
  43286. * Base class of materials working in push mode in babylon JS
  43287. * @hidden
  43288. */
  43289. var PushMaterial = /** @class */ (function (_super) {
  43290. __extends(PushMaterial, _super);
  43291. function PushMaterial(name, scene) {
  43292. var _this = _super.call(this, name, scene) || this;
  43293. _this._normalMatrix = new BABYLON.Matrix();
  43294. /**
  43295. * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping.
  43296. * This means that the material can keep using a previous shader while a new one is being compiled.
  43297. * This is mostly used when shader parallel compilation is supported (true by default)
  43298. */
  43299. _this.allowShaderHotSwapping = true;
  43300. _this._storeEffectOnSubMeshes = true;
  43301. return _this;
  43302. }
  43303. PushMaterial.prototype.getEffect = function () {
  43304. return this._activeEffect;
  43305. };
  43306. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43307. if (!mesh) {
  43308. return false;
  43309. }
  43310. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43311. return true;
  43312. }
  43313. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43314. };
  43315. /**
  43316. * Binds the given world matrix to the active effect
  43317. *
  43318. * @param world the matrix to bind
  43319. */
  43320. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43321. this._activeEffect.setMatrix("world", world);
  43322. };
  43323. /**
  43324. * Binds the given normal matrix to the active effect
  43325. *
  43326. * @param normalMatrix the matrix to bind
  43327. */
  43328. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43329. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43330. };
  43331. PushMaterial.prototype.bind = function (world, mesh) {
  43332. if (!mesh) {
  43333. return;
  43334. }
  43335. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43336. };
  43337. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43338. if (effect === void 0) { effect = null; }
  43339. _super.prototype._afterBind.call(this, mesh);
  43340. this.getScene()._cachedEffect = effect;
  43341. };
  43342. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43343. if (visibility === void 0) { visibility = 1; }
  43344. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43345. };
  43346. return PushMaterial;
  43347. }(BABYLON.Material));
  43348. BABYLON.PushMaterial = PushMaterial;
  43349. })(BABYLON || (BABYLON = {}));
  43350. //# sourceMappingURL=babylon.pushMaterial.js.map
  43351. var BABYLON;
  43352. (function (BABYLON) {
  43353. /** @hidden */
  43354. var StandardMaterialDefines = /** @class */ (function (_super) {
  43355. __extends(StandardMaterialDefines, _super);
  43356. function StandardMaterialDefines() {
  43357. var _this = _super.call(this) || this;
  43358. _this.MAINUV1 = false;
  43359. _this.MAINUV2 = false;
  43360. _this.DIFFUSE = false;
  43361. _this.DIFFUSEDIRECTUV = 0;
  43362. _this.AMBIENT = false;
  43363. _this.AMBIENTDIRECTUV = 0;
  43364. _this.OPACITY = false;
  43365. _this.OPACITYDIRECTUV = 0;
  43366. _this.OPACITYRGB = false;
  43367. _this.REFLECTION = false;
  43368. _this.EMISSIVE = false;
  43369. _this.EMISSIVEDIRECTUV = 0;
  43370. _this.SPECULAR = false;
  43371. _this.SPECULARDIRECTUV = 0;
  43372. _this.BUMP = false;
  43373. _this.BUMPDIRECTUV = 0;
  43374. _this.PARALLAX = false;
  43375. _this.PARALLAXOCCLUSION = false;
  43376. _this.SPECULAROVERALPHA = false;
  43377. _this.CLIPPLANE = false;
  43378. _this.CLIPPLANE2 = false;
  43379. _this.CLIPPLANE3 = false;
  43380. _this.CLIPPLANE4 = false;
  43381. _this.ALPHATEST = false;
  43382. _this.DEPTHPREPASS = false;
  43383. _this.ALPHAFROMDIFFUSE = false;
  43384. _this.POINTSIZE = false;
  43385. _this.FOG = false;
  43386. _this.SPECULARTERM = false;
  43387. _this.DIFFUSEFRESNEL = false;
  43388. _this.OPACITYFRESNEL = false;
  43389. _this.REFLECTIONFRESNEL = false;
  43390. _this.REFRACTIONFRESNEL = false;
  43391. _this.EMISSIVEFRESNEL = false;
  43392. _this.FRESNEL = false;
  43393. _this.NORMAL = false;
  43394. _this.UV1 = false;
  43395. _this.UV2 = false;
  43396. _this.VERTEXCOLOR = false;
  43397. _this.VERTEXALPHA = false;
  43398. _this.NUM_BONE_INFLUENCERS = 0;
  43399. _this.BonesPerMesh = 0;
  43400. _this.INSTANCES = false;
  43401. _this.GLOSSINESS = false;
  43402. _this.ROUGHNESS = false;
  43403. _this.EMISSIVEASILLUMINATION = false;
  43404. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43405. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43406. _this.LIGHTMAP = false;
  43407. _this.LIGHTMAPDIRECTUV = 0;
  43408. _this.OBJECTSPACE_NORMALMAP = false;
  43409. _this.USELIGHTMAPASSHADOWMAP = false;
  43410. _this.REFLECTIONMAP_3D = false;
  43411. _this.REFLECTIONMAP_SPHERICAL = false;
  43412. _this.REFLECTIONMAP_PLANAR = false;
  43413. _this.REFLECTIONMAP_CUBIC = false;
  43414. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43415. _this.REFLECTIONMAP_PROJECTION = false;
  43416. _this.REFLECTIONMAP_SKYBOX = false;
  43417. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43418. _this.REFLECTIONMAP_EXPLICIT = false;
  43419. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43420. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43421. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43422. _this.INVERTCUBICMAP = false;
  43423. _this.LOGARITHMICDEPTH = false;
  43424. _this.REFRACTION = false;
  43425. _this.REFRACTIONMAP_3D = false;
  43426. _this.REFLECTIONOVERALPHA = false;
  43427. _this.TWOSIDEDLIGHTING = false;
  43428. _this.SHADOWFLOAT = false;
  43429. _this.MORPHTARGETS = false;
  43430. _this.MORPHTARGETS_NORMAL = false;
  43431. _this.MORPHTARGETS_TANGENT = false;
  43432. _this.NUM_MORPH_INFLUENCERS = 0;
  43433. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43434. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43435. _this.IMAGEPROCESSING = false;
  43436. _this.VIGNETTE = false;
  43437. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43438. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43439. _this.TONEMAPPING = false;
  43440. _this.TONEMAPPING_ACES = false;
  43441. _this.CONTRAST = false;
  43442. _this.COLORCURVES = false;
  43443. _this.COLORGRADING = false;
  43444. _this.COLORGRADING3D = false;
  43445. _this.SAMPLER3DGREENDEPTH = false;
  43446. _this.SAMPLER3DBGRMAP = false;
  43447. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43448. /**
  43449. * If the reflection texture on this material is in linear color space
  43450. * @hidden
  43451. */
  43452. _this.IS_REFLECTION_LINEAR = false;
  43453. /**
  43454. * If the refraction texture on this material is in linear color space
  43455. * @hidden
  43456. */
  43457. _this.IS_REFRACTION_LINEAR = false;
  43458. _this.EXPOSURE = false;
  43459. _this.rebuild();
  43460. return _this;
  43461. }
  43462. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43463. var modes = [
  43464. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43465. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43466. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43467. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43468. ];
  43469. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43470. var mode = modes_1[_i];
  43471. this[mode] = (mode === modeToEnable);
  43472. }
  43473. };
  43474. return StandardMaterialDefines;
  43475. }(BABYLON.MaterialDefines));
  43476. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43477. /**
  43478. * This is the default material used in Babylon. It is the best trade off between quality
  43479. * and performances.
  43480. * @see http://doc.babylonjs.com/babylon101/materials
  43481. */
  43482. var StandardMaterial = /** @class */ (function (_super) {
  43483. __extends(StandardMaterial, _super);
  43484. /**
  43485. * Instantiates a new standard material.
  43486. * This is the default material used in Babylon. It is the best trade off between quality
  43487. * and performances.
  43488. * @see http://doc.babylonjs.com/babylon101/materials
  43489. * @param name Define the name of the material in the scene
  43490. * @param scene Define the scene the material belong to
  43491. */
  43492. function StandardMaterial(name, scene) {
  43493. var _this = _super.call(this, name, scene) || this;
  43494. /**
  43495. * The color of the material lit by the environmental background lighting.
  43496. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43497. */
  43498. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43499. /**
  43500. * The basic color of the material as viewed under a light.
  43501. */
  43502. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43503. /**
  43504. * Define how the color and intensity of the highlight given by the light in the material.
  43505. */
  43506. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43507. /**
  43508. * Define the color of the material as if self lit.
  43509. * This will be mixed in the final result even in the absence of light.
  43510. */
  43511. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43512. /**
  43513. * Defines how sharp are the highlights in the material.
  43514. * The bigger the value the sharper giving a more glossy feeling to the result.
  43515. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43516. */
  43517. _this.specularPower = 64;
  43518. _this._useAlphaFromDiffuseTexture = false;
  43519. _this._useEmissiveAsIllumination = false;
  43520. _this._linkEmissiveWithDiffuse = false;
  43521. _this._useSpecularOverAlpha = false;
  43522. _this._useReflectionOverAlpha = false;
  43523. _this._disableLighting = false;
  43524. _this._useObjectSpaceNormalMap = false;
  43525. _this._useParallax = false;
  43526. _this._useParallaxOcclusion = false;
  43527. /**
  43528. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  43529. */
  43530. _this.parallaxScaleBias = 0.05;
  43531. _this._roughness = 0;
  43532. /**
  43533. * In case of refraction, define the value of the indice of refraction.
  43534. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43535. */
  43536. _this.indexOfRefraction = 0.98;
  43537. /**
  43538. * Invert the refraction texture alongside the y axis.
  43539. * It can be usefull with procedural textures or probe for instance.
  43540. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43541. */
  43542. _this.invertRefractionY = true;
  43543. /**
  43544. * Defines the alpha limits in alpha test mode.
  43545. */
  43546. _this.alphaCutOff = 0.4;
  43547. _this._useLightmapAsShadowmap = false;
  43548. _this._useReflectionFresnelFromSpecular = false;
  43549. _this._useGlossinessFromSpecularMapAlpha = false;
  43550. _this._maxSimultaneousLights = 4;
  43551. _this._invertNormalMapX = false;
  43552. _this._invertNormalMapY = false;
  43553. _this._twoSidedLighting = false;
  43554. _this._renderTargets = new BABYLON.SmartArray(16);
  43555. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43556. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43557. // Setup the default processing configuration to the scene.
  43558. _this._attachImageProcessingConfiguration(null);
  43559. _this.getRenderTargetTextures = function () {
  43560. _this._renderTargets.reset();
  43561. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43562. _this._renderTargets.push(_this._reflectionTexture);
  43563. }
  43564. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43565. _this._renderTargets.push(_this._refractionTexture);
  43566. }
  43567. return _this._renderTargets;
  43568. };
  43569. return _this;
  43570. }
  43571. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43572. /**
  43573. * Gets the image processing configuration used either in this material.
  43574. */
  43575. get: function () {
  43576. return this._imageProcessingConfiguration;
  43577. },
  43578. /**
  43579. * Sets the Default image processing configuration used either in the this material.
  43580. *
  43581. * If sets to null, the scene one is in use.
  43582. */
  43583. set: function (value) {
  43584. this._attachImageProcessingConfiguration(value);
  43585. // Ensure the effect will be rebuilt.
  43586. this._markAllSubMeshesAsTexturesDirty();
  43587. },
  43588. enumerable: true,
  43589. configurable: true
  43590. });
  43591. /**
  43592. * Attaches a new image processing configuration to the Standard Material.
  43593. * @param configuration
  43594. */
  43595. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43596. var _this = this;
  43597. if (configuration === this._imageProcessingConfiguration) {
  43598. return;
  43599. }
  43600. // Detaches observer.
  43601. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43602. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43603. }
  43604. // Pick the scene configuration if needed.
  43605. if (!configuration) {
  43606. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43607. }
  43608. else {
  43609. this._imageProcessingConfiguration = configuration;
  43610. }
  43611. // Attaches observer.
  43612. if (this._imageProcessingConfiguration) {
  43613. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43614. _this._markAllSubMeshesAsImageProcessingDirty();
  43615. });
  43616. }
  43617. };
  43618. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43619. /**
  43620. * Gets wether the color curves effect is enabled.
  43621. */
  43622. get: function () {
  43623. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43624. },
  43625. /**
  43626. * Sets wether the color curves effect is enabled.
  43627. */
  43628. set: function (value) {
  43629. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43630. },
  43631. enumerable: true,
  43632. configurable: true
  43633. });
  43634. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43635. /**
  43636. * Gets wether the color grading effect is enabled.
  43637. */
  43638. get: function () {
  43639. return this.imageProcessingConfiguration.colorGradingEnabled;
  43640. },
  43641. /**
  43642. * Gets wether the color grading effect is enabled.
  43643. */
  43644. set: function (value) {
  43645. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43646. },
  43647. enumerable: true,
  43648. configurable: true
  43649. });
  43650. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43651. /**
  43652. * Gets wether tonemapping is enabled or not.
  43653. */
  43654. get: function () {
  43655. return this._imageProcessingConfiguration.toneMappingEnabled;
  43656. },
  43657. /**
  43658. * Sets wether tonemapping is enabled or not
  43659. */
  43660. set: function (value) {
  43661. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43662. },
  43663. enumerable: true,
  43664. configurable: true
  43665. });
  43666. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43667. /**
  43668. * The camera exposure used on this material.
  43669. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43670. * This corresponds to a photographic exposure.
  43671. */
  43672. get: function () {
  43673. return this._imageProcessingConfiguration.exposure;
  43674. },
  43675. /**
  43676. * The camera exposure used on this material.
  43677. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43678. * This corresponds to a photographic exposure.
  43679. */
  43680. set: function (value) {
  43681. this._imageProcessingConfiguration.exposure = value;
  43682. },
  43683. enumerable: true,
  43684. configurable: true
  43685. });
  43686. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43687. /**
  43688. * Gets The camera contrast used on this material.
  43689. */
  43690. get: function () {
  43691. return this._imageProcessingConfiguration.contrast;
  43692. },
  43693. /**
  43694. * Sets The camera contrast used on this material.
  43695. */
  43696. set: function (value) {
  43697. this._imageProcessingConfiguration.contrast = value;
  43698. },
  43699. enumerable: true,
  43700. configurable: true
  43701. });
  43702. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43703. /**
  43704. * Gets the Color Grading 2D Lookup Texture.
  43705. */
  43706. get: function () {
  43707. return this._imageProcessingConfiguration.colorGradingTexture;
  43708. },
  43709. /**
  43710. * Sets the Color Grading 2D Lookup Texture.
  43711. */
  43712. set: function (value) {
  43713. this._imageProcessingConfiguration.colorGradingTexture = value;
  43714. },
  43715. enumerable: true,
  43716. configurable: true
  43717. });
  43718. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43719. /**
  43720. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43721. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43722. * 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;
  43723. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43724. */
  43725. get: function () {
  43726. return this._imageProcessingConfiguration.colorCurves;
  43727. },
  43728. /**
  43729. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43730. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43731. * 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;
  43732. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43733. */
  43734. set: function (value) {
  43735. this._imageProcessingConfiguration.colorCurves = value;
  43736. },
  43737. enumerable: true,
  43738. configurable: true
  43739. });
  43740. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43741. /**
  43742. * Gets a boolean indicating that current material needs to register RTT
  43743. */
  43744. get: function () {
  43745. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43746. return true;
  43747. }
  43748. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43749. return true;
  43750. }
  43751. return false;
  43752. },
  43753. enumerable: true,
  43754. configurable: true
  43755. });
  43756. /**
  43757. * Gets the current class name of the material e.g. "StandardMaterial"
  43758. * Mainly use in serialization.
  43759. * @returns the class name
  43760. */
  43761. StandardMaterial.prototype.getClassName = function () {
  43762. return "StandardMaterial";
  43763. };
  43764. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43765. /**
  43766. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43767. * You can try switching to logarithmic depth.
  43768. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43769. */
  43770. get: function () {
  43771. return this._useLogarithmicDepth;
  43772. },
  43773. set: function (value) {
  43774. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43775. this._markAllSubMeshesAsMiscDirty();
  43776. },
  43777. enumerable: true,
  43778. configurable: true
  43779. });
  43780. /**
  43781. * Specifies if the material will require alpha blending
  43782. * @returns a boolean specifying if alpha blending is needed
  43783. */
  43784. StandardMaterial.prototype.needAlphaBlending = function () {
  43785. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43786. };
  43787. /**
  43788. * Specifies if this material should be rendered in alpha test mode
  43789. * @returns a boolean specifying if an alpha test is needed.
  43790. */
  43791. StandardMaterial.prototype.needAlphaTesting = function () {
  43792. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43793. };
  43794. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43795. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43796. };
  43797. /**
  43798. * Get the texture used for alpha test purpose.
  43799. * @returns the diffuse texture in case of the standard material.
  43800. */
  43801. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43802. return this._diffuseTexture;
  43803. };
  43804. /**
  43805. * Get if the submesh is ready to be used and all its information available.
  43806. * Child classes can use it to update shaders
  43807. * @param mesh defines the mesh to check
  43808. * @param subMesh defines which submesh to check
  43809. * @param useInstances specifies that instances should be used
  43810. * @returns a boolean indicating that the submesh is ready or not
  43811. */
  43812. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43813. if (useInstances === void 0) { useInstances = false; }
  43814. if (subMesh.effect && this.isFrozen) {
  43815. if (this._wasPreviouslyReady) {
  43816. return true;
  43817. }
  43818. }
  43819. if (!subMesh._materialDefines) {
  43820. subMesh._materialDefines = new StandardMaterialDefines();
  43821. }
  43822. var scene = this.getScene();
  43823. var defines = subMesh._materialDefines;
  43824. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43825. if (defines._renderId === scene.getRenderId()) {
  43826. return true;
  43827. }
  43828. }
  43829. var engine = scene.getEngine();
  43830. // Lights
  43831. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43832. // Textures
  43833. if (defines._areTexturesDirty) {
  43834. defines._needUVs = false;
  43835. defines.MAINUV1 = false;
  43836. defines.MAINUV2 = false;
  43837. if (scene.texturesEnabled) {
  43838. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43839. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43840. return false;
  43841. }
  43842. else {
  43843. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43844. }
  43845. }
  43846. else {
  43847. defines.DIFFUSE = false;
  43848. }
  43849. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43850. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43851. return false;
  43852. }
  43853. else {
  43854. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43855. }
  43856. }
  43857. else {
  43858. defines.AMBIENT = false;
  43859. }
  43860. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43861. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43862. return false;
  43863. }
  43864. else {
  43865. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43866. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43867. }
  43868. }
  43869. else {
  43870. defines.OPACITY = false;
  43871. }
  43872. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43873. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43874. return false;
  43875. }
  43876. else {
  43877. defines._needNormals = true;
  43878. defines.REFLECTION = true;
  43879. defines.ROUGHNESS = (this._roughness > 0);
  43880. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43881. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43882. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43883. switch (this._reflectionTexture.coordinatesMode) {
  43884. case BABYLON.Texture.EXPLICIT_MODE:
  43885. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43886. break;
  43887. case BABYLON.Texture.PLANAR_MODE:
  43888. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43889. break;
  43890. case BABYLON.Texture.PROJECTION_MODE:
  43891. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43892. break;
  43893. case BABYLON.Texture.SKYBOX_MODE:
  43894. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43895. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43896. break;
  43897. case BABYLON.Texture.SPHERICAL_MODE:
  43898. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43899. break;
  43900. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43901. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43902. break;
  43903. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43904. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43905. break;
  43906. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43907. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43908. break;
  43909. case BABYLON.Texture.CUBIC_MODE:
  43910. case BABYLON.Texture.INVCUBIC_MODE:
  43911. default:
  43912. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43913. break;
  43914. }
  43915. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43916. }
  43917. }
  43918. else {
  43919. defines.REFLECTION = false;
  43920. }
  43921. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43922. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43923. return false;
  43924. }
  43925. else {
  43926. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43927. }
  43928. }
  43929. else {
  43930. defines.EMISSIVE = false;
  43931. }
  43932. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43933. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43934. return false;
  43935. }
  43936. else {
  43937. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43938. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43939. }
  43940. }
  43941. else {
  43942. defines.LIGHTMAP = false;
  43943. }
  43944. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43945. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43946. return false;
  43947. }
  43948. else {
  43949. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43950. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43951. }
  43952. }
  43953. else {
  43954. defines.SPECULAR = false;
  43955. }
  43956. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43957. // Bump texure can not be not blocking.
  43958. if (!this._bumpTexture.isReady()) {
  43959. return false;
  43960. }
  43961. else {
  43962. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43963. defines.PARALLAX = this._useParallax;
  43964. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43965. }
  43966. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43967. }
  43968. else {
  43969. defines.BUMP = false;
  43970. }
  43971. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43972. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43973. return false;
  43974. }
  43975. else {
  43976. defines._needUVs = true;
  43977. defines.REFRACTION = true;
  43978. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43979. }
  43980. }
  43981. else {
  43982. defines.REFRACTION = false;
  43983. }
  43984. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43985. }
  43986. else {
  43987. defines.DIFFUSE = false;
  43988. defines.AMBIENT = false;
  43989. defines.OPACITY = false;
  43990. defines.REFLECTION = false;
  43991. defines.EMISSIVE = false;
  43992. defines.LIGHTMAP = false;
  43993. defines.BUMP = false;
  43994. defines.REFRACTION = false;
  43995. }
  43996. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43997. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43998. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43999. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44000. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44001. }
  44002. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44003. if (!this._imageProcessingConfiguration.isReady()) {
  44004. return false;
  44005. }
  44006. this._imageProcessingConfiguration.prepareDefines(defines);
  44007. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  44008. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  44009. }
  44010. if (defines._areFresnelDirty) {
  44011. if (StandardMaterial.FresnelEnabled) {
  44012. // Fresnel
  44013. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44014. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44015. this._reflectionFresnelParameters) {
  44016. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44017. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44018. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44019. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44020. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44021. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44022. defines._needNormals = true;
  44023. defines.FRESNEL = true;
  44024. }
  44025. }
  44026. else {
  44027. defines.FRESNEL = false;
  44028. }
  44029. }
  44030. // Misc.
  44031. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  44032. // Attribs
  44033. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44034. // Values that need to be evaluated on every frame
  44035. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44036. // Get correct effect
  44037. if (defines.isDirty) {
  44038. defines.markAsProcessed();
  44039. // Fallbacks
  44040. var fallbacks = new BABYLON.EffectFallbacks();
  44041. if (defines.REFLECTION) {
  44042. fallbacks.addFallback(0, "REFLECTION");
  44043. }
  44044. if (defines.SPECULAR) {
  44045. fallbacks.addFallback(0, "SPECULAR");
  44046. }
  44047. if (defines.BUMP) {
  44048. fallbacks.addFallback(0, "BUMP");
  44049. }
  44050. if (defines.PARALLAX) {
  44051. fallbacks.addFallback(1, "PARALLAX");
  44052. }
  44053. if (defines.PARALLAXOCCLUSION) {
  44054. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44055. }
  44056. if (defines.SPECULAROVERALPHA) {
  44057. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44058. }
  44059. if (defines.FOG) {
  44060. fallbacks.addFallback(1, "FOG");
  44061. }
  44062. if (defines.POINTSIZE) {
  44063. fallbacks.addFallback(0, "POINTSIZE");
  44064. }
  44065. if (defines.LOGARITHMICDEPTH) {
  44066. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44067. }
  44068. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44069. if (defines.SPECULARTERM) {
  44070. fallbacks.addFallback(0, "SPECULARTERM");
  44071. }
  44072. if (defines.DIFFUSEFRESNEL) {
  44073. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44074. }
  44075. if (defines.OPACITYFRESNEL) {
  44076. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44077. }
  44078. if (defines.REFLECTIONFRESNEL) {
  44079. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44080. }
  44081. if (defines.EMISSIVEFRESNEL) {
  44082. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44083. }
  44084. if (defines.FRESNEL) {
  44085. fallbacks.addFallback(4, "FRESNEL");
  44086. }
  44087. //Attributes
  44088. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44089. if (defines.NORMAL) {
  44090. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44091. }
  44092. if (defines.UV1) {
  44093. attribs.push(BABYLON.VertexBuffer.UVKind);
  44094. }
  44095. if (defines.UV2) {
  44096. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44097. }
  44098. if (defines.VERTEXCOLOR) {
  44099. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44100. }
  44101. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44102. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44103. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44104. var shaderName = "default";
  44105. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44106. "vFogInfos", "vFogColor", "pointSize",
  44107. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44108. "mBones",
  44109. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  44110. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44111. "vReflectionPosition", "vReflectionSize",
  44112. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  44113. ];
  44114. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  44115. var uniformBuffers = ["Material", "Scene"];
  44116. if (BABYLON.ImageProcessingConfiguration) {
  44117. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44118. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44119. }
  44120. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44121. uniformsNames: uniforms,
  44122. uniformBuffersNames: uniformBuffers,
  44123. samplers: samplers,
  44124. defines: defines,
  44125. maxSimultaneousLights: this._maxSimultaneousLights
  44126. });
  44127. if (this.customShaderNameResolve) {
  44128. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44129. }
  44130. var join = defines.toString();
  44131. var previousEffect = subMesh.effect;
  44132. var effect = scene.getEngine().createEffect(shaderName, {
  44133. attributes: attribs,
  44134. uniformsNames: uniforms,
  44135. uniformBuffersNames: uniformBuffers,
  44136. samplers: samplers,
  44137. defines: join,
  44138. fallbacks: fallbacks,
  44139. onCompiled: this.onCompiled,
  44140. onError: this.onError,
  44141. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44142. }, engine);
  44143. if (effect) {
  44144. // Use previous effect while new one is compiling
  44145. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  44146. effect = previousEffect;
  44147. defines.markAsUnprocessed();
  44148. }
  44149. else {
  44150. scene.resetCachedMaterial();
  44151. subMesh.setEffect(effect, defines);
  44152. this.buildUniformLayout();
  44153. }
  44154. }
  44155. }
  44156. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44157. return false;
  44158. }
  44159. defines._renderId = scene.getRenderId();
  44160. this._wasPreviouslyReady = true;
  44161. return true;
  44162. };
  44163. /**
  44164. * Builds the material UBO layouts.
  44165. * Used internally during the effect preparation.
  44166. */
  44167. StandardMaterial.prototype.buildUniformLayout = function () {
  44168. // Order is important !
  44169. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44170. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44171. this._uniformBuffer.addUniform("opacityParts", 4);
  44172. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44173. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44174. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44175. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44176. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44177. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44178. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44179. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44180. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44181. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44182. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44183. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44184. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44185. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44186. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44187. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44188. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44189. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44190. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44191. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44192. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44193. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44194. this._uniformBuffer.addUniform("specularMatrix", 16);
  44195. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44196. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44197. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44198. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44199. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44200. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44201. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44202. this._uniformBuffer.addUniform("pointSize", 1);
  44203. this._uniformBuffer.create();
  44204. };
  44205. /**
  44206. * Unbinds the material from the mesh
  44207. */
  44208. StandardMaterial.prototype.unbind = function () {
  44209. if (this._activeEffect) {
  44210. var needFlag = false;
  44211. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44212. this._activeEffect.setTexture("reflection2DSampler", null);
  44213. needFlag = true;
  44214. }
  44215. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44216. this._activeEffect.setTexture("refraction2DSampler", null);
  44217. needFlag = true;
  44218. }
  44219. if (needFlag) {
  44220. this._markAllSubMeshesAsTexturesDirty();
  44221. }
  44222. }
  44223. _super.prototype.unbind.call(this);
  44224. };
  44225. /**
  44226. * Binds the submesh to this material by preparing the effect and shader to draw
  44227. * @param world defines the world transformation matrix
  44228. * @param mesh defines the mesh containing the submesh
  44229. * @param subMesh defines the submesh to bind the material to
  44230. */
  44231. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44232. var scene = this.getScene();
  44233. var defines = subMesh._materialDefines;
  44234. if (!defines) {
  44235. return;
  44236. }
  44237. var effect = subMesh.effect;
  44238. if (!effect) {
  44239. return;
  44240. }
  44241. this._activeEffect = effect;
  44242. // Matrices
  44243. this.bindOnlyWorldMatrix(world);
  44244. // Normal Matrix
  44245. if (defines.OBJECTSPACE_NORMALMAP) {
  44246. world.toNormalMatrix(this._normalMatrix);
  44247. this.bindOnlyNormalMatrix(this._normalMatrix);
  44248. }
  44249. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44250. // Bones
  44251. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44252. if (mustRebind) {
  44253. this._uniformBuffer.bindToEffect(effect, "Material");
  44254. this.bindViewProjection(effect);
  44255. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44256. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44257. // Fresnel
  44258. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44259. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44260. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44261. }
  44262. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44263. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44264. }
  44265. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44266. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44267. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44268. }
  44269. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44270. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44271. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44272. }
  44273. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44274. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44275. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44276. }
  44277. }
  44278. // Textures
  44279. if (scene.texturesEnabled) {
  44280. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44281. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44282. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44283. if (this._diffuseTexture.hasAlpha) {
  44284. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44285. }
  44286. }
  44287. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44288. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44289. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44290. }
  44291. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44292. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44293. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44294. }
  44295. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44296. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44297. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44298. if (this._reflectionTexture.boundingBoxSize) {
  44299. var cubeTexture = this._reflectionTexture;
  44300. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44301. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44302. }
  44303. }
  44304. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44305. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44306. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44307. }
  44308. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44309. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44310. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44311. }
  44312. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44313. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44314. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44315. }
  44316. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44317. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44318. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44319. if (scene._mirroredCameraPosition) {
  44320. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44321. }
  44322. else {
  44323. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44324. }
  44325. }
  44326. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44327. var depth = 1.0;
  44328. if (!this._refractionTexture.isCube) {
  44329. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44330. if (this._refractionTexture.depth) {
  44331. depth = this._refractionTexture.depth;
  44332. }
  44333. }
  44334. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44335. }
  44336. }
  44337. // Point size
  44338. if (this.pointsCloud) {
  44339. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44340. }
  44341. if (defines.SPECULARTERM) {
  44342. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44343. }
  44344. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44345. // Diffuse
  44346. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44347. }
  44348. // Textures
  44349. if (scene.texturesEnabled) {
  44350. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44351. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44352. }
  44353. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44354. effect.setTexture("ambientSampler", this._ambientTexture);
  44355. }
  44356. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44357. effect.setTexture("opacitySampler", this._opacityTexture);
  44358. }
  44359. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44360. if (this._reflectionTexture.isCube) {
  44361. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44362. }
  44363. else {
  44364. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44365. }
  44366. }
  44367. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44368. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44369. }
  44370. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44371. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44372. }
  44373. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44374. effect.setTexture("specularSampler", this._specularTexture);
  44375. }
  44376. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44377. effect.setTexture("bumpSampler", this._bumpTexture);
  44378. }
  44379. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44380. var depth = 1.0;
  44381. if (this._refractionTexture.isCube) {
  44382. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44383. }
  44384. else {
  44385. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44386. }
  44387. }
  44388. }
  44389. // Clip plane
  44390. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44391. // Colors
  44392. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44393. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44394. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44395. }
  44396. if (mustRebind || !this.isFrozen) {
  44397. // Lights
  44398. if (scene.lightsEnabled && !this._disableLighting) {
  44399. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44400. }
  44401. // View
  44402. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44403. this.bindView(effect);
  44404. }
  44405. // Fog
  44406. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44407. // Morph targets
  44408. if (defines.NUM_MORPH_INFLUENCERS) {
  44409. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44410. }
  44411. // Log. depth
  44412. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44413. // image processing
  44414. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44415. this._imageProcessingConfiguration.bind(this._activeEffect);
  44416. }
  44417. }
  44418. this._uniformBuffer.update();
  44419. this._afterBind(mesh, this._activeEffect);
  44420. };
  44421. /**
  44422. * Get the list of animatables in the material.
  44423. * @returns the list of animatables object used in the material
  44424. */
  44425. StandardMaterial.prototype.getAnimatables = function () {
  44426. var results = [];
  44427. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44428. results.push(this._diffuseTexture);
  44429. }
  44430. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44431. results.push(this._ambientTexture);
  44432. }
  44433. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44434. results.push(this._opacityTexture);
  44435. }
  44436. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44437. results.push(this._reflectionTexture);
  44438. }
  44439. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44440. results.push(this._emissiveTexture);
  44441. }
  44442. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44443. results.push(this._specularTexture);
  44444. }
  44445. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44446. results.push(this._bumpTexture);
  44447. }
  44448. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44449. results.push(this._lightmapTexture);
  44450. }
  44451. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44452. results.push(this._refractionTexture);
  44453. }
  44454. return results;
  44455. };
  44456. /**
  44457. * Gets the active textures from the material
  44458. * @returns an array of textures
  44459. */
  44460. StandardMaterial.prototype.getActiveTextures = function () {
  44461. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44462. if (this._diffuseTexture) {
  44463. activeTextures.push(this._diffuseTexture);
  44464. }
  44465. if (this._ambientTexture) {
  44466. activeTextures.push(this._ambientTexture);
  44467. }
  44468. if (this._opacityTexture) {
  44469. activeTextures.push(this._opacityTexture);
  44470. }
  44471. if (this._reflectionTexture) {
  44472. activeTextures.push(this._reflectionTexture);
  44473. }
  44474. if (this._emissiveTexture) {
  44475. activeTextures.push(this._emissiveTexture);
  44476. }
  44477. if (this._specularTexture) {
  44478. activeTextures.push(this._specularTexture);
  44479. }
  44480. if (this._bumpTexture) {
  44481. activeTextures.push(this._bumpTexture);
  44482. }
  44483. if (this._lightmapTexture) {
  44484. activeTextures.push(this._lightmapTexture);
  44485. }
  44486. if (this._refractionTexture) {
  44487. activeTextures.push(this._refractionTexture);
  44488. }
  44489. return activeTextures;
  44490. };
  44491. /**
  44492. * Specifies if the material uses a texture
  44493. * @param texture defines the texture to check against the material
  44494. * @returns a boolean specifying if the material uses the texture
  44495. */
  44496. StandardMaterial.prototype.hasTexture = function (texture) {
  44497. if (_super.prototype.hasTexture.call(this, texture)) {
  44498. return true;
  44499. }
  44500. if (this._diffuseTexture === texture) {
  44501. return true;
  44502. }
  44503. if (this._ambientTexture === texture) {
  44504. return true;
  44505. }
  44506. if (this._opacityTexture === texture) {
  44507. return true;
  44508. }
  44509. if (this._reflectionTexture === texture) {
  44510. return true;
  44511. }
  44512. if (this._emissiveTexture === texture) {
  44513. return true;
  44514. }
  44515. if (this._specularTexture === texture) {
  44516. return true;
  44517. }
  44518. if (this._bumpTexture === texture) {
  44519. return true;
  44520. }
  44521. if (this._lightmapTexture === texture) {
  44522. return true;
  44523. }
  44524. if (this._refractionTexture === texture) {
  44525. return true;
  44526. }
  44527. return false;
  44528. };
  44529. /**
  44530. * Disposes the material
  44531. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44532. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44533. */
  44534. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44535. if (forceDisposeTextures) {
  44536. if (this._diffuseTexture) {
  44537. this._diffuseTexture.dispose();
  44538. }
  44539. if (this._ambientTexture) {
  44540. this._ambientTexture.dispose();
  44541. }
  44542. if (this._opacityTexture) {
  44543. this._opacityTexture.dispose();
  44544. }
  44545. if (this._reflectionTexture) {
  44546. this._reflectionTexture.dispose();
  44547. }
  44548. if (this._emissiveTexture) {
  44549. this._emissiveTexture.dispose();
  44550. }
  44551. if (this._specularTexture) {
  44552. this._specularTexture.dispose();
  44553. }
  44554. if (this._bumpTexture) {
  44555. this._bumpTexture.dispose();
  44556. }
  44557. if (this._lightmapTexture) {
  44558. this._lightmapTexture.dispose();
  44559. }
  44560. if (this._refractionTexture) {
  44561. this._refractionTexture.dispose();
  44562. }
  44563. }
  44564. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44565. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44566. }
  44567. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44568. };
  44569. /**
  44570. * Makes a duplicate of the material, and gives it a new name
  44571. * @param name defines the new name for the duplicated material
  44572. * @returns the cloned material
  44573. */
  44574. StandardMaterial.prototype.clone = function (name) {
  44575. var _this = this;
  44576. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44577. result.name = name;
  44578. result.id = name;
  44579. return result;
  44580. };
  44581. /**
  44582. * Serializes this material in a JSON representation
  44583. * @returns the serialized material object
  44584. */
  44585. StandardMaterial.prototype.serialize = function () {
  44586. return BABYLON.SerializationHelper.Serialize(this);
  44587. };
  44588. /**
  44589. * Creates a standard material from parsed material data
  44590. * @param source defines the JSON represnetation of the material
  44591. * @param scene defines the hosting scene
  44592. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44593. * @returns a new material
  44594. */
  44595. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44596. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44597. };
  44598. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44599. /**
  44600. * Are diffuse textures enabled in the application.
  44601. */
  44602. get: function () {
  44603. return StandardMaterial._DiffuseTextureEnabled;
  44604. },
  44605. set: function (value) {
  44606. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44607. return;
  44608. }
  44609. StandardMaterial._DiffuseTextureEnabled = value;
  44610. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44611. },
  44612. enumerable: true,
  44613. configurable: true
  44614. });
  44615. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44616. /**
  44617. * Are ambient textures enabled in the application.
  44618. */
  44619. get: function () {
  44620. return StandardMaterial._AmbientTextureEnabled;
  44621. },
  44622. set: function (value) {
  44623. if (StandardMaterial._AmbientTextureEnabled === value) {
  44624. return;
  44625. }
  44626. StandardMaterial._AmbientTextureEnabled = value;
  44627. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44628. },
  44629. enumerable: true,
  44630. configurable: true
  44631. });
  44632. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44633. /**
  44634. * Are opacity textures enabled in the application.
  44635. */
  44636. get: function () {
  44637. return StandardMaterial._OpacityTextureEnabled;
  44638. },
  44639. set: function (value) {
  44640. if (StandardMaterial._OpacityTextureEnabled === value) {
  44641. return;
  44642. }
  44643. StandardMaterial._OpacityTextureEnabled = value;
  44644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44645. },
  44646. enumerable: true,
  44647. configurable: true
  44648. });
  44649. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44650. /**
  44651. * Are reflection textures enabled in the application.
  44652. */
  44653. get: function () {
  44654. return StandardMaterial._ReflectionTextureEnabled;
  44655. },
  44656. set: function (value) {
  44657. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44658. return;
  44659. }
  44660. StandardMaterial._ReflectionTextureEnabled = value;
  44661. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44662. },
  44663. enumerable: true,
  44664. configurable: true
  44665. });
  44666. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44667. /**
  44668. * Are emissive textures enabled in the application.
  44669. */
  44670. get: function () {
  44671. return StandardMaterial._EmissiveTextureEnabled;
  44672. },
  44673. set: function (value) {
  44674. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44675. return;
  44676. }
  44677. StandardMaterial._EmissiveTextureEnabled = value;
  44678. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44679. },
  44680. enumerable: true,
  44681. configurable: true
  44682. });
  44683. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44684. /**
  44685. * Are specular textures enabled in the application.
  44686. */
  44687. get: function () {
  44688. return StandardMaterial._SpecularTextureEnabled;
  44689. },
  44690. set: function (value) {
  44691. if (StandardMaterial._SpecularTextureEnabled === value) {
  44692. return;
  44693. }
  44694. StandardMaterial._SpecularTextureEnabled = value;
  44695. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44696. },
  44697. enumerable: true,
  44698. configurable: true
  44699. });
  44700. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44701. /**
  44702. * Are bump textures enabled in the application.
  44703. */
  44704. get: function () {
  44705. return StandardMaterial._BumpTextureEnabled;
  44706. },
  44707. set: function (value) {
  44708. if (StandardMaterial._BumpTextureEnabled === value) {
  44709. return;
  44710. }
  44711. StandardMaterial._BumpTextureEnabled = value;
  44712. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44713. },
  44714. enumerable: true,
  44715. configurable: true
  44716. });
  44717. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44718. /**
  44719. * Are lightmap textures enabled in the application.
  44720. */
  44721. get: function () {
  44722. return StandardMaterial._LightmapTextureEnabled;
  44723. },
  44724. set: function (value) {
  44725. if (StandardMaterial._LightmapTextureEnabled === value) {
  44726. return;
  44727. }
  44728. StandardMaterial._LightmapTextureEnabled = value;
  44729. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44730. },
  44731. enumerable: true,
  44732. configurable: true
  44733. });
  44734. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44735. /**
  44736. * Are refraction textures enabled in the application.
  44737. */
  44738. get: function () {
  44739. return StandardMaterial._RefractionTextureEnabled;
  44740. },
  44741. set: function (value) {
  44742. if (StandardMaterial._RefractionTextureEnabled === value) {
  44743. return;
  44744. }
  44745. StandardMaterial._RefractionTextureEnabled = value;
  44746. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44747. },
  44748. enumerable: true,
  44749. configurable: true
  44750. });
  44751. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44752. /**
  44753. * Are color grading textures enabled in the application.
  44754. */
  44755. get: function () {
  44756. return StandardMaterial._ColorGradingTextureEnabled;
  44757. },
  44758. set: function (value) {
  44759. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44760. return;
  44761. }
  44762. StandardMaterial._ColorGradingTextureEnabled = value;
  44763. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44764. },
  44765. enumerable: true,
  44766. configurable: true
  44767. });
  44768. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44769. /**
  44770. * Are fresnels enabled in the application.
  44771. */
  44772. get: function () {
  44773. return StandardMaterial._FresnelEnabled;
  44774. },
  44775. set: function (value) {
  44776. if (StandardMaterial._FresnelEnabled === value) {
  44777. return;
  44778. }
  44779. StandardMaterial._FresnelEnabled = value;
  44780. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44781. },
  44782. enumerable: true,
  44783. configurable: true
  44784. });
  44785. // Flags used to enable or disable a type of texture for all Standard Materials
  44786. StandardMaterial._DiffuseTextureEnabled = true;
  44787. StandardMaterial._AmbientTextureEnabled = true;
  44788. StandardMaterial._OpacityTextureEnabled = true;
  44789. StandardMaterial._ReflectionTextureEnabled = true;
  44790. StandardMaterial._EmissiveTextureEnabled = true;
  44791. StandardMaterial._SpecularTextureEnabled = true;
  44792. StandardMaterial._BumpTextureEnabled = true;
  44793. StandardMaterial._LightmapTextureEnabled = true;
  44794. StandardMaterial._RefractionTextureEnabled = true;
  44795. StandardMaterial._ColorGradingTextureEnabled = true;
  44796. StandardMaterial._FresnelEnabled = true;
  44797. __decorate([
  44798. BABYLON.serializeAsTexture("diffuseTexture")
  44799. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44800. __decorate([
  44801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44802. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44803. __decorate([
  44804. BABYLON.serializeAsTexture("ambientTexture")
  44805. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44806. __decorate([
  44807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44808. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44809. __decorate([
  44810. BABYLON.serializeAsTexture("opacityTexture")
  44811. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44812. __decorate([
  44813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44814. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44815. __decorate([
  44816. BABYLON.serializeAsTexture("reflectionTexture")
  44817. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44818. __decorate([
  44819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44820. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44821. __decorate([
  44822. BABYLON.serializeAsTexture("emissiveTexture")
  44823. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44824. __decorate([
  44825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44826. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44827. __decorate([
  44828. BABYLON.serializeAsTexture("specularTexture")
  44829. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44830. __decorate([
  44831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44832. ], StandardMaterial.prototype, "specularTexture", void 0);
  44833. __decorate([
  44834. BABYLON.serializeAsTexture("bumpTexture")
  44835. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44836. __decorate([
  44837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44838. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44839. __decorate([
  44840. BABYLON.serializeAsTexture("lightmapTexture")
  44841. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44842. __decorate([
  44843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44844. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44845. __decorate([
  44846. BABYLON.serializeAsTexture("refractionTexture")
  44847. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44848. __decorate([
  44849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44850. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44851. __decorate([
  44852. BABYLON.serializeAsColor3("ambient")
  44853. ], StandardMaterial.prototype, "ambientColor", void 0);
  44854. __decorate([
  44855. BABYLON.serializeAsColor3("diffuse")
  44856. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44857. __decorate([
  44858. BABYLON.serializeAsColor3("specular")
  44859. ], StandardMaterial.prototype, "specularColor", void 0);
  44860. __decorate([
  44861. BABYLON.serializeAsColor3("emissive")
  44862. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44863. __decorate([
  44864. BABYLON.serialize()
  44865. ], StandardMaterial.prototype, "specularPower", void 0);
  44866. __decorate([
  44867. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44868. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44869. __decorate([
  44870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44871. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44872. __decorate([
  44873. BABYLON.serialize("useEmissiveAsIllumination")
  44874. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44875. __decorate([
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44877. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44878. __decorate([
  44879. BABYLON.serialize("linkEmissiveWithDiffuse")
  44880. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44881. __decorate([
  44882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44883. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44884. __decorate([
  44885. BABYLON.serialize("useSpecularOverAlpha")
  44886. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44887. __decorate([
  44888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44889. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44890. __decorate([
  44891. BABYLON.serialize("useReflectionOverAlpha")
  44892. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44893. __decorate([
  44894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44895. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44896. __decorate([
  44897. BABYLON.serialize("disableLighting")
  44898. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44899. __decorate([
  44900. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44901. ], StandardMaterial.prototype, "disableLighting", void 0);
  44902. __decorate([
  44903. BABYLON.serialize("useObjectSpaceNormalMap")
  44904. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44905. __decorate([
  44906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44907. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44908. __decorate([
  44909. BABYLON.serialize("useParallax")
  44910. ], StandardMaterial.prototype, "_useParallax", void 0);
  44911. __decorate([
  44912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44913. ], StandardMaterial.prototype, "useParallax", void 0);
  44914. __decorate([
  44915. BABYLON.serialize("useParallaxOcclusion")
  44916. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44917. __decorate([
  44918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44919. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44920. __decorate([
  44921. BABYLON.serialize()
  44922. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44923. __decorate([
  44924. BABYLON.serialize("roughness")
  44925. ], StandardMaterial.prototype, "_roughness", void 0);
  44926. __decorate([
  44927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44928. ], StandardMaterial.prototype, "roughness", void 0);
  44929. __decorate([
  44930. BABYLON.serialize()
  44931. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44932. __decorate([
  44933. BABYLON.serialize()
  44934. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44935. __decorate([
  44936. BABYLON.serialize()
  44937. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44938. __decorate([
  44939. BABYLON.serialize("useLightmapAsShadowmap")
  44940. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44941. __decorate([
  44942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44943. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44944. __decorate([
  44945. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44946. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44947. __decorate([
  44948. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44949. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44950. __decorate([
  44951. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44952. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44953. __decorate([
  44954. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44955. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44956. __decorate([
  44957. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44958. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44959. __decorate([
  44960. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44961. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44962. __decorate([
  44963. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44964. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44965. __decorate([
  44966. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44967. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44968. __decorate([
  44969. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44970. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44971. __decorate([
  44972. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44973. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44974. __decorate([
  44975. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44976. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44977. __decorate([
  44978. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44979. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44980. __decorate([
  44981. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44982. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44983. __decorate([
  44984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44985. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44986. __decorate([
  44987. BABYLON.serialize("maxSimultaneousLights")
  44988. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44989. __decorate([
  44990. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44991. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44992. __decorate([
  44993. BABYLON.serialize("invertNormalMapX")
  44994. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44995. __decorate([
  44996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44997. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44998. __decorate([
  44999. BABYLON.serialize("invertNormalMapY")
  45000. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45001. __decorate([
  45002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45003. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45004. __decorate([
  45005. BABYLON.serialize("twoSidedLighting")
  45006. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45007. __decorate([
  45008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45009. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45010. __decorate([
  45011. BABYLON.serialize()
  45012. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45013. return StandardMaterial;
  45014. }(BABYLON.PushMaterial));
  45015. BABYLON.StandardMaterial = StandardMaterial;
  45016. })(BABYLON || (BABYLON = {}));
  45017. //# sourceMappingURL=babylon.standardMaterial.js.map
  45018. var BABYLON;
  45019. (function (BABYLON) {
  45020. /**
  45021. * Class representing spherical polynomial coefficients to the 3rd degree
  45022. */
  45023. var SphericalPolynomial = /** @class */ (function () {
  45024. function SphericalPolynomial() {
  45025. /**
  45026. * The x coefficients of the spherical polynomial
  45027. */
  45028. this.x = BABYLON.Vector3.Zero();
  45029. /**
  45030. * The y coefficients of the spherical polynomial
  45031. */
  45032. this.y = BABYLON.Vector3.Zero();
  45033. /**
  45034. * The z coefficients of the spherical polynomial
  45035. */
  45036. this.z = BABYLON.Vector3.Zero();
  45037. /**
  45038. * The xx coefficients of the spherical polynomial
  45039. */
  45040. this.xx = BABYLON.Vector3.Zero();
  45041. /**
  45042. * The yy coefficients of the spherical polynomial
  45043. */
  45044. this.yy = BABYLON.Vector3.Zero();
  45045. /**
  45046. * The zz coefficients of the spherical polynomial
  45047. */
  45048. this.zz = BABYLON.Vector3.Zero();
  45049. /**
  45050. * The xy coefficients of the spherical polynomial
  45051. */
  45052. this.xy = BABYLON.Vector3.Zero();
  45053. /**
  45054. * The yz coefficients of the spherical polynomial
  45055. */
  45056. this.yz = BABYLON.Vector3.Zero();
  45057. /**
  45058. * The zx coefficients of the spherical polynomial
  45059. */
  45060. this.zx = BABYLON.Vector3.Zero();
  45061. }
  45062. /**
  45063. * Adds an ambient color to the spherical polynomial
  45064. * @param color the color to add
  45065. */
  45066. SphericalPolynomial.prototype.addAmbient = function (color) {
  45067. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45068. this.xx = this.xx.add(colorVector);
  45069. this.yy = this.yy.add(colorVector);
  45070. this.zz = this.zz.add(colorVector);
  45071. };
  45072. /**
  45073. * Scales the spherical polynomial by the given amount
  45074. * @param scale the amount to scale
  45075. */
  45076. SphericalPolynomial.prototype.scale = function (scale) {
  45077. this.x = this.x.scale(scale);
  45078. this.y = this.y.scale(scale);
  45079. this.z = this.z.scale(scale);
  45080. this.xx = this.xx.scale(scale);
  45081. this.yy = this.yy.scale(scale);
  45082. this.zz = this.zz.scale(scale);
  45083. this.yz = this.yz.scale(scale);
  45084. this.zx = this.zx.scale(scale);
  45085. this.xy = this.xy.scale(scale);
  45086. };
  45087. /**
  45088. * Gets the spherical polynomial from harmonics
  45089. * @param harmonics the spherical harmonics
  45090. * @returns the spherical polynomial
  45091. */
  45092. SphericalPolynomial.FromHarmonics = function (harmonics) {
  45093. var result = new SphericalPolynomial();
  45094. result.x = harmonics.l11.scale(1.02333);
  45095. result.y = harmonics.l1_1.scale(1.02333);
  45096. result.z = harmonics.l10.scale(1.02333);
  45097. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  45098. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  45099. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  45100. result.yz = harmonics.l2_1.scale(0.858086);
  45101. result.zx = harmonics.l21.scale(0.858086);
  45102. result.xy = harmonics.l2_2.scale(0.858086);
  45103. result.scale(1.0 / Math.PI);
  45104. return result;
  45105. };
  45106. /**
  45107. * Constructs a spherical polynomial from an array.
  45108. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  45109. * @returns the spherical polynomial
  45110. */
  45111. SphericalPolynomial.FromArray = function (data) {
  45112. var sp = new SphericalPolynomial();
  45113. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  45114. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  45115. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  45116. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  45117. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  45118. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  45119. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  45120. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  45121. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  45122. return sp;
  45123. };
  45124. return SphericalPolynomial;
  45125. }());
  45126. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45127. /**
  45128. * Class representing spherical harmonics coefficients to the 3rd degree
  45129. */
  45130. var SphericalHarmonics = /** @class */ (function () {
  45131. function SphericalHarmonics() {
  45132. /**
  45133. * The l0,0 coefficients of the spherical harmonics
  45134. */
  45135. this.l00 = BABYLON.Vector3.Zero();
  45136. /**
  45137. * The l1,-1 coefficients of the spherical harmonics
  45138. */
  45139. this.l1_1 = BABYLON.Vector3.Zero();
  45140. /**
  45141. * The l1,0 coefficients of the spherical harmonics
  45142. */
  45143. this.l10 = BABYLON.Vector3.Zero();
  45144. /**
  45145. * The l1,1 coefficients of the spherical harmonics
  45146. */
  45147. this.l11 = BABYLON.Vector3.Zero();
  45148. /**
  45149. * The l2,-2 coefficients of the spherical harmonics
  45150. */
  45151. this.l2_2 = BABYLON.Vector3.Zero();
  45152. /**
  45153. * The l2,-1 coefficients of the spherical harmonics
  45154. */
  45155. this.l2_1 = BABYLON.Vector3.Zero();
  45156. /**
  45157. * The l2,0 coefficients of the spherical harmonics
  45158. */
  45159. this.l20 = BABYLON.Vector3.Zero();
  45160. /**
  45161. * The l2,1 coefficients of the spherical harmonics
  45162. */
  45163. this.l21 = BABYLON.Vector3.Zero();
  45164. /**
  45165. * The l2,2 coefficients of the spherical harmonics
  45166. */
  45167. this.lL22 = BABYLON.Vector3.Zero();
  45168. }
  45169. /**
  45170. * Adds a light to the spherical harmonics
  45171. * @param direction the direction of the light
  45172. * @param color the color of the light
  45173. * @param deltaSolidAngle the delta solid angle of the light
  45174. */
  45175. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45176. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45177. var c = colorVector.scale(deltaSolidAngle);
  45178. this.l00 = this.l00.add(c.scale(0.282095));
  45179. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  45180. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  45181. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  45182. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  45183. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  45184. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  45185. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  45186. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  45187. };
  45188. /**
  45189. * Scales the spherical harmonics by the given amount
  45190. * @param scale the amount to scale
  45191. */
  45192. SphericalHarmonics.prototype.scale = function (scale) {
  45193. this.l00 = this.l00.scale(scale);
  45194. this.l1_1 = this.l1_1.scale(scale);
  45195. this.l10 = this.l10.scale(scale);
  45196. this.l11 = this.l11.scale(scale);
  45197. this.l2_2 = this.l2_2.scale(scale);
  45198. this.l2_1 = this.l2_1.scale(scale);
  45199. this.l20 = this.l20.scale(scale);
  45200. this.l21 = this.l21.scale(scale);
  45201. this.lL22 = this.lL22.scale(scale);
  45202. };
  45203. /**
  45204. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  45205. *
  45206. * ```
  45207. * E_lm = A_l * L_lm
  45208. * ```
  45209. *
  45210. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  45211. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  45212. * the scaling factors are given in equation 9.
  45213. */
  45214. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  45215. // Constant (Band 0)
  45216. this.l00 = this.l00.scale(3.141593);
  45217. // Linear (Band 1)
  45218. this.l1_1 = this.l1_1.scale(2.094395);
  45219. this.l10 = this.l10.scale(2.094395);
  45220. this.l11 = this.l11.scale(2.094395);
  45221. // Quadratic (Band 2)
  45222. this.l2_2 = this.l2_2.scale(0.785398);
  45223. this.l2_1 = this.l2_1.scale(0.785398);
  45224. this.l20 = this.l20.scale(0.785398);
  45225. this.l21 = this.l21.scale(0.785398);
  45226. this.lL22 = this.lL22.scale(0.785398);
  45227. };
  45228. /**
  45229. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  45230. *
  45231. * ```
  45232. * L = (1/pi) * E * rho
  45233. * ```
  45234. *
  45235. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  45236. */
  45237. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  45238. this.scale(1.0 / Math.PI);
  45239. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  45240. // (The pixel shader must apply albedo after texture fetches, etc).
  45241. };
  45242. /**
  45243. * Gets the spherical harmonics from polynomial
  45244. * @param polynomial the spherical polynomial
  45245. * @returns the spherical harmonics
  45246. */
  45247. SphericalHarmonics.FromPolynomial = function (polynomial) {
  45248. var result = new SphericalHarmonics();
  45249. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  45250. result.l1_1 = polynomial.y.scale(0.977204);
  45251. result.l10 = polynomial.z.scale(0.977204);
  45252. result.l11 = polynomial.x.scale(0.977204);
  45253. result.l2_2 = polynomial.xy.scale(1.16538);
  45254. result.l2_1 = polynomial.yz.scale(1.16538);
  45255. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  45256. result.l21 = polynomial.zx.scale(1.16538);
  45257. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  45258. result.scale(Math.PI);
  45259. return result;
  45260. };
  45261. /**
  45262. * Constructs a spherical harmonics from an array.
  45263. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  45264. * @returns the spherical harmonics
  45265. */
  45266. SphericalHarmonics.FromArray = function (data) {
  45267. var sh = new SphericalHarmonics();
  45268. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  45269. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  45270. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  45271. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  45272. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  45273. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  45274. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  45275. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  45276. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  45277. return sh;
  45278. };
  45279. return SphericalHarmonics;
  45280. }());
  45281. BABYLON.SphericalHarmonics = SphericalHarmonics;
  45282. })(BABYLON || (BABYLON = {}));
  45283. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  45284. var BABYLON;
  45285. (function (BABYLON) {
  45286. var FileFaceOrientation = /** @class */ (function () {
  45287. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45288. this.name = name;
  45289. this.worldAxisForNormal = worldAxisForNormal;
  45290. this.worldAxisForFileX = worldAxisForFileX;
  45291. this.worldAxisForFileY = worldAxisForFileY;
  45292. }
  45293. return FileFaceOrientation;
  45294. }());
  45295. /**
  45296. * Helper class dealing with the extraction of spherical polynomial dataArray
  45297. * from a cube map.
  45298. */
  45299. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  45300. function CubeMapToSphericalPolynomialTools() {
  45301. }
  45302. /**
  45303. * Converts a texture to the according Spherical Polynomial data.
  45304. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45305. *
  45306. * @param texture The texture to extract the information from.
  45307. * @return The Spherical Polynomial data.
  45308. */
  45309. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  45310. if (!texture.isCube) {
  45311. // Only supports cube Textures currently.
  45312. return null;
  45313. }
  45314. var size = texture.getSize().width;
  45315. var right = texture.readPixels(0);
  45316. var left = texture.readPixels(1);
  45317. var up;
  45318. var down;
  45319. if (texture.isRenderTarget) {
  45320. up = texture.readPixels(3);
  45321. down = texture.readPixels(2);
  45322. }
  45323. else {
  45324. up = texture.readPixels(2);
  45325. down = texture.readPixels(3);
  45326. }
  45327. var front = texture.readPixels(4);
  45328. var back = texture.readPixels(5);
  45329. var gammaSpace = texture.gammaSpace;
  45330. // Always read as RGBA.
  45331. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  45332. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45333. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45334. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45335. }
  45336. var cubeInfo = {
  45337. size: size,
  45338. right: right,
  45339. left: left,
  45340. up: up,
  45341. down: down,
  45342. front: front,
  45343. back: back,
  45344. format: format,
  45345. type: type,
  45346. gammaSpace: gammaSpace,
  45347. };
  45348. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45349. };
  45350. /**
  45351. * Converts a cubemap to the according Spherical Polynomial data.
  45352. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45353. *
  45354. * @param cubeInfo The Cube map to extract the information from.
  45355. * @return The Spherical Polynomial data.
  45356. */
  45357. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45358. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45359. var totalSolidAngle = 0.0;
  45360. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45361. var du = 2.0 / cubeInfo.size;
  45362. var dv = du;
  45363. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45364. var minUV = du * 0.5 - 1.0;
  45365. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45366. var fileFace = this.FileFaces[faceIndex];
  45367. var dataArray = cubeInfo[fileFace.name];
  45368. var v = minUV;
  45369. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45370. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45371. // Because SP is still linear, so summation is fine in that basis.
  45372. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45373. for (var y = 0; y < cubeInfo.size; y++) {
  45374. var u = minUV;
  45375. for (var x = 0; x < cubeInfo.size; x++) {
  45376. // World direction (not normalised)
  45377. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45378. worldDirection.normalize();
  45379. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45380. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45381. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45382. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45383. // Handle Integer types.
  45384. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45385. r /= 255;
  45386. g /= 255;
  45387. b /= 255;
  45388. }
  45389. // Handle Gamma space textures.
  45390. if (cubeInfo.gammaSpace) {
  45391. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45392. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45393. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45394. }
  45395. var color = new BABYLON.Color3(r, g, b);
  45396. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45397. totalSolidAngle += deltaSolidAngle;
  45398. u += du;
  45399. }
  45400. v += dv;
  45401. }
  45402. }
  45403. // Solid angle for entire sphere is 4*pi
  45404. var sphereSolidAngle = 4.0 * Math.PI;
  45405. // Adjust the solid angle to allow for how many faces we processed.
  45406. var facesProcessed = 6.0;
  45407. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45408. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45409. // This is needed because the numerical integration over the cube uses a
  45410. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45411. // and also to compensate for accumulative error due to float precision in the summation.
  45412. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45413. sphericalHarmonics.scale(correctionFactor);
  45414. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45415. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45416. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45417. };
  45418. CubeMapToSphericalPolynomialTools.FileFaces = [
  45419. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45420. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45421. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45422. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45423. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45424. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45425. ];
  45426. return CubeMapToSphericalPolynomialTools;
  45427. }());
  45428. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45429. })(BABYLON || (BABYLON = {}));
  45430. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45431. var BABYLON;
  45432. (function (BABYLON) {
  45433. /**
  45434. * Manages the defines for the PBR Material.
  45435. * @hiddenChildren
  45436. */
  45437. var PBRMaterialDefines = /** @class */ (function (_super) {
  45438. __extends(PBRMaterialDefines, _super);
  45439. /**
  45440. * Initializes the PBR Material defines.
  45441. */
  45442. function PBRMaterialDefines() {
  45443. var _this = _super.call(this) || this;
  45444. _this.PBR = true;
  45445. _this.MAINUV1 = false;
  45446. _this.MAINUV2 = false;
  45447. _this.UV1 = false;
  45448. _this.UV2 = false;
  45449. _this.ALBEDO = false;
  45450. _this.ALBEDODIRECTUV = 0;
  45451. _this.VERTEXCOLOR = false;
  45452. _this.AMBIENT = false;
  45453. _this.AMBIENTDIRECTUV = 0;
  45454. _this.AMBIENTINGRAYSCALE = false;
  45455. _this.OPACITY = false;
  45456. _this.VERTEXALPHA = false;
  45457. _this.OPACITYDIRECTUV = 0;
  45458. _this.OPACITYRGB = false;
  45459. _this.ALPHATEST = false;
  45460. _this.DEPTHPREPASS = false;
  45461. _this.ALPHABLEND = false;
  45462. _this.ALPHAFROMALBEDO = false;
  45463. _this.ALPHATESTVALUE = "0.5";
  45464. _this.SPECULAROVERALPHA = false;
  45465. _this.RADIANCEOVERALPHA = false;
  45466. _this.ALPHAFRESNEL = false;
  45467. _this.LINEARALPHAFRESNEL = false;
  45468. _this.PREMULTIPLYALPHA = false;
  45469. _this.EMISSIVE = false;
  45470. _this.EMISSIVEDIRECTUV = 0;
  45471. _this.REFLECTIVITY = false;
  45472. _this.REFLECTIVITYDIRECTUV = 0;
  45473. _this.SPECULARTERM = false;
  45474. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45475. _this.MICROSURFACEAUTOMATIC = false;
  45476. _this.LODBASEDMICROSFURACE = false;
  45477. _this.MICROSURFACEMAP = false;
  45478. _this.MICROSURFACEMAPDIRECTUV = 0;
  45479. _this.METALLICWORKFLOW = false;
  45480. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45481. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45482. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45483. _this.AOSTOREINMETALMAPRED = false;
  45484. _this.ENVIRONMENTBRDF = false;
  45485. _this.NORMAL = false;
  45486. _this.TANGENT = false;
  45487. _this.BUMP = false;
  45488. _this.BUMPDIRECTUV = 0;
  45489. _this.OBJECTSPACE_NORMALMAP = false;
  45490. _this.PARALLAX = false;
  45491. _this.PARALLAXOCCLUSION = false;
  45492. _this.NORMALXYSCALE = true;
  45493. _this.LIGHTMAP = false;
  45494. _this.LIGHTMAPDIRECTUV = 0;
  45495. _this.USELIGHTMAPASSHADOWMAP = false;
  45496. _this.GAMMALIGHTMAP = false;
  45497. _this.REFLECTION = false;
  45498. _this.REFLECTIONMAP_3D = false;
  45499. _this.REFLECTIONMAP_SPHERICAL = false;
  45500. _this.REFLECTIONMAP_PLANAR = false;
  45501. _this.REFLECTIONMAP_CUBIC = false;
  45502. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45503. _this.REFLECTIONMAP_PROJECTION = false;
  45504. _this.REFLECTIONMAP_SKYBOX = false;
  45505. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45506. _this.REFLECTIONMAP_EXPLICIT = false;
  45507. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45508. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45509. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45510. _this.INVERTCUBICMAP = false;
  45511. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45512. _this.USESPHERICALINVERTEX = false;
  45513. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45514. _this.LODINREFLECTIONALPHA = false;
  45515. _this.GAMMAREFLECTION = false;
  45516. _this.RGBDREFLECTION = false;
  45517. _this.RADIANCEOCCLUSION = false;
  45518. _this.HORIZONOCCLUSION = false;
  45519. _this.REFRACTION = false;
  45520. _this.REFRACTIONMAP_3D = false;
  45521. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45522. _this.LODINREFRACTIONALPHA = false;
  45523. _this.GAMMAREFRACTION = false;
  45524. _this.RGBDREFRACTION = false;
  45525. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45526. _this.INSTANCES = false;
  45527. _this.NUM_BONE_INFLUENCERS = 0;
  45528. _this.BonesPerMesh = 0;
  45529. _this.NONUNIFORMSCALING = false;
  45530. _this.MORPHTARGETS = false;
  45531. _this.MORPHTARGETS_NORMAL = false;
  45532. _this.MORPHTARGETS_TANGENT = false;
  45533. _this.NUM_MORPH_INFLUENCERS = 0;
  45534. _this.IMAGEPROCESSING = false;
  45535. _this.VIGNETTE = false;
  45536. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45537. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45538. _this.TONEMAPPING = false;
  45539. _this.TONEMAPPING_ACES = false;
  45540. _this.CONTRAST = false;
  45541. _this.COLORCURVES = false;
  45542. _this.COLORGRADING = false;
  45543. _this.COLORGRADING3D = false;
  45544. _this.SAMPLER3DGREENDEPTH = false;
  45545. _this.SAMPLER3DBGRMAP = false;
  45546. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45547. _this.EXPOSURE = false;
  45548. _this.USEPHYSICALLIGHTFALLOFF = false;
  45549. _this.USEGLTFLIGHTFALLOFF = false;
  45550. _this.TWOSIDEDLIGHTING = false;
  45551. _this.SHADOWFLOAT = false;
  45552. _this.CLIPPLANE = false;
  45553. _this.CLIPPLANE2 = false;
  45554. _this.CLIPPLANE3 = false;
  45555. _this.CLIPPLANE4 = false;
  45556. _this.POINTSIZE = false;
  45557. _this.FOG = false;
  45558. _this.LOGARITHMICDEPTH = false;
  45559. _this.FORCENORMALFORWARD = false;
  45560. _this.SPECULARAA = false;
  45561. _this.UNLIT = false;
  45562. _this.rebuild();
  45563. return _this;
  45564. }
  45565. /**
  45566. * Resets the PBR Material defines.
  45567. */
  45568. PBRMaterialDefines.prototype.reset = function () {
  45569. _super.prototype.reset.call(this);
  45570. this.ALPHATESTVALUE = "0.5";
  45571. this.PBR = true;
  45572. };
  45573. return PBRMaterialDefines;
  45574. }(BABYLON.MaterialDefines));
  45575. /**
  45576. * The Physically based material base class of BJS.
  45577. *
  45578. * This offers the main features of a standard PBR material.
  45579. * For more information, please refer to the documentation :
  45580. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45581. */
  45582. var PBRBaseMaterial = /** @class */ (function (_super) {
  45583. __extends(PBRBaseMaterial, _super);
  45584. /**
  45585. * Instantiates a new PBRMaterial instance.
  45586. *
  45587. * @param name The material name
  45588. * @param scene The scene the material will be use in.
  45589. */
  45590. function PBRBaseMaterial(name, scene) {
  45591. var _this = _super.call(this, name, scene) || this;
  45592. /**
  45593. * Intensity of the direct lights e.g. the four lights available in your scene.
  45594. * This impacts both the direct diffuse and specular highlights.
  45595. */
  45596. _this._directIntensity = 1.0;
  45597. /**
  45598. * Intensity of the emissive part of the material.
  45599. * This helps controlling the emissive effect without modifying the emissive color.
  45600. */
  45601. _this._emissiveIntensity = 1.0;
  45602. /**
  45603. * Intensity of the environment e.g. how much the environment will light the object
  45604. * either through harmonics for rough material or through the refelction for shiny ones.
  45605. */
  45606. _this._environmentIntensity = 1.0;
  45607. /**
  45608. * This is a special control allowing the reduction of the specular highlights coming from the
  45609. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45610. */
  45611. _this._specularIntensity = 1.0;
  45612. /**
  45613. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45614. */
  45615. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45616. /**
  45617. * Debug Control allowing disabling the bump map on this material.
  45618. */
  45619. _this._disableBumpMap = false;
  45620. /**
  45621. * AKA Occlusion Texture Intensity in other nomenclature.
  45622. */
  45623. _this._ambientTextureStrength = 1.0;
  45624. /**
  45625. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45626. * 1 means it completely occludes it
  45627. * 0 mean it has no impact
  45628. */
  45629. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45630. /**
  45631. * The color of a material in ambient lighting.
  45632. */
  45633. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45634. /**
  45635. * AKA Diffuse Color in other nomenclature.
  45636. */
  45637. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45638. /**
  45639. * AKA Specular Color in other nomenclature.
  45640. */
  45641. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45642. /**
  45643. * The color applied when light is reflected from a material.
  45644. */
  45645. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45646. /**
  45647. * The color applied when light is emitted from a material.
  45648. */
  45649. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45650. /**
  45651. * AKA Glossiness in other nomenclature.
  45652. */
  45653. _this._microSurface = 0.9;
  45654. /**
  45655. * source material index of refraction (IOR)' / 'destination material IOR.
  45656. */
  45657. _this._indexOfRefraction = 0.66;
  45658. /**
  45659. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45660. */
  45661. _this._invertRefractionY = false;
  45662. /**
  45663. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45664. * Materials half opaque for instance using refraction could benefit from this control.
  45665. */
  45666. _this._linkRefractionWithTransparency = false;
  45667. /**
  45668. * Specifies that the material will use the light map as a show map.
  45669. */
  45670. _this._useLightmapAsShadowmap = false;
  45671. /**
  45672. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45673. * makes the reflect vector face the model (under horizon).
  45674. */
  45675. _this._useHorizonOcclusion = true;
  45676. /**
  45677. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45678. * too much the area relying on ambient texture to define their ambient occlusion.
  45679. */
  45680. _this._useRadianceOcclusion = true;
  45681. /**
  45682. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45683. */
  45684. _this._useAlphaFromAlbedoTexture = false;
  45685. /**
  45686. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45687. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45688. */
  45689. _this._useSpecularOverAlpha = true;
  45690. /**
  45691. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45692. */
  45693. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45694. /**
  45695. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45696. */
  45697. _this._useRoughnessFromMetallicTextureAlpha = true;
  45698. /**
  45699. * Specifies if the metallic texture contains the roughness information in its green channel.
  45700. */
  45701. _this._useRoughnessFromMetallicTextureGreen = false;
  45702. /**
  45703. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45704. */
  45705. _this._useMetallnessFromMetallicTextureBlue = false;
  45706. /**
  45707. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45708. */
  45709. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45710. /**
  45711. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45712. */
  45713. _this._useAmbientInGrayScale = false;
  45714. /**
  45715. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45716. * The material will try to infer what glossiness each pixel should be.
  45717. */
  45718. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45719. /**
  45720. * Defines the falloff type used in this material.
  45721. * It by default is Physical.
  45722. */
  45723. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45724. /**
  45725. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45726. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45727. */
  45728. _this._useRadianceOverAlpha = true;
  45729. /**
  45730. * Allows using an object space normal map (instead of tangent space).
  45731. */
  45732. _this._useObjectSpaceNormalMap = false;
  45733. /**
  45734. * Allows using the bump map in parallax mode.
  45735. */
  45736. _this._useParallax = false;
  45737. /**
  45738. * Allows using the bump map in parallax occlusion mode.
  45739. */
  45740. _this._useParallaxOcclusion = false;
  45741. /**
  45742. * Controls the scale bias of the parallax mode.
  45743. */
  45744. _this._parallaxScaleBias = 0.05;
  45745. /**
  45746. * If sets to true, disables all the lights affecting the material.
  45747. */
  45748. _this._disableLighting = false;
  45749. /**
  45750. * Number of Simultaneous lights allowed on the material.
  45751. */
  45752. _this._maxSimultaneousLights = 4;
  45753. /**
  45754. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45755. */
  45756. _this._invertNormalMapX = false;
  45757. /**
  45758. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45759. */
  45760. _this._invertNormalMapY = false;
  45761. /**
  45762. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45763. */
  45764. _this._twoSidedLighting = false;
  45765. /**
  45766. * Defines the alpha limits in alpha test mode.
  45767. */
  45768. _this._alphaCutOff = 0.4;
  45769. /**
  45770. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45771. */
  45772. _this._forceAlphaTest = false;
  45773. /**
  45774. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45775. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45776. */
  45777. _this._useAlphaFresnel = false;
  45778. /**
  45779. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45780. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45781. */
  45782. _this._useLinearAlphaFresnel = false;
  45783. /**
  45784. * The transparency mode of the material.
  45785. */
  45786. _this._transparencyMode = null;
  45787. /**
  45788. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45789. * from cos thetav and roughness:
  45790. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45791. */
  45792. _this._environmentBRDFTexture = null;
  45793. /**
  45794. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45795. */
  45796. _this._forceIrradianceInFragment = false;
  45797. /**
  45798. * Force normal to face away from face.
  45799. */
  45800. _this._forceNormalForward = false;
  45801. /**
  45802. * Enables specular anti aliasing in the PBR shader.
  45803. * It will both interacts on the Geometry for analytical and IBL lighting.
  45804. * It also prefilter the roughness map based on the bump values.
  45805. */
  45806. _this._enableSpecularAntiAliasing = false;
  45807. /**
  45808. * Stores the available render targets.
  45809. */
  45810. _this._renderTargets = new BABYLON.SmartArray(16);
  45811. /**
  45812. * Sets the global ambient color for the material used in lighting calculations.
  45813. */
  45814. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45815. /**
  45816. * If set to true, no lighting calculations will be applied.
  45817. */
  45818. _this._unlit = false;
  45819. // Setup the default processing configuration to the scene.
  45820. _this._attachImageProcessingConfiguration(null);
  45821. _this.getRenderTargetTextures = function () {
  45822. _this._renderTargets.reset();
  45823. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45824. _this._renderTargets.push(_this._reflectionTexture);
  45825. }
  45826. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45827. _this._renderTargets.push(_this._refractionTexture);
  45828. }
  45829. return _this._renderTargets;
  45830. };
  45831. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45832. return _this;
  45833. }
  45834. /**
  45835. * Attaches a new image processing configuration to the PBR Material.
  45836. * @param configuration
  45837. */
  45838. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45839. var _this = this;
  45840. if (configuration === this._imageProcessingConfiguration) {
  45841. return;
  45842. }
  45843. // Detaches observer.
  45844. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45845. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45846. }
  45847. // Pick the scene configuration if needed.
  45848. if (!configuration) {
  45849. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45850. }
  45851. else {
  45852. this._imageProcessingConfiguration = configuration;
  45853. }
  45854. // Attaches observer.
  45855. if (this._imageProcessingConfiguration) {
  45856. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45857. _this._markAllSubMeshesAsImageProcessingDirty();
  45858. });
  45859. }
  45860. };
  45861. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45862. /**
  45863. * Gets a boolean indicating that current material needs to register RTT
  45864. */
  45865. get: function () {
  45866. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45867. return true;
  45868. }
  45869. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45870. return true;
  45871. }
  45872. return false;
  45873. },
  45874. enumerable: true,
  45875. configurable: true
  45876. });
  45877. /**
  45878. * Gets the name of the material class.
  45879. */
  45880. PBRBaseMaterial.prototype.getClassName = function () {
  45881. return "PBRBaseMaterial";
  45882. };
  45883. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45884. /**
  45885. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45886. */
  45887. get: function () {
  45888. return this._useLogarithmicDepth;
  45889. },
  45890. /**
  45891. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45892. */
  45893. set: function (value) {
  45894. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45895. },
  45896. enumerable: true,
  45897. configurable: true
  45898. });
  45899. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45900. /**
  45901. * Gets the current transparency mode.
  45902. */
  45903. get: function () {
  45904. return this._transparencyMode;
  45905. },
  45906. /**
  45907. * Sets the transparency mode of the material.
  45908. *
  45909. * | Value | Type | Description |
  45910. * | ----- | ----------------------------------- | ----------- |
  45911. * | 0 | OPAQUE | |
  45912. * | 1 | ALPHATEST | |
  45913. * | 2 | ALPHABLEND | |
  45914. * | 3 | ALPHATESTANDBLEND | |
  45915. *
  45916. */
  45917. set: function (value) {
  45918. if (this._transparencyMode === value) {
  45919. return;
  45920. }
  45921. this._transparencyMode = value;
  45922. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45923. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45924. },
  45925. enumerable: true,
  45926. configurable: true
  45927. });
  45928. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45929. /**
  45930. * Returns true if alpha blending should be disabled.
  45931. */
  45932. get: function () {
  45933. return (this._linkRefractionWithTransparency ||
  45934. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45935. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. /**
  45941. * Specifies whether or not this material should be rendered in alpha blend mode.
  45942. */
  45943. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45944. if (this._disableAlphaBlending) {
  45945. return false;
  45946. }
  45947. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45948. };
  45949. /**
  45950. * Specifies if the mesh will require alpha blending.
  45951. * @param mesh - BJS mesh.
  45952. */
  45953. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45954. if (this._disableAlphaBlending) {
  45955. return false;
  45956. }
  45957. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45958. };
  45959. /**
  45960. * Specifies whether or not this material should be rendered in alpha test mode.
  45961. */
  45962. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45963. if (this._forceAlphaTest) {
  45964. return true;
  45965. }
  45966. if (this._linkRefractionWithTransparency) {
  45967. return false;
  45968. }
  45969. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45970. };
  45971. /**
  45972. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45973. */
  45974. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45975. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45976. };
  45977. /**
  45978. * Gets the texture used for the alpha test.
  45979. */
  45980. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45981. return this._albedoTexture;
  45982. };
  45983. /**
  45984. * Specifies that the submesh is ready to be used.
  45985. * @param mesh - BJS mesh.
  45986. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45987. * @param useInstances - Specifies that instances should be used.
  45988. * @returns - boolean indicating that the submesh is ready or not.
  45989. */
  45990. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45991. if (subMesh.effect && this.isFrozen) {
  45992. if (this._wasPreviouslyReady) {
  45993. return true;
  45994. }
  45995. }
  45996. if (!subMesh._materialDefines) {
  45997. subMesh._materialDefines = new PBRMaterialDefines();
  45998. }
  45999. var defines = subMesh._materialDefines;
  46000. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  46001. if (defines._renderId === this.getScene().getRenderId()) {
  46002. return true;
  46003. }
  46004. }
  46005. var scene = this.getScene();
  46006. var engine = scene.getEngine();
  46007. if (defines._areTexturesDirty) {
  46008. if (scene.texturesEnabled) {
  46009. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46010. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  46011. return false;
  46012. }
  46013. }
  46014. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46015. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  46016. return false;
  46017. }
  46018. }
  46019. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46020. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  46021. return false;
  46022. }
  46023. }
  46024. var reflectionTexture = this._getReflectionTexture();
  46025. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46026. if (!reflectionTexture.isReadyOrNotBlocking()) {
  46027. return false;
  46028. }
  46029. }
  46030. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46031. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  46032. return false;
  46033. }
  46034. }
  46035. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46036. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  46037. return false;
  46038. }
  46039. }
  46040. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46041. if (this._metallicTexture) {
  46042. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  46043. return false;
  46044. }
  46045. }
  46046. else if (this._reflectivityTexture) {
  46047. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  46048. return false;
  46049. }
  46050. }
  46051. if (this._microSurfaceTexture) {
  46052. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  46053. return false;
  46054. }
  46055. }
  46056. }
  46057. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46058. // Bump texture cannot be not blocking.
  46059. if (!this._bumpTexture.isReady()) {
  46060. return false;
  46061. }
  46062. }
  46063. var refractionTexture = this._getRefractionTexture();
  46064. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46065. if (!refractionTexture.isReadyOrNotBlocking()) {
  46066. return false;
  46067. }
  46068. }
  46069. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46070. // This is blocking.
  46071. if (!this._environmentBRDFTexture.isReady()) {
  46072. return false;
  46073. }
  46074. }
  46075. }
  46076. }
  46077. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46078. if (!this._imageProcessingConfiguration.isReady()) {
  46079. return false;
  46080. }
  46081. }
  46082. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46083. mesh.createNormals(true);
  46084. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  46085. }
  46086. var previousEffect = subMesh.effect;
  46087. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  46088. if (effect) {
  46089. // Use previous effect while new one is compiling
  46090. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  46091. effect = previousEffect;
  46092. defines.markAsUnprocessed();
  46093. }
  46094. else {
  46095. scene.resetCachedMaterial();
  46096. subMesh.setEffect(effect, defines);
  46097. this.buildUniformLayout();
  46098. }
  46099. }
  46100. if (!subMesh.effect || !subMesh.effect.isReady()) {
  46101. return false;
  46102. }
  46103. defines._renderId = scene.getRenderId();
  46104. this._wasPreviouslyReady = true;
  46105. return true;
  46106. };
  46107. /**
  46108. * Specifies if the material uses metallic roughness workflow.
  46109. * @returns boolean specifiying if the material uses metallic roughness workflow.
  46110. */
  46111. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  46112. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  46113. return true;
  46114. }
  46115. return false;
  46116. };
  46117. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  46118. if (onCompiled === void 0) { onCompiled = null; }
  46119. if (onError === void 0) { onError = null; }
  46120. if (useInstances === void 0) { useInstances = null; }
  46121. if (useClipPlane === void 0) { useClipPlane = null; }
  46122. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  46123. if (!defines.isDirty) {
  46124. return null;
  46125. }
  46126. defines.markAsProcessed();
  46127. var scene = this.getScene();
  46128. var engine = scene.getEngine();
  46129. // Fallbacks
  46130. var fallbacks = new BABYLON.EffectFallbacks();
  46131. var fallbackRank = 0;
  46132. if (defines.USESPHERICALINVERTEX) {
  46133. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  46134. }
  46135. if (defines.FOG) {
  46136. fallbacks.addFallback(fallbackRank, "FOG");
  46137. }
  46138. if (defines.SPECULARAA) {
  46139. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  46140. }
  46141. if (defines.POINTSIZE) {
  46142. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  46143. }
  46144. if (defines.LOGARITHMICDEPTH) {
  46145. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  46146. }
  46147. if (defines.PARALLAX) {
  46148. fallbacks.addFallback(fallbackRank, "PARALLAX");
  46149. }
  46150. if (defines.PARALLAXOCCLUSION) {
  46151. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  46152. }
  46153. if (defines.ENVIRONMENTBRDF) {
  46154. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  46155. }
  46156. if (defines.TANGENT) {
  46157. fallbacks.addFallback(fallbackRank++, "TANGENT");
  46158. }
  46159. if (defines.BUMP) {
  46160. fallbacks.addFallback(fallbackRank++, "BUMP");
  46161. }
  46162. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  46163. if (defines.SPECULARTERM) {
  46164. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  46165. }
  46166. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  46167. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  46168. }
  46169. if (defines.LIGHTMAP) {
  46170. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  46171. }
  46172. if (defines.NORMAL) {
  46173. fallbacks.addFallback(fallbackRank++, "NORMAL");
  46174. }
  46175. if (defines.AMBIENT) {
  46176. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  46177. }
  46178. if (defines.EMISSIVE) {
  46179. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  46180. }
  46181. if (defines.VERTEXCOLOR) {
  46182. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  46183. }
  46184. if (defines.NUM_BONE_INFLUENCERS > 0) {
  46185. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  46186. }
  46187. if (defines.MORPHTARGETS) {
  46188. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  46189. }
  46190. //Attributes
  46191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46192. if (defines.NORMAL) {
  46193. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46194. }
  46195. if (defines.TANGENT) {
  46196. attribs.push(BABYLON.VertexBuffer.TangentKind);
  46197. }
  46198. if (defines.UV1) {
  46199. attribs.push(BABYLON.VertexBuffer.UVKind);
  46200. }
  46201. if (defines.UV2) {
  46202. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46203. }
  46204. if (defines.VERTEXCOLOR) {
  46205. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46206. }
  46207. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  46208. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  46209. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  46210. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46211. "vFogInfos", "vFogColor", "pointSize",
  46212. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  46213. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46214. "mBones",
  46215. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46216. "vLightingIntensity",
  46217. "logarithmicDepthConstant",
  46218. "vSphericalX", "vSphericalY", "vSphericalZ",
  46219. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46220. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46221. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  46222. "vTangentSpaceParams"
  46223. ];
  46224. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  46225. "bumpSampler", "lightmapSampler", "opacitySampler",
  46226. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  46227. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  46228. "microSurfaceSampler", "environmentBrdfSampler"];
  46229. var uniformBuffers = ["Material", "Scene"];
  46230. if (BABYLON.ImageProcessingConfiguration) {
  46231. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  46232. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  46233. }
  46234. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  46235. uniformsNames: uniforms,
  46236. uniformBuffersNames: uniformBuffers,
  46237. samplers: samplers,
  46238. defines: defines,
  46239. maxSimultaneousLights: this._maxSimultaneousLights
  46240. });
  46241. var join = defines.toString();
  46242. return engine.createEffect("pbr", {
  46243. attributes: attribs,
  46244. uniformsNames: uniforms,
  46245. uniformBuffersNames: uniformBuffers,
  46246. samplers: samplers,
  46247. defines: join,
  46248. fallbacks: fallbacks,
  46249. onCompiled: onCompiled,
  46250. onError: onError,
  46251. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  46252. }, engine);
  46253. };
  46254. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  46255. if (useInstances === void 0) { useInstances = null; }
  46256. if (useClipPlane === void 0) { useClipPlane = null; }
  46257. var scene = this.getScene();
  46258. var engine = scene.getEngine();
  46259. // Lights
  46260. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  46261. defines._needNormals = true;
  46262. // Textures
  46263. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  46264. if (defines._areTexturesDirty) {
  46265. defines._needUVs = false;
  46266. if (scene.texturesEnabled) {
  46267. if (scene.getEngine().getCaps().textureLOD) {
  46268. defines.LODBASEDMICROSFURACE = true;
  46269. }
  46270. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46271. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  46272. }
  46273. else {
  46274. defines.ALBEDO = false;
  46275. }
  46276. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  46278. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  46279. }
  46280. else {
  46281. defines.AMBIENT = false;
  46282. }
  46283. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46284. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  46285. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  46286. }
  46287. else {
  46288. defines.OPACITY = false;
  46289. }
  46290. var reflectionTexture = this._getReflectionTexture();
  46291. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46292. defines.REFLECTION = true;
  46293. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  46294. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  46295. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  46296. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  46297. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  46298. defines.INVERTCUBICMAP = true;
  46299. }
  46300. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  46301. switch (reflectionTexture.coordinatesMode) {
  46302. case BABYLON.Texture.EXPLICIT_MODE:
  46303. defines.REFLECTIONMAP_EXPLICIT = true;
  46304. break;
  46305. case BABYLON.Texture.PLANAR_MODE:
  46306. defines.REFLECTIONMAP_PLANAR = true;
  46307. break;
  46308. case BABYLON.Texture.PROJECTION_MODE:
  46309. defines.REFLECTIONMAP_PROJECTION = true;
  46310. break;
  46311. case BABYLON.Texture.SKYBOX_MODE:
  46312. defines.REFLECTIONMAP_SKYBOX = true;
  46313. break;
  46314. case BABYLON.Texture.SPHERICAL_MODE:
  46315. defines.REFLECTIONMAP_SPHERICAL = true;
  46316. break;
  46317. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  46318. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  46319. break;
  46320. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  46321. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  46322. break;
  46323. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  46324. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  46325. break;
  46326. case BABYLON.Texture.CUBIC_MODE:
  46327. case BABYLON.Texture.INVCUBIC_MODE:
  46328. default:
  46329. defines.REFLECTIONMAP_CUBIC = true;
  46330. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  46331. break;
  46332. }
  46333. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  46334. if (reflectionTexture.sphericalPolynomial) {
  46335. defines.USESPHERICALFROMREFLECTIONMAP = true;
  46336. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  46337. defines.USESPHERICALINVERTEX = false;
  46338. }
  46339. else {
  46340. defines.USESPHERICALINVERTEX = true;
  46341. }
  46342. }
  46343. }
  46344. else {
  46345. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  46346. }
  46347. }
  46348. else {
  46349. defines.REFLECTION = false;
  46350. defines.REFLECTIONMAP_3D = false;
  46351. defines.REFLECTIONMAP_SPHERICAL = false;
  46352. defines.REFLECTIONMAP_PLANAR = false;
  46353. defines.REFLECTIONMAP_CUBIC = false;
  46354. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46355. defines.REFLECTIONMAP_PROJECTION = false;
  46356. defines.REFLECTIONMAP_SKYBOX = false;
  46357. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46358. defines.REFLECTIONMAP_EXPLICIT = false;
  46359. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46360. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46361. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46362. defines.INVERTCUBICMAP = false;
  46363. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46364. defines.USESPHERICALINVERTEX = false;
  46365. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46366. defines.LODINREFLECTIONALPHA = false;
  46367. defines.GAMMAREFLECTION = false;
  46368. defines.RGBDREFLECTION = false;
  46369. }
  46370. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46372. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46373. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46374. }
  46375. else {
  46376. defines.LIGHTMAP = false;
  46377. }
  46378. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46379. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46380. }
  46381. else {
  46382. defines.EMISSIVE = false;
  46383. }
  46384. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46385. if (this._metallicTexture) {
  46386. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46387. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46388. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46389. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46390. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46391. }
  46392. else if (this._reflectivityTexture) {
  46393. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46394. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46395. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46396. }
  46397. else {
  46398. defines.REFLECTIVITY = false;
  46399. }
  46400. if (this._microSurfaceTexture) {
  46401. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46402. }
  46403. else {
  46404. defines.MICROSURFACEMAP = false;
  46405. }
  46406. }
  46407. else {
  46408. defines.REFLECTIVITY = false;
  46409. defines.MICROSURFACEMAP = false;
  46410. }
  46411. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46412. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46413. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46414. defines.PARALLAX = true;
  46415. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46416. }
  46417. else {
  46418. defines.PARALLAX = false;
  46419. }
  46420. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46421. }
  46422. else {
  46423. defines.BUMP = false;
  46424. }
  46425. var refractionTexture = this._getRefractionTexture();
  46426. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46427. defines.REFRACTION = true;
  46428. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46429. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46430. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46431. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46432. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46433. if (this._linkRefractionWithTransparency) {
  46434. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46435. }
  46436. }
  46437. else {
  46438. defines.REFRACTION = false;
  46439. }
  46440. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46441. defines.ENVIRONMENTBRDF = true;
  46442. }
  46443. else {
  46444. defines.ENVIRONMENTBRDF = false;
  46445. }
  46446. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46447. defines.ALPHAFROMALBEDO = true;
  46448. }
  46449. else {
  46450. defines.ALPHAFROMALBEDO = false;
  46451. }
  46452. }
  46453. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46454. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46455. defines.USEPHYSICALLIGHTFALLOFF = false;
  46456. defines.USEGLTFLIGHTFALLOFF = false;
  46457. }
  46458. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46459. defines.USEPHYSICALLIGHTFALLOFF = false;
  46460. defines.USEGLTFLIGHTFALLOFF = true;
  46461. }
  46462. else {
  46463. defines.USEPHYSICALLIGHTFALLOFF = true;
  46464. defines.USEGLTFLIGHTFALLOFF = false;
  46465. }
  46466. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46467. if (!this.backFaceCulling && this._twoSidedLighting) {
  46468. defines.TWOSIDEDLIGHTING = true;
  46469. }
  46470. else {
  46471. defines.TWOSIDEDLIGHTING = false;
  46472. }
  46473. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46474. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46475. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46476. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46477. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46478. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46479. }
  46480. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46481. this._imageProcessingConfiguration.prepareDefines(defines);
  46482. }
  46483. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46484. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46485. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46486. // Misc.
  46487. if (defines._areMiscDirty) {
  46488. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46489. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46490. }
  46491. // Values that need to be evaluated on every frame
  46492. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46493. // Attribs
  46494. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46495. };
  46496. /**
  46497. * Force shader compilation
  46498. */
  46499. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46500. var _this = this;
  46501. var localOptions = __assign({ clipPlane: false }, options);
  46502. var defines = new PBRMaterialDefines();
  46503. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46504. if (effect.isReady()) {
  46505. if (onCompiled) {
  46506. onCompiled(this);
  46507. }
  46508. }
  46509. else {
  46510. effect.onCompileObservable.add(function () {
  46511. if (onCompiled) {
  46512. onCompiled(_this);
  46513. }
  46514. });
  46515. }
  46516. };
  46517. /**
  46518. * Initializes the uniform buffer layout for the shader.
  46519. */
  46520. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46521. // Order is important !
  46522. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46523. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46524. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46525. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46526. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46527. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46528. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46529. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46530. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46531. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46532. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46533. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46534. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46535. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46536. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46537. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46538. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46539. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46540. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46541. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46542. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46543. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46544. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46545. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46546. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46547. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46548. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46549. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46550. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46551. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46552. this._uniformBuffer.addUniform("pointSize", 1);
  46553. this._uniformBuffer.create();
  46554. };
  46555. /**
  46556. * Unbinds the textures.
  46557. */
  46558. PBRBaseMaterial.prototype.unbind = function () {
  46559. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46560. this._uniformBuffer.setTexture("reflectionSampler", null);
  46561. }
  46562. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46563. this._uniformBuffer.setTexture("refractionSampler", null);
  46564. }
  46565. _super.prototype.unbind.call(this);
  46566. };
  46567. /**
  46568. * Binds the submesh data.
  46569. * @param world - The world matrix.
  46570. * @param mesh - The BJS mesh.
  46571. * @param subMesh - A submesh of the BJS mesh.
  46572. */
  46573. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46574. var scene = this.getScene();
  46575. var defines = subMesh._materialDefines;
  46576. if (!defines) {
  46577. return;
  46578. }
  46579. var effect = subMesh.effect;
  46580. if (!effect) {
  46581. return;
  46582. }
  46583. this._activeEffect = effect;
  46584. // Matrices
  46585. this.bindOnlyWorldMatrix(world);
  46586. // Normal Matrix
  46587. if (defines.OBJECTSPACE_NORMALMAP) {
  46588. world.toNormalMatrix(this._normalMatrix);
  46589. this.bindOnlyNormalMatrix(this._normalMatrix);
  46590. }
  46591. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46592. // Bones
  46593. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46594. var reflectionTexture = null;
  46595. if (mustRebind) {
  46596. this._uniformBuffer.bindToEffect(effect, "Material");
  46597. this.bindViewProjection(effect);
  46598. reflectionTexture = this._getReflectionTexture();
  46599. var refractionTexture = this._getRefractionTexture();
  46600. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46601. // Texture uniforms
  46602. if (scene.texturesEnabled) {
  46603. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46604. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46605. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46606. }
  46607. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46608. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46609. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46610. }
  46611. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46612. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46613. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46614. }
  46615. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46616. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46617. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46618. if (reflectionTexture.boundingBoxSize) {
  46619. var cubeTexture = reflectionTexture;
  46620. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46621. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46622. }
  46623. var polynomials = reflectionTexture.sphericalPolynomial;
  46624. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46625. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46626. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46627. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46628. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46629. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46630. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46631. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46632. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46633. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46634. }
  46635. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46636. }
  46637. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46638. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46639. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46640. }
  46641. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46642. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46643. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46644. }
  46645. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46646. if (this._metallicTexture) {
  46647. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46648. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46649. }
  46650. else if (this._reflectivityTexture) {
  46651. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46652. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46653. }
  46654. if (this._microSurfaceTexture) {
  46655. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46656. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46657. }
  46658. }
  46659. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46660. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46661. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46662. if (scene._mirroredCameraPosition) {
  46663. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46664. }
  46665. else {
  46666. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46667. }
  46668. }
  46669. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46670. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46671. var depth = 1.0;
  46672. if (!refractionTexture.isCube) {
  46673. if (refractionTexture.depth) {
  46674. depth = refractionTexture.depth;
  46675. }
  46676. }
  46677. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46678. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46679. }
  46680. }
  46681. // Point size
  46682. if (this.pointsCloud) {
  46683. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46684. }
  46685. // Colors
  46686. if (defines.METALLICWORKFLOW) {
  46687. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46688. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46689. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46690. }
  46691. else {
  46692. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46693. }
  46694. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46695. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46696. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46697. // Misc
  46698. this._lightingInfos.x = this._directIntensity;
  46699. this._lightingInfos.y = this._emissiveIntensity;
  46700. this._lightingInfos.z = this._environmentIntensity;
  46701. this._lightingInfos.w = this._specularIntensity;
  46702. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46703. }
  46704. // Textures
  46705. if (scene.texturesEnabled) {
  46706. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46707. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46708. }
  46709. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46710. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46711. }
  46712. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46713. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46714. }
  46715. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46716. if (defines.LODBASEDMICROSFURACE) {
  46717. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46718. }
  46719. else {
  46720. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46721. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46722. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46723. }
  46724. }
  46725. if (defines.ENVIRONMENTBRDF) {
  46726. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46727. }
  46728. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46729. if (defines.LODBASEDMICROSFURACE) {
  46730. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46731. }
  46732. else {
  46733. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46734. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46735. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46736. }
  46737. }
  46738. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46739. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46740. }
  46741. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46742. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46743. }
  46744. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46745. if (this._metallicTexture) {
  46746. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46747. }
  46748. else if (this._reflectivityTexture) {
  46749. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46750. }
  46751. if (this._microSurfaceTexture) {
  46752. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46753. }
  46754. }
  46755. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46756. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46757. }
  46758. }
  46759. // Clip plane
  46760. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46761. // Colors
  46762. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46763. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46764. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46765. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46766. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46767. }
  46768. if (mustRebind || !this.isFrozen) {
  46769. // Lights
  46770. if (scene.lightsEnabled && !this._disableLighting) {
  46771. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46772. }
  46773. // View
  46774. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46775. this.bindView(effect);
  46776. }
  46777. // Fog
  46778. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46779. // Morph targets
  46780. if (defines.NUM_MORPH_INFLUENCERS) {
  46781. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46782. }
  46783. // image processing
  46784. this._imageProcessingConfiguration.bind(this._activeEffect);
  46785. // Log. depth
  46786. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46787. }
  46788. this._uniformBuffer.update();
  46789. this._afterBind(mesh, this._activeEffect);
  46790. };
  46791. /**
  46792. * Returns the animatable textures.
  46793. * @returns - Array of animatable textures.
  46794. */
  46795. PBRBaseMaterial.prototype.getAnimatables = function () {
  46796. var results = [];
  46797. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46798. results.push(this._albedoTexture);
  46799. }
  46800. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46801. results.push(this._ambientTexture);
  46802. }
  46803. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46804. results.push(this._opacityTexture);
  46805. }
  46806. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46807. results.push(this._reflectionTexture);
  46808. }
  46809. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46810. results.push(this._emissiveTexture);
  46811. }
  46812. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46813. results.push(this._metallicTexture);
  46814. }
  46815. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46816. results.push(this._reflectivityTexture);
  46817. }
  46818. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46819. results.push(this._bumpTexture);
  46820. }
  46821. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46822. results.push(this._lightmapTexture);
  46823. }
  46824. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46825. results.push(this._refractionTexture);
  46826. }
  46827. return results;
  46828. };
  46829. /**
  46830. * Returns the texture used for reflections.
  46831. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46832. */
  46833. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46834. if (this._reflectionTexture) {
  46835. return this._reflectionTexture;
  46836. }
  46837. return this.getScene().environmentTexture;
  46838. };
  46839. /**
  46840. * Returns the texture used for refraction or null if none is used.
  46841. * @returns - Refection texture if present. If no refraction texture and refraction
  46842. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46843. */
  46844. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46845. if (this._refractionTexture) {
  46846. return this._refractionTexture;
  46847. }
  46848. if (this._linkRefractionWithTransparency) {
  46849. return this.getScene().environmentTexture;
  46850. }
  46851. return null;
  46852. };
  46853. /**
  46854. * Disposes the resources of the material.
  46855. * @param forceDisposeEffect - Forces the disposal of effects.
  46856. * @param forceDisposeTextures - Forces the disposal of all textures.
  46857. */
  46858. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46859. if (forceDisposeTextures) {
  46860. if (this._albedoTexture) {
  46861. this._albedoTexture.dispose();
  46862. }
  46863. if (this._ambientTexture) {
  46864. this._ambientTexture.dispose();
  46865. }
  46866. if (this._opacityTexture) {
  46867. this._opacityTexture.dispose();
  46868. }
  46869. if (this._reflectionTexture) {
  46870. this._reflectionTexture.dispose();
  46871. }
  46872. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46873. this._environmentBRDFTexture.dispose();
  46874. }
  46875. if (this._emissiveTexture) {
  46876. this._emissiveTexture.dispose();
  46877. }
  46878. if (this._metallicTexture) {
  46879. this._metallicTexture.dispose();
  46880. }
  46881. if (this._reflectivityTexture) {
  46882. this._reflectivityTexture.dispose();
  46883. }
  46884. if (this._bumpTexture) {
  46885. this._bumpTexture.dispose();
  46886. }
  46887. if (this._lightmapTexture) {
  46888. this._lightmapTexture.dispose();
  46889. }
  46890. if (this._refractionTexture) {
  46891. this._refractionTexture.dispose();
  46892. }
  46893. }
  46894. this._renderTargets.dispose();
  46895. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46896. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46897. }
  46898. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46899. };
  46900. /**
  46901. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46902. */
  46903. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46904. /**
  46905. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46906. * to enhance interoperability with other engines.
  46907. */
  46908. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46909. /**
  46910. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46911. * to enhance interoperability with other materials.
  46912. */
  46913. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46914. /**
  46915. * Stores the reflectivity values based on metallic roughness workflow.
  46916. */
  46917. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46918. __decorate([
  46919. BABYLON.serializeAsImageProcessingConfiguration()
  46920. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46921. __decorate([
  46922. BABYLON.serialize()
  46923. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46924. __decorate([
  46925. BABYLON.serialize()
  46926. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46927. return PBRBaseMaterial;
  46928. }(BABYLON.PushMaterial));
  46929. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46930. })(BABYLON || (BABYLON = {}));
  46931. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46932. var BABYLON;
  46933. (function (BABYLON) {
  46934. /**
  46935. * The Physically based simple base material of BJS.
  46936. *
  46937. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46938. * It is used as the base class for both the specGloss and metalRough conventions.
  46939. */
  46940. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46941. __extends(PBRBaseSimpleMaterial, _super);
  46942. /**
  46943. * Instantiates a new PBRMaterial instance.
  46944. *
  46945. * @param name The material name
  46946. * @param scene The scene the material will be use in.
  46947. */
  46948. function PBRBaseSimpleMaterial(name, scene) {
  46949. var _this = _super.call(this, name, scene) || this;
  46950. /**
  46951. * Number of Simultaneous lights allowed on the material.
  46952. */
  46953. _this.maxSimultaneousLights = 4;
  46954. /**
  46955. * If sets to true, disables all the lights affecting the material.
  46956. */
  46957. _this.disableLighting = false;
  46958. /**
  46959. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46960. */
  46961. _this.invertNormalMapX = false;
  46962. /**
  46963. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46964. */
  46965. _this.invertNormalMapY = false;
  46966. /**
  46967. * Emissivie color used to self-illuminate the model.
  46968. */
  46969. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46970. /**
  46971. * Occlusion Channel Strenght.
  46972. */
  46973. _this.occlusionStrength = 1.0;
  46974. /**
  46975. * If true, the light map contains occlusion information instead of lighting info.
  46976. */
  46977. _this.useLightmapAsShadowmap = false;
  46978. _this._useAlphaFromAlbedoTexture = true;
  46979. _this._useAmbientInGrayScale = true;
  46980. return _this;
  46981. }
  46982. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46983. /**
  46984. * Gets the current double sided mode.
  46985. */
  46986. get: function () {
  46987. return this._twoSidedLighting;
  46988. },
  46989. /**
  46990. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46991. */
  46992. set: function (value) {
  46993. if (this._twoSidedLighting === value) {
  46994. return;
  46995. }
  46996. this._twoSidedLighting = value;
  46997. this.backFaceCulling = !value;
  46998. this._markAllSubMeshesAsTexturesDirty();
  46999. },
  47000. enumerable: true,
  47001. configurable: true
  47002. });
  47003. /**
  47004. * Return the active textures of the material.
  47005. */
  47006. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  47007. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47008. if (this.environmentTexture) {
  47009. activeTextures.push(this.environmentTexture);
  47010. }
  47011. if (this.normalTexture) {
  47012. activeTextures.push(this.normalTexture);
  47013. }
  47014. if (this.emissiveTexture) {
  47015. activeTextures.push(this.emissiveTexture);
  47016. }
  47017. if (this.occlusionTexture) {
  47018. activeTextures.push(this.occlusionTexture);
  47019. }
  47020. if (this.lightmapTexture) {
  47021. activeTextures.push(this.lightmapTexture);
  47022. }
  47023. return activeTextures;
  47024. };
  47025. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  47026. if (_super.prototype.hasTexture.call(this, texture)) {
  47027. return true;
  47028. }
  47029. if (this.lightmapTexture === texture) {
  47030. return true;
  47031. }
  47032. return false;
  47033. };
  47034. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  47035. return "PBRBaseSimpleMaterial";
  47036. };
  47037. __decorate([
  47038. BABYLON.serialize(),
  47039. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47040. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  47041. __decorate([
  47042. BABYLON.serialize(),
  47043. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47044. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  47045. __decorate([
  47046. BABYLON.serializeAsTexture(),
  47047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  47048. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  47049. __decorate([
  47050. BABYLON.serialize(),
  47051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47052. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  47053. __decorate([
  47054. BABYLON.serialize(),
  47055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47056. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  47057. __decorate([
  47058. BABYLON.serializeAsTexture(),
  47059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  47060. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  47061. __decorate([
  47062. BABYLON.serializeAsColor3("emissive"),
  47063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47064. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  47065. __decorate([
  47066. BABYLON.serializeAsTexture(),
  47067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47068. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  47069. __decorate([
  47070. BABYLON.serialize(),
  47071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  47072. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  47073. __decorate([
  47074. BABYLON.serializeAsTexture(),
  47075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  47076. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  47077. __decorate([
  47078. BABYLON.serialize(),
  47079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  47080. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  47081. __decorate([
  47082. BABYLON.serialize()
  47083. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  47084. __decorate([
  47085. BABYLON.serializeAsTexture(),
  47086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47087. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  47088. __decorate([
  47089. BABYLON.serialize(),
  47090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47091. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47092. return PBRBaseSimpleMaterial;
  47093. }(BABYLON.PBRBaseMaterial));
  47094. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  47095. })(BABYLON || (BABYLON = {}));
  47096. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  47097. var BABYLON;
  47098. (function (BABYLON) {
  47099. /**
  47100. * The Physically based material of BJS.
  47101. *
  47102. * This offers the main features of a standard PBR material.
  47103. * For more information, please refer to the documentation :
  47104. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  47105. */
  47106. var PBRMaterial = /** @class */ (function (_super) {
  47107. __extends(PBRMaterial, _super);
  47108. /**
  47109. * Instantiates a new PBRMaterial instance.
  47110. *
  47111. * @param name The material name
  47112. * @param scene The scene the material will be use in.
  47113. */
  47114. function PBRMaterial(name, scene) {
  47115. var _this = _super.call(this, name, scene) || this;
  47116. /**
  47117. * Intensity of the direct lights e.g. the four lights available in your scene.
  47118. * This impacts both the direct diffuse and specular highlights.
  47119. */
  47120. _this.directIntensity = 1.0;
  47121. /**
  47122. * Intensity of the emissive part of the material.
  47123. * This helps controlling the emissive effect without modifying the emissive color.
  47124. */
  47125. _this.emissiveIntensity = 1.0;
  47126. /**
  47127. * Intensity of the environment e.g. how much the environment will light the object
  47128. * either through harmonics for rough material or through the refelction for shiny ones.
  47129. */
  47130. _this.environmentIntensity = 1.0;
  47131. /**
  47132. * This is a special control allowing the reduction of the specular highlights coming from the
  47133. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  47134. */
  47135. _this.specularIntensity = 1.0;
  47136. /**
  47137. * Debug Control allowing disabling the bump map on this material.
  47138. */
  47139. _this.disableBumpMap = false;
  47140. /**
  47141. * AKA Occlusion Texture Intensity in other nomenclature.
  47142. */
  47143. _this.ambientTextureStrength = 1.0;
  47144. /**
  47145. * Defines how much the AO map is occluding the analytical lights (point spot...).
  47146. * 1 means it completely occludes it
  47147. * 0 mean it has no impact
  47148. */
  47149. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  47150. /**
  47151. * The color of a material in ambient lighting.
  47152. */
  47153. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  47154. /**
  47155. * AKA Diffuse Color in other nomenclature.
  47156. */
  47157. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  47158. /**
  47159. * AKA Specular Color in other nomenclature.
  47160. */
  47161. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  47162. /**
  47163. * The color reflected from the material.
  47164. */
  47165. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  47166. /**
  47167. * The color emitted from the material.
  47168. */
  47169. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47170. /**
  47171. * AKA Glossiness in other nomenclature.
  47172. */
  47173. _this.microSurface = 1.0;
  47174. /**
  47175. * source material index of refraction (IOR)' / 'destination material IOR.
  47176. */
  47177. _this.indexOfRefraction = 0.66;
  47178. /**
  47179. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  47180. */
  47181. _this.invertRefractionY = false;
  47182. /**
  47183. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  47184. * Materials half opaque for instance using refraction could benefit from this control.
  47185. */
  47186. _this.linkRefractionWithTransparency = false;
  47187. /**
  47188. * If true, the light map contains occlusion information instead of lighting info.
  47189. */
  47190. _this.useLightmapAsShadowmap = false;
  47191. /**
  47192. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  47193. */
  47194. _this.useAlphaFromAlbedoTexture = false;
  47195. /**
  47196. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  47197. */
  47198. _this.forceAlphaTest = false;
  47199. /**
  47200. * Defines the alpha limits in alpha test mode.
  47201. */
  47202. _this.alphaCutOff = 0.4;
  47203. /**
  47204. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  47205. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  47206. */
  47207. _this.useSpecularOverAlpha = true;
  47208. /**
  47209. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  47210. */
  47211. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  47212. /**
  47213. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  47214. */
  47215. _this.useRoughnessFromMetallicTextureAlpha = true;
  47216. /**
  47217. * Specifies if the metallic texture contains the roughness information in its green channel.
  47218. */
  47219. _this.useRoughnessFromMetallicTextureGreen = false;
  47220. /**
  47221. * Specifies if the metallic texture contains the metallness information in its blue channel.
  47222. */
  47223. _this.useMetallnessFromMetallicTextureBlue = false;
  47224. /**
  47225. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  47226. */
  47227. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  47228. /**
  47229. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  47230. */
  47231. _this.useAmbientInGrayScale = false;
  47232. /**
  47233. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  47234. * The material will try to infer what glossiness each pixel should be.
  47235. */
  47236. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  47237. /**
  47238. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  47239. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  47240. */
  47241. _this.useRadianceOverAlpha = true;
  47242. /**
  47243. * Allows using an object space normal map (instead of tangent space).
  47244. */
  47245. _this.useObjectSpaceNormalMap = false;
  47246. /**
  47247. * Allows using the bump map in parallax mode.
  47248. */
  47249. _this.useParallax = false;
  47250. /**
  47251. * Allows using the bump map in parallax occlusion mode.
  47252. */
  47253. _this.useParallaxOcclusion = false;
  47254. /**
  47255. * Controls the scale bias of the parallax mode.
  47256. */
  47257. _this.parallaxScaleBias = 0.05;
  47258. /**
  47259. * If sets to true, disables all the lights affecting the material.
  47260. */
  47261. _this.disableLighting = false;
  47262. /**
  47263. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  47264. */
  47265. _this.forceIrradianceInFragment = false;
  47266. /**
  47267. * Number of Simultaneous lights allowed on the material.
  47268. */
  47269. _this.maxSimultaneousLights = 4;
  47270. /**
  47271. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47272. */
  47273. _this.invertNormalMapX = false;
  47274. /**
  47275. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47276. */
  47277. _this.invertNormalMapY = false;
  47278. /**
  47279. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47280. */
  47281. _this.twoSidedLighting = false;
  47282. /**
  47283. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47284. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  47285. */
  47286. _this.useAlphaFresnel = false;
  47287. /**
  47288. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47289. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  47290. */
  47291. _this.useLinearAlphaFresnel = false;
  47292. /**
  47293. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47294. * And/Or occlude the blended part.
  47295. */
  47296. _this.environmentBRDFTexture = null;
  47297. /**
  47298. * Force normal to face away from face.
  47299. */
  47300. _this.forceNormalForward = false;
  47301. /**
  47302. * Enables specular anti aliasing in the PBR shader.
  47303. * It will both interacts on the Geometry for analytical and IBL lighting.
  47304. * It also prefilter the roughness map based on the bump values.
  47305. */
  47306. _this.enableSpecularAntiAliasing = false;
  47307. /**
  47308. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  47309. * makes the reflect vector face the model (under horizon).
  47310. */
  47311. _this.useHorizonOcclusion = true;
  47312. /**
  47313. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  47314. * too much the area relying on ambient texture to define their ambient occlusion.
  47315. */
  47316. _this.useRadianceOcclusion = true;
  47317. /**
  47318. * If set to true, no lighting calculations will be applied.
  47319. */
  47320. _this.unlit = false;
  47321. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  47322. return _this;
  47323. }
  47324. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  47325. /**
  47326. * BJS is using an harcoded light falloff based on a manually sets up range.
  47327. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47328. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47329. */
  47330. get: function () {
  47331. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47332. },
  47333. /**
  47334. * BJS is using an harcoded light falloff based on a manually sets up range.
  47335. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47336. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47337. */
  47338. set: function (value) {
  47339. if (value !== this.usePhysicalLightFalloff) {
  47340. // Ensure the effect will be rebuilt.
  47341. this._markAllSubMeshesAsTexturesDirty();
  47342. if (value) {
  47343. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47344. }
  47345. else {
  47346. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47347. }
  47348. }
  47349. },
  47350. enumerable: true,
  47351. configurable: true
  47352. });
  47353. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47354. /**
  47355. * In order to support the falloff compatibility with gltf, a special mode has been added
  47356. * to reproduce the gltf light falloff.
  47357. */
  47358. get: function () {
  47359. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47360. },
  47361. /**
  47362. * In order to support the falloff compatibility with gltf, a special mode has been added
  47363. * to reproduce the gltf light falloff.
  47364. */
  47365. set: function (value) {
  47366. if (value !== this.useGLTFLightFalloff) {
  47367. // Ensure the effect will be rebuilt.
  47368. this._markAllSubMeshesAsTexturesDirty();
  47369. if (value) {
  47370. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47371. }
  47372. else {
  47373. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47374. }
  47375. }
  47376. },
  47377. enumerable: true,
  47378. configurable: true
  47379. });
  47380. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47381. /**
  47382. * Gets the image processing configuration used either in this material.
  47383. */
  47384. get: function () {
  47385. return this._imageProcessingConfiguration;
  47386. },
  47387. /**
  47388. * Sets the Default image processing configuration used either in the this material.
  47389. *
  47390. * If sets to null, the scene one is in use.
  47391. */
  47392. set: function (value) {
  47393. this._attachImageProcessingConfiguration(value);
  47394. // Ensure the effect will be rebuilt.
  47395. this._markAllSubMeshesAsTexturesDirty();
  47396. },
  47397. enumerable: true,
  47398. configurable: true
  47399. });
  47400. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47401. /**
  47402. * Gets wether the color curves effect is enabled.
  47403. */
  47404. get: function () {
  47405. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47406. },
  47407. /**
  47408. * Sets wether the color curves effect is enabled.
  47409. */
  47410. set: function (value) {
  47411. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47412. },
  47413. enumerable: true,
  47414. configurable: true
  47415. });
  47416. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47417. /**
  47418. * Gets wether the color grading effect is enabled.
  47419. */
  47420. get: function () {
  47421. return this.imageProcessingConfiguration.colorGradingEnabled;
  47422. },
  47423. /**
  47424. * Gets wether the color grading effect is enabled.
  47425. */
  47426. set: function (value) {
  47427. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47428. },
  47429. enumerable: true,
  47430. configurable: true
  47431. });
  47432. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47433. /**
  47434. * Gets wether tonemapping is enabled or not.
  47435. */
  47436. get: function () {
  47437. return this._imageProcessingConfiguration.toneMappingEnabled;
  47438. },
  47439. /**
  47440. * Sets wether tonemapping is enabled or not
  47441. */
  47442. set: function (value) {
  47443. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47444. },
  47445. enumerable: true,
  47446. configurable: true
  47447. });
  47448. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47449. /**
  47450. * The camera exposure used on this material.
  47451. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47452. * This corresponds to a photographic exposure.
  47453. */
  47454. get: function () {
  47455. return this._imageProcessingConfiguration.exposure;
  47456. },
  47457. /**
  47458. * The camera exposure used on this material.
  47459. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47460. * This corresponds to a photographic exposure.
  47461. */
  47462. set: function (value) {
  47463. this._imageProcessingConfiguration.exposure = value;
  47464. },
  47465. enumerable: true,
  47466. configurable: true
  47467. });
  47468. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47469. /**
  47470. * Gets The camera contrast used on this material.
  47471. */
  47472. get: function () {
  47473. return this._imageProcessingConfiguration.contrast;
  47474. },
  47475. /**
  47476. * Sets The camera contrast used on this material.
  47477. */
  47478. set: function (value) {
  47479. this._imageProcessingConfiguration.contrast = value;
  47480. },
  47481. enumerable: true,
  47482. configurable: true
  47483. });
  47484. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47485. /**
  47486. * Gets the Color Grading 2D Lookup Texture.
  47487. */
  47488. get: function () {
  47489. return this._imageProcessingConfiguration.colorGradingTexture;
  47490. },
  47491. /**
  47492. * Sets the Color Grading 2D Lookup Texture.
  47493. */
  47494. set: function (value) {
  47495. this._imageProcessingConfiguration.colorGradingTexture = value;
  47496. },
  47497. enumerable: true,
  47498. configurable: true
  47499. });
  47500. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47501. /**
  47502. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47503. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47504. * 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;
  47505. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47506. */
  47507. get: function () {
  47508. return this._imageProcessingConfiguration.colorCurves;
  47509. },
  47510. /**
  47511. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47512. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47513. * 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;
  47514. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47515. */
  47516. set: function (value) {
  47517. this._imageProcessingConfiguration.colorCurves = value;
  47518. },
  47519. enumerable: true,
  47520. configurable: true
  47521. });
  47522. /**
  47523. * Returns the name of this material class.
  47524. */
  47525. PBRMaterial.prototype.getClassName = function () {
  47526. return "PBRMaterial";
  47527. };
  47528. /**
  47529. * Returns an array of the actively used textures.
  47530. * @returns - Array of BaseTextures
  47531. */
  47532. PBRMaterial.prototype.getActiveTextures = function () {
  47533. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47534. if (this._albedoTexture) {
  47535. activeTextures.push(this._albedoTexture);
  47536. }
  47537. if (this._ambientTexture) {
  47538. activeTextures.push(this._ambientTexture);
  47539. }
  47540. if (this._opacityTexture) {
  47541. activeTextures.push(this._opacityTexture);
  47542. }
  47543. if (this._reflectionTexture) {
  47544. activeTextures.push(this._reflectionTexture);
  47545. }
  47546. if (this._emissiveTexture) {
  47547. activeTextures.push(this._emissiveTexture);
  47548. }
  47549. if (this._reflectivityTexture) {
  47550. activeTextures.push(this._reflectivityTexture);
  47551. }
  47552. if (this._metallicTexture) {
  47553. activeTextures.push(this._metallicTexture);
  47554. }
  47555. if (this._microSurfaceTexture) {
  47556. activeTextures.push(this._microSurfaceTexture);
  47557. }
  47558. if (this._bumpTexture) {
  47559. activeTextures.push(this._bumpTexture);
  47560. }
  47561. if (this._lightmapTexture) {
  47562. activeTextures.push(this._lightmapTexture);
  47563. }
  47564. if (this._refractionTexture) {
  47565. activeTextures.push(this._refractionTexture);
  47566. }
  47567. return activeTextures;
  47568. };
  47569. /**
  47570. * Checks to see if a texture is used in the material.
  47571. * @param texture - Base texture to use.
  47572. * @returns - Boolean specifying if a texture is used in the material.
  47573. */
  47574. PBRMaterial.prototype.hasTexture = function (texture) {
  47575. if (_super.prototype.hasTexture.call(this, texture)) {
  47576. return true;
  47577. }
  47578. if (this._albedoTexture === texture) {
  47579. return true;
  47580. }
  47581. if (this._ambientTexture === texture) {
  47582. return true;
  47583. }
  47584. if (this._opacityTexture === texture) {
  47585. return true;
  47586. }
  47587. if (this._reflectionTexture === texture) {
  47588. return true;
  47589. }
  47590. if (this._reflectivityTexture === texture) {
  47591. return true;
  47592. }
  47593. if (this._metallicTexture === texture) {
  47594. return true;
  47595. }
  47596. if (this._microSurfaceTexture === texture) {
  47597. return true;
  47598. }
  47599. if (this._bumpTexture === texture) {
  47600. return true;
  47601. }
  47602. if (this._lightmapTexture === texture) {
  47603. return true;
  47604. }
  47605. if (this._refractionTexture === texture) {
  47606. return true;
  47607. }
  47608. return false;
  47609. };
  47610. /**
  47611. * Makes a duplicate of the current material.
  47612. * @param name - name to use for the new material.
  47613. */
  47614. PBRMaterial.prototype.clone = function (name) {
  47615. var _this = this;
  47616. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47617. clone.id = name;
  47618. clone.name = name;
  47619. return clone;
  47620. };
  47621. /**
  47622. * Serializes this PBR Material.
  47623. * @returns - An object with the serialized material.
  47624. */
  47625. PBRMaterial.prototype.serialize = function () {
  47626. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47627. serializationObject.customType = "BABYLON.PBRMaterial";
  47628. return serializationObject;
  47629. };
  47630. // Statics
  47631. /**
  47632. * Parses a PBR Material from a serialized object.
  47633. * @param source - Serialized object.
  47634. * @param scene - BJS scene instance.
  47635. * @param rootUrl - url for the scene object
  47636. * @returns - PBRMaterial
  47637. */
  47638. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47639. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47640. };
  47641. /**
  47642. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47643. */
  47644. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47645. /**
  47646. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47647. */
  47648. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47649. /**
  47650. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47651. */
  47652. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47653. /**
  47654. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47655. * They are also discarded below the alpha cutoff threshold to improve performances.
  47656. */
  47657. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47658. /**
  47659. * Defines the default value of how much AO map is occluding the analytical lights
  47660. * (point spot...).
  47661. */
  47662. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47663. __decorate([
  47664. BABYLON.serialize(),
  47665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47666. ], PBRMaterial.prototype, "directIntensity", void 0);
  47667. __decorate([
  47668. BABYLON.serialize(),
  47669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47670. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47671. __decorate([
  47672. BABYLON.serialize(),
  47673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47674. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47675. __decorate([
  47676. BABYLON.serialize(),
  47677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47678. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47679. __decorate([
  47680. BABYLON.serialize(),
  47681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47682. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47683. __decorate([
  47684. BABYLON.serializeAsTexture(),
  47685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47686. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47687. __decorate([
  47688. BABYLON.serializeAsTexture(),
  47689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47690. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47691. __decorate([
  47692. BABYLON.serialize(),
  47693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47694. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47695. __decorate([
  47696. BABYLON.serialize(),
  47697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47698. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47699. __decorate([
  47700. BABYLON.serializeAsTexture(),
  47701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47702. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47703. __decorate([
  47704. BABYLON.serializeAsTexture(),
  47705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47706. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47707. __decorate([
  47708. BABYLON.serializeAsTexture(),
  47709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47710. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47711. __decorate([
  47712. BABYLON.serializeAsTexture(),
  47713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47714. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47715. __decorate([
  47716. BABYLON.serializeAsTexture(),
  47717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47718. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47719. __decorate([
  47720. BABYLON.serialize(),
  47721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47722. ], PBRMaterial.prototype, "metallic", void 0);
  47723. __decorate([
  47724. BABYLON.serialize(),
  47725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47726. ], PBRMaterial.prototype, "roughness", void 0);
  47727. __decorate([
  47728. BABYLON.serializeAsTexture(),
  47729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47730. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47731. __decorate([
  47732. BABYLON.serializeAsTexture(),
  47733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47734. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47735. __decorate([
  47736. BABYLON.serializeAsTexture(),
  47737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47738. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47739. __decorate([
  47740. BABYLON.serializeAsTexture(),
  47741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47742. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47743. __decorate([
  47744. BABYLON.serializeAsColor3("ambient"),
  47745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47746. ], PBRMaterial.prototype, "ambientColor", void 0);
  47747. __decorate([
  47748. BABYLON.serializeAsColor3("albedo"),
  47749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47750. ], PBRMaterial.prototype, "albedoColor", void 0);
  47751. __decorate([
  47752. BABYLON.serializeAsColor3("reflectivity"),
  47753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47754. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47755. __decorate([
  47756. BABYLON.serializeAsColor3("reflection"),
  47757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47758. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47759. __decorate([
  47760. BABYLON.serializeAsColor3("emissive"),
  47761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47762. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47763. __decorate([
  47764. BABYLON.serialize(),
  47765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47766. ], PBRMaterial.prototype, "microSurface", void 0);
  47767. __decorate([
  47768. BABYLON.serialize(),
  47769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47770. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47771. __decorate([
  47772. BABYLON.serialize(),
  47773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47774. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47775. __decorate([
  47776. BABYLON.serialize(),
  47777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47778. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47779. __decorate([
  47780. BABYLON.serialize(),
  47781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47782. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47783. __decorate([
  47784. BABYLON.serialize(),
  47785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47786. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47787. __decorate([
  47788. BABYLON.serialize(),
  47789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47790. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47791. __decorate([
  47792. BABYLON.serialize(),
  47793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47794. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47795. __decorate([
  47796. BABYLON.serialize(),
  47797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47798. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47799. __decorate([
  47800. BABYLON.serialize(),
  47801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47802. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47803. __decorate([
  47804. BABYLON.serialize(),
  47805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47806. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47807. __decorate([
  47808. BABYLON.serialize(),
  47809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47810. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47811. __decorate([
  47812. BABYLON.serialize(),
  47813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47814. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47815. __decorate([
  47816. BABYLON.serialize(),
  47817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47818. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47819. __decorate([
  47820. BABYLON.serialize(),
  47821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47822. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47823. __decorate([
  47824. BABYLON.serialize(),
  47825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47826. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47827. __decorate([
  47828. BABYLON.serialize()
  47829. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47830. __decorate([
  47831. BABYLON.serialize()
  47832. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47833. __decorate([
  47834. BABYLON.serialize(),
  47835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47836. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47837. __decorate([
  47838. BABYLON.serialize(),
  47839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47840. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47841. __decorate([
  47842. BABYLON.serialize(),
  47843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47844. ], PBRMaterial.prototype, "useParallax", void 0);
  47845. __decorate([
  47846. BABYLON.serialize(),
  47847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47848. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47849. __decorate([
  47850. BABYLON.serialize(),
  47851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47852. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47853. __decorate([
  47854. BABYLON.serialize(),
  47855. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47856. ], PBRMaterial.prototype, "disableLighting", void 0);
  47857. __decorate([
  47858. BABYLON.serialize(),
  47859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47860. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47861. __decorate([
  47862. BABYLON.serialize(),
  47863. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47864. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47865. __decorate([
  47866. BABYLON.serialize(),
  47867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47868. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47869. __decorate([
  47870. BABYLON.serialize(),
  47871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47872. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47873. __decorate([
  47874. BABYLON.serialize(),
  47875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47876. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47877. __decorate([
  47878. BABYLON.serialize(),
  47879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47880. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47881. __decorate([
  47882. BABYLON.serialize(),
  47883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47884. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47885. __decorate([
  47886. BABYLON.serializeAsTexture(),
  47887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47888. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47889. __decorate([
  47890. BABYLON.serialize(),
  47891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47892. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47893. __decorate([
  47894. BABYLON.serialize(),
  47895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47896. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47897. __decorate([
  47898. BABYLON.serialize(),
  47899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47900. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47901. __decorate([
  47902. BABYLON.serialize(),
  47903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47904. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47905. __decorate([
  47906. BABYLON.serialize(),
  47907. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47908. ], PBRMaterial.prototype, "unlit", void 0);
  47909. return PBRMaterial;
  47910. }(BABYLON.PBRBaseMaterial));
  47911. BABYLON.PBRMaterial = PBRMaterial;
  47912. })(BABYLON || (BABYLON = {}));
  47913. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47914. var BABYLON;
  47915. (function (BABYLON) {
  47916. /**
  47917. * The PBR material of BJS following the metal roughness convention.
  47918. *
  47919. * This fits to the PBR convention in the GLTF definition:
  47920. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47921. */
  47922. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47923. __extends(PBRMetallicRoughnessMaterial, _super);
  47924. /**
  47925. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47926. *
  47927. * @param name The material name
  47928. * @param scene The scene the material will be use in.
  47929. */
  47930. function PBRMetallicRoughnessMaterial(name, scene) {
  47931. var _this = _super.call(this, name, scene) || this;
  47932. _this._useRoughnessFromMetallicTextureAlpha = false;
  47933. _this._useRoughnessFromMetallicTextureGreen = true;
  47934. _this._useMetallnessFromMetallicTextureBlue = true;
  47935. _this.metallic = 1.0;
  47936. _this.roughness = 1.0;
  47937. return _this;
  47938. }
  47939. /**
  47940. * Return the currrent class name of the material.
  47941. */
  47942. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47943. return "PBRMetallicRoughnessMaterial";
  47944. };
  47945. /**
  47946. * Return the active textures of the material.
  47947. */
  47948. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47949. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47950. if (this.baseTexture) {
  47951. activeTextures.push(this.baseTexture);
  47952. }
  47953. if (this.metallicRoughnessTexture) {
  47954. activeTextures.push(this.metallicRoughnessTexture);
  47955. }
  47956. return activeTextures;
  47957. };
  47958. /**
  47959. * Checks to see if a texture is used in the material.
  47960. * @param texture - Base texture to use.
  47961. * @returns - Boolean specifying if a texture is used in the material.
  47962. */
  47963. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47964. if (_super.prototype.hasTexture.call(this, texture)) {
  47965. return true;
  47966. }
  47967. if (this.baseTexture === texture) {
  47968. return true;
  47969. }
  47970. if (this.metallicRoughnessTexture === texture) {
  47971. return true;
  47972. }
  47973. return false;
  47974. };
  47975. /**
  47976. * Makes a duplicate of the current material.
  47977. * @param name - name to use for the new material.
  47978. */
  47979. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47980. var _this = this;
  47981. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47982. clone.id = name;
  47983. clone.name = name;
  47984. return clone;
  47985. };
  47986. /**
  47987. * Serialize the material to a parsable JSON object.
  47988. */
  47989. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47990. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47991. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47992. return serializationObject;
  47993. };
  47994. /**
  47995. * Parses a JSON object correponding to the serialize function.
  47996. */
  47997. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47998. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47999. };
  48000. __decorate([
  48001. BABYLON.serializeAsColor3(),
  48002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48003. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  48004. __decorate([
  48005. BABYLON.serializeAsTexture(),
  48006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48007. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  48008. __decorate([
  48009. BABYLON.serialize(),
  48010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48011. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  48012. __decorate([
  48013. BABYLON.serialize(),
  48014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48015. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  48016. __decorate([
  48017. BABYLON.serializeAsTexture(),
  48018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  48019. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  48020. return PBRMetallicRoughnessMaterial;
  48021. }(BABYLON.PBRBaseSimpleMaterial));
  48022. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  48023. })(BABYLON || (BABYLON = {}));
  48024. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  48025. var BABYLON;
  48026. (function (BABYLON) {
  48027. /**
  48028. * The PBR material of BJS following the specular glossiness convention.
  48029. *
  48030. * This fits to the PBR convention in the GLTF definition:
  48031. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  48032. */
  48033. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  48034. __extends(PBRSpecularGlossinessMaterial, _super);
  48035. /**
  48036. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  48037. *
  48038. * @param name The material name
  48039. * @param scene The scene the material will be use in.
  48040. */
  48041. function PBRSpecularGlossinessMaterial(name, scene) {
  48042. var _this = _super.call(this, name, scene) || this;
  48043. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  48044. return _this;
  48045. }
  48046. /**
  48047. * Return the currrent class name of the material.
  48048. */
  48049. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  48050. return "PBRSpecularGlossinessMaterial";
  48051. };
  48052. /**
  48053. * Return the active textures of the material.
  48054. */
  48055. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  48056. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48057. if (this.diffuseTexture) {
  48058. activeTextures.push(this.diffuseTexture);
  48059. }
  48060. if (this.specularGlossinessTexture) {
  48061. activeTextures.push(this.specularGlossinessTexture);
  48062. }
  48063. return activeTextures;
  48064. };
  48065. /**
  48066. * Checks to see if a texture is used in the material.
  48067. * @param texture - Base texture to use.
  48068. * @returns - Boolean specifying if a texture is used in the material.
  48069. */
  48070. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  48071. if (_super.prototype.hasTexture.call(this, texture)) {
  48072. return true;
  48073. }
  48074. if (this.diffuseTexture === texture) {
  48075. return true;
  48076. }
  48077. if (this.specularGlossinessTexture === texture) {
  48078. return true;
  48079. }
  48080. return false;
  48081. };
  48082. /**
  48083. * Makes a duplicate of the current material.
  48084. * @param name - name to use for the new material.
  48085. */
  48086. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  48087. var _this = this;
  48088. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  48089. clone.id = name;
  48090. clone.name = name;
  48091. return clone;
  48092. };
  48093. /**
  48094. * Serialize the material to a parsable JSON object.
  48095. */
  48096. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  48097. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48098. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  48099. return serializationObject;
  48100. };
  48101. /**
  48102. * Parses a JSON object correponding to the serialize function.
  48103. */
  48104. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  48105. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  48106. };
  48107. __decorate([
  48108. BABYLON.serializeAsColor3("diffuse"),
  48109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48110. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  48111. __decorate([
  48112. BABYLON.serializeAsTexture(),
  48113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48114. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  48115. __decorate([
  48116. BABYLON.serializeAsColor3("specular"),
  48117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  48118. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  48119. __decorate([
  48120. BABYLON.serialize(),
  48121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  48122. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  48123. __decorate([
  48124. BABYLON.serializeAsTexture(),
  48125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  48126. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  48127. return PBRSpecularGlossinessMaterial;
  48128. }(BABYLON.PBRBaseSimpleMaterial));
  48129. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  48130. })(BABYLON || (BABYLON = {}));
  48131. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  48132. var BABYLON;
  48133. (function (BABYLON) {
  48134. /**
  48135. * @ignore
  48136. * This is a list of all the different input types that are available in the application.
  48137. * Fo instance: ArcRotateCameraGamepadInput...
  48138. */
  48139. BABYLON.CameraInputTypes = {};
  48140. /**
  48141. * This represents the input manager used within a camera.
  48142. * It helps dealing with all the different kind of input attached to a camera.
  48143. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48144. */
  48145. var CameraInputsManager = /** @class */ (function () {
  48146. /**
  48147. * Instantiate a new Camera Input Manager.
  48148. * @param camera Defines the camera the input manager blongs to
  48149. */
  48150. function CameraInputsManager(camera) {
  48151. this.attached = {};
  48152. this.camera = camera;
  48153. this.checkInputs = function () { };
  48154. }
  48155. /**
  48156. * Add an input method to a camera
  48157. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48158. * @param input camera input method
  48159. */
  48160. CameraInputsManager.prototype.add = function (input) {
  48161. var type = input.getSimpleName();
  48162. if (this.attached[type]) {
  48163. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  48164. return;
  48165. }
  48166. this.attached[type] = input;
  48167. input.camera = this.camera;
  48168. //for checkInputs, we are dynamically creating a function
  48169. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  48170. if (input.checkInputs) {
  48171. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48172. }
  48173. if (this.attachedElement) {
  48174. input.attachControl(this.attachedElement);
  48175. }
  48176. };
  48177. /**
  48178. * Remove a specific input method from a camera
  48179. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  48180. * @param inputToRemove camera input method
  48181. */
  48182. CameraInputsManager.prototype.remove = function (inputToRemove) {
  48183. for (var cam in this.attached) {
  48184. var input = this.attached[cam];
  48185. if (input === inputToRemove) {
  48186. input.detachControl(this.attachedElement);
  48187. input.camera = null;
  48188. delete this.attached[cam];
  48189. this.rebuildInputCheck();
  48190. }
  48191. }
  48192. };
  48193. /**
  48194. * Remove a specific input type from a camera
  48195. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  48196. * @param inputType the type of the input to remove
  48197. */
  48198. CameraInputsManager.prototype.removeByType = function (inputType) {
  48199. for (var cam in this.attached) {
  48200. var input = this.attached[cam];
  48201. if (input.getClassName() === inputType) {
  48202. input.detachControl(this.attachedElement);
  48203. input.camera = null;
  48204. delete this.attached[cam];
  48205. this.rebuildInputCheck();
  48206. }
  48207. }
  48208. };
  48209. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  48210. var current = this.checkInputs;
  48211. return function () {
  48212. current();
  48213. fn();
  48214. };
  48215. };
  48216. /**
  48217. * Attach the input controls to the currently attached dom element to listen the events from.
  48218. * @param input Defines the input to attach
  48219. */
  48220. CameraInputsManager.prototype.attachInput = function (input) {
  48221. if (this.attachedElement) {
  48222. input.attachControl(this.attachedElement, this.noPreventDefault);
  48223. }
  48224. };
  48225. /**
  48226. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  48227. * @param element Defines the dom element to collect the events from
  48228. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48229. */
  48230. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  48231. if (noPreventDefault === void 0) { noPreventDefault = false; }
  48232. if (this.attachedElement) {
  48233. return;
  48234. }
  48235. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48236. this.attachedElement = element;
  48237. this.noPreventDefault = noPreventDefault;
  48238. for (var cam in this.attached) {
  48239. this.attached[cam].attachControl(element, noPreventDefault);
  48240. }
  48241. };
  48242. /**
  48243. * Detach the current manager inputs controls from a specific dom element.
  48244. * @param element Defines the dom element to collect the events from
  48245. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  48246. */
  48247. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  48248. if (disconnect === void 0) { disconnect = false; }
  48249. if (this.attachedElement !== element) {
  48250. return;
  48251. }
  48252. for (var cam in this.attached) {
  48253. this.attached[cam].detachControl(element);
  48254. if (disconnect) {
  48255. this.attached[cam].camera = null;
  48256. }
  48257. }
  48258. this.attachedElement = null;
  48259. };
  48260. /**
  48261. * Rebuild the dynamic inputCheck function from the current list of
  48262. * defined inputs in the manager.
  48263. */
  48264. CameraInputsManager.prototype.rebuildInputCheck = function () {
  48265. this.checkInputs = function () { };
  48266. for (var cam in this.attached) {
  48267. var input = this.attached[cam];
  48268. if (input.checkInputs) {
  48269. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48270. }
  48271. }
  48272. };
  48273. /**
  48274. * Remove all attached input methods from a camera
  48275. */
  48276. CameraInputsManager.prototype.clear = function () {
  48277. if (this.attachedElement) {
  48278. this.detachElement(this.attachedElement, true);
  48279. }
  48280. this.attached = {};
  48281. this.attachedElement = null;
  48282. this.checkInputs = function () { };
  48283. };
  48284. /**
  48285. * Serialize the current input manager attached to a camera.
  48286. * This ensures than once parsed,
  48287. * the input associated to the camera will be identical to the current ones
  48288. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  48289. */
  48290. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  48291. var inputs = {};
  48292. for (var cam in this.attached) {
  48293. var input = this.attached[cam];
  48294. var res = BABYLON.SerializationHelper.Serialize(input);
  48295. inputs[input.getClassName()] = res;
  48296. }
  48297. serializedCamera.inputsmgr = inputs;
  48298. };
  48299. /**
  48300. * Parses an input manager serialized JSON to restore the previous list of inputs
  48301. * and states associated to a camera.
  48302. * @param parsedCamera Defines the JSON to parse
  48303. */
  48304. CameraInputsManager.prototype.parse = function (parsedCamera) {
  48305. var parsedInputs = parsedCamera.inputsmgr;
  48306. if (parsedInputs) {
  48307. this.clear();
  48308. for (var n in parsedInputs) {
  48309. var construct = BABYLON.CameraInputTypes[n];
  48310. if (construct) {
  48311. var parsedinput = parsedInputs[n];
  48312. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  48313. this.add(input);
  48314. }
  48315. }
  48316. }
  48317. else {
  48318. //2016-03-08 this part is for managing backward compatibility
  48319. for (var n in this.attached) {
  48320. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  48321. if (construct) {
  48322. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  48323. this.remove(this.attached[n]);
  48324. this.add(input);
  48325. }
  48326. }
  48327. }
  48328. };
  48329. return CameraInputsManager;
  48330. }());
  48331. BABYLON.CameraInputsManager = CameraInputsManager;
  48332. })(BABYLON || (BABYLON = {}));
  48333. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  48334. var BABYLON;
  48335. (function (BABYLON) {
  48336. /**
  48337. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  48338. * This is the base of the follow, arc rotate cameras and Free camera
  48339. * @see http://doc.babylonjs.com/features/cameras
  48340. */
  48341. var TargetCamera = /** @class */ (function (_super) {
  48342. __extends(TargetCamera, _super);
  48343. /**
  48344. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  48345. * This is the base of the follow, arc rotate cameras and Free camera
  48346. * @see http://doc.babylonjs.com/features/cameras
  48347. * @param name Defines the name of the camera in the scene
  48348. * @param position Defines the start position of the camera in the scene
  48349. * @param scene Defines the scene the camera belongs to
  48350. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48351. */
  48352. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48353. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48354. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48355. /**
  48356. * Define the current direction the camera is moving to
  48357. */
  48358. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48359. /**
  48360. * Define the current rotation the camera is rotating to
  48361. */
  48362. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48363. /**
  48364. * Define the current rotation of the camera
  48365. */
  48366. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48367. /**
  48368. * Define the current speed of the camera
  48369. */
  48370. _this.speed = 2.0;
  48371. /**
  48372. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48373. * around all axis.
  48374. */
  48375. _this.noRotationConstraint = false;
  48376. /**
  48377. * Define the current target of the camera as an object or a position.
  48378. */
  48379. _this.lockedTarget = null;
  48380. /** @hidden */
  48381. _this._currentTarget = BABYLON.Vector3.Zero();
  48382. /** @hidden */
  48383. _this._viewMatrix = BABYLON.Matrix.Zero();
  48384. /** @hidden */
  48385. _this._camMatrix = BABYLON.Matrix.Zero();
  48386. /** @hidden */
  48387. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48388. /** @hidden */
  48389. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48390. /** @hidden */
  48391. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48392. /** @hidden */
  48393. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48394. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48395. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48396. _this._defaultUp = BABYLON.Vector3.Up();
  48397. _this._cachedRotationZ = 0;
  48398. _this._cachedQuaternionRotationZ = 0;
  48399. return _this;
  48400. }
  48401. /**
  48402. * Gets the position in front of the camera at a given distance.
  48403. * @param distance The distance from the camera we want the position to be
  48404. * @returns the position
  48405. */
  48406. TargetCamera.prototype.getFrontPosition = function (distance) {
  48407. this.getWorldMatrix();
  48408. var direction = this.getTarget().subtract(this.position);
  48409. direction.normalize();
  48410. direction.scaleInPlace(distance);
  48411. return this.globalPosition.add(direction);
  48412. };
  48413. /** @hidden */
  48414. TargetCamera.prototype._getLockedTargetPosition = function () {
  48415. if (!this.lockedTarget) {
  48416. return null;
  48417. }
  48418. if (this.lockedTarget.absolutePosition) {
  48419. this.lockedTarget.computeWorldMatrix();
  48420. }
  48421. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48422. };
  48423. /**
  48424. * Store current camera state of the camera (fov, position, rotation, etc..)
  48425. * @returns the camera
  48426. */
  48427. TargetCamera.prototype.storeState = function () {
  48428. this._storedPosition = this.position.clone();
  48429. this._storedRotation = this.rotation.clone();
  48430. if (this.rotationQuaternion) {
  48431. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48432. }
  48433. return _super.prototype.storeState.call(this);
  48434. };
  48435. /**
  48436. * Restored camera state. You must call storeState() first
  48437. * @returns whether it was successful or not
  48438. * @hidden
  48439. */
  48440. TargetCamera.prototype._restoreStateValues = function () {
  48441. if (!_super.prototype._restoreStateValues.call(this)) {
  48442. return false;
  48443. }
  48444. this.position = this._storedPosition.clone();
  48445. this.rotation = this._storedRotation.clone();
  48446. if (this.rotationQuaternion) {
  48447. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48448. }
  48449. this.cameraDirection.copyFromFloats(0, 0, 0);
  48450. this.cameraRotation.copyFromFloats(0, 0);
  48451. return true;
  48452. };
  48453. /** @hidden */
  48454. TargetCamera.prototype._initCache = function () {
  48455. _super.prototype._initCache.call(this);
  48456. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48457. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48458. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48459. };
  48460. /** @hidden */
  48461. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48462. if (!ignoreParentClass) {
  48463. _super.prototype._updateCache.call(this);
  48464. }
  48465. var lockedTargetPosition = this._getLockedTargetPosition();
  48466. if (!lockedTargetPosition) {
  48467. this._cache.lockedTarget = null;
  48468. }
  48469. else {
  48470. if (!this._cache.lockedTarget) {
  48471. this._cache.lockedTarget = lockedTargetPosition.clone();
  48472. }
  48473. else {
  48474. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48475. }
  48476. }
  48477. this._cache.rotation.copyFrom(this.rotation);
  48478. if (this.rotationQuaternion) {
  48479. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48480. }
  48481. };
  48482. // Synchronized
  48483. /** @hidden */
  48484. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48485. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48486. return false;
  48487. }
  48488. var lockedTargetPosition = this._getLockedTargetPosition();
  48489. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48490. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48491. };
  48492. // Methods
  48493. /** @hidden */
  48494. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48495. var engine = this.getEngine();
  48496. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48497. };
  48498. // Target
  48499. /** @hidden */
  48500. TargetCamera.prototype.setTarget = function (target) {
  48501. this.upVector.normalize();
  48502. if (this.position.z === target.z) {
  48503. this.position.z += BABYLON.Epsilon;
  48504. }
  48505. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48506. this._camMatrix.invert();
  48507. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48508. var vDir = target.subtract(this.position);
  48509. if (vDir.x >= 0.0) {
  48510. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48511. }
  48512. else {
  48513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48514. }
  48515. this.rotation.z = 0;
  48516. if (isNaN(this.rotation.x)) {
  48517. this.rotation.x = 0;
  48518. }
  48519. if (isNaN(this.rotation.y)) {
  48520. this.rotation.y = 0;
  48521. }
  48522. if (isNaN(this.rotation.z)) {
  48523. this.rotation.z = 0;
  48524. }
  48525. if (this.rotationQuaternion) {
  48526. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48527. }
  48528. };
  48529. /**
  48530. * Return the current target position of the camera. This value is expressed in local space.
  48531. * @returns the target position
  48532. */
  48533. TargetCamera.prototype.getTarget = function () {
  48534. return this._currentTarget;
  48535. };
  48536. /** @hidden */
  48537. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48538. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48539. };
  48540. /** @hidden */
  48541. TargetCamera.prototype._updatePosition = function () {
  48542. if (this.parent) {
  48543. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48544. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48545. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48546. return;
  48547. }
  48548. this.position.addInPlace(this.cameraDirection);
  48549. };
  48550. /** @hidden */
  48551. TargetCamera.prototype._checkInputs = function () {
  48552. var needToMove = this._decideIfNeedsToMove();
  48553. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48554. // Move
  48555. if (needToMove) {
  48556. this._updatePosition();
  48557. }
  48558. // Rotate
  48559. if (needToRotate) {
  48560. this.rotation.x += this.cameraRotation.x;
  48561. this.rotation.y += this.cameraRotation.y;
  48562. //rotate, if quaternion is set and rotation was used
  48563. if (this.rotationQuaternion) {
  48564. var len = this.rotation.lengthSquared();
  48565. if (len) {
  48566. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48567. }
  48568. }
  48569. if (!this.noRotationConstraint) {
  48570. var limit = (Math.PI / 2) * 0.95;
  48571. if (this.rotation.x > limit) {
  48572. this.rotation.x = limit;
  48573. }
  48574. if (this.rotation.x < -limit) {
  48575. this.rotation.x = -limit;
  48576. }
  48577. }
  48578. }
  48579. // Inertia
  48580. if (needToMove) {
  48581. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48582. this.cameraDirection.x = 0;
  48583. }
  48584. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48585. this.cameraDirection.y = 0;
  48586. }
  48587. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48588. this.cameraDirection.z = 0;
  48589. }
  48590. this.cameraDirection.scaleInPlace(this.inertia);
  48591. }
  48592. if (needToRotate) {
  48593. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48594. this.cameraRotation.x = 0;
  48595. }
  48596. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48597. this.cameraRotation.y = 0;
  48598. }
  48599. this.cameraRotation.scaleInPlace(this.inertia);
  48600. }
  48601. _super.prototype._checkInputs.call(this);
  48602. };
  48603. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48604. if (this.rotationQuaternion) {
  48605. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48606. }
  48607. else {
  48608. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48609. }
  48610. };
  48611. /**
  48612. * 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)
  48613. * @returns the current camera
  48614. */
  48615. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48616. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48617. return this;
  48618. };
  48619. /** @hidden */
  48620. TargetCamera.prototype._getViewMatrix = function () {
  48621. if (this.lockedTarget) {
  48622. this.setTarget(this._getLockedTargetPosition());
  48623. }
  48624. // Compute
  48625. this._updateCameraRotationMatrix();
  48626. // Apply the changed rotation to the upVector
  48627. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48628. this._rotateUpVectorWithCameraRotationMatrix();
  48629. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48630. }
  48631. else if (this._cachedRotationZ != this.rotation.z) {
  48632. this._rotateUpVectorWithCameraRotationMatrix();
  48633. this._cachedRotationZ = this.rotation.z;
  48634. }
  48635. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48636. // Computing target and final matrix
  48637. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48638. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48639. return this._viewMatrix;
  48640. };
  48641. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48642. if (this.parent) {
  48643. var parentWorldMatrix = this.parent.getWorldMatrix();
  48644. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48645. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48646. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48647. this._markSyncedWithParent();
  48648. }
  48649. else {
  48650. this._globalPosition.copyFrom(position);
  48651. this._globalCurrentTarget.copyFrom(target);
  48652. this._globalCurrentUpVector.copyFrom(up);
  48653. }
  48654. if (this.getScene().useRightHandedSystem) {
  48655. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48656. }
  48657. else {
  48658. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48659. }
  48660. };
  48661. /**
  48662. * @hidden
  48663. */
  48664. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48665. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48666. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48667. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48668. if (!this.rotationQuaternion) {
  48669. this.rotationQuaternion = new BABYLON.Quaternion();
  48670. }
  48671. rigCamera._cameraRigParams = {};
  48672. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48673. }
  48674. return rigCamera;
  48675. }
  48676. return null;
  48677. };
  48678. /**
  48679. * @hidden
  48680. */
  48681. TargetCamera.prototype._updateRigCameras = function () {
  48682. var camLeft = this._rigCameras[0];
  48683. var camRight = this._rigCameras[1];
  48684. switch (this.cameraRigMode) {
  48685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48686. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48689. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48690. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48691. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48692. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48693. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48694. camLeft.setTarget(this.getTarget());
  48695. camRight.setTarget(this.getTarget());
  48696. break;
  48697. case BABYLON.Camera.RIG_MODE_VR:
  48698. if (camLeft.rotationQuaternion) {
  48699. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48700. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48701. }
  48702. else {
  48703. camLeft.rotation.copyFrom(this.rotation);
  48704. camRight.rotation.copyFrom(this.rotation);
  48705. }
  48706. camLeft.position.copyFrom(this.position);
  48707. camRight.position.copyFrom(this.position);
  48708. break;
  48709. }
  48710. _super.prototype._updateRigCameras.call(this);
  48711. };
  48712. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48713. if (!this._rigCamTransformMatrix) {
  48714. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48715. }
  48716. var target = this.getTarget();
  48717. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48718. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48719. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48720. };
  48721. /**
  48722. * Gets the current object class name.
  48723. * @return the class name
  48724. */
  48725. TargetCamera.prototype.getClassName = function () {
  48726. return "TargetCamera";
  48727. };
  48728. __decorate([
  48729. BABYLON.serializeAsVector3()
  48730. ], TargetCamera.prototype, "rotation", void 0);
  48731. __decorate([
  48732. BABYLON.serialize()
  48733. ], TargetCamera.prototype, "speed", void 0);
  48734. __decorate([
  48735. BABYLON.serializeAsMeshReference("lockedTargetId")
  48736. ], TargetCamera.prototype, "lockedTarget", void 0);
  48737. return TargetCamera;
  48738. }(BABYLON.Camera));
  48739. BABYLON.TargetCamera = TargetCamera;
  48740. })(BABYLON || (BABYLON = {}));
  48741. //# sourceMappingURL=babylon.targetCamera.js.map
  48742. var BABYLON;
  48743. (function (BABYLON) {
  48744. /**
  48745. * Manage the mouse inputs to control the movement of a free camera.
  48746. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48747. */
  48748. var FreeCameraMouseInput = /** @class */ (function () {
  48749. /**
  48750. * Manage the mouse inputs to control the movement of a free camera.
  48751. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48752. * @param touchEnabled Defines if touch is enabled or not
  48753. */
  48754. function FreeCameraMouseInput(
  48755. /**
  48756. * Define if touch is enabled in the mouse input
  48757. */
  48758. touchEnabled) {
  48759. if (touchEnabled === void 0) { touchEnabled = true; }
  48760. this.touchEnabled = touchEnabled;
  48761. /**
  48762. * Defines the buttons associated with the input to handle camera move.
  48763. */
  48764. this.buttons = [0, 1, 2];
  48765. /**
  48766. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48767. */
  48768. this.angularSensibility = 2000.0;
  48769. this.previousPosition = null;
  48770. }
  48771. /**
  48772. * Attach the input controls to a specific dom element to get the input from.
  48773. * @param element Defines the element the controls should be listened from
  48774. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48775. */
  48776. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48777. var _this = this;
  48778. var engine = this.camera.getEngine();
  48779. if (!this._pointerInput) {
  48780. this._pointerInput = function (p, s) {
  48781. var evt = p.event;
  48782. if (engine.isInVRExclusivePointerMode) {
  48783. return;
  48784. }
  48785. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48786. return;
  48787. }
  48788. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48789. return;
  48790. }
  48791. var srcElement = (evt.srcElement || evt.target);
  48792. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48793. try {
  48794. srcElement.setPointerCapture(evt.pointerId);
  48795. }
  48796. catch (e) {
  48797. //Nothing to do with the error. Execution will continue.
  48798. }
  48799. _this.previousPosition = {
  48800. x: evt.clientX,
  48801. y: evt.clientY
  48802. };
  48803. if (!noPreventDefault) {
  48804. evt.preventDefault();
  48805. element.focus();
  48806. }
  48807. }
  48808. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48809. try {
  48810. srcElement.releasePointerCapture(evt.pointerId);
  48811. }
  48812. catch (e) {
  48813. //Nothing to do with the error.
  48814. }
  48815. _this.previousPosition = null;
  48816. if (!noPreventDefault) {
  48817. evt.preventDefault();
  48818. }
  48819. }
  48820. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48821. if (!_this.previousPosition || engine.isPointerLock) {
  48822. return;
  48823. }
  48824. var offsetX = evt.clientX - _this.previousPosition.x;
  48825. if (_this.camera.getScene().useRightHandedSystem) {
  48826. offsetX *= -1;
  48827. }
  48828. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48829. offsetX *= -1;
  48830. }
  48831. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48832. var offsetY = evt.clientY - _this.previousPosition.y;
  48833. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48834. _this.previousPosition = {
  48835. x: evt.clientX,
  48836. y: evt.clientY
  48837. };
  48838. if (!noPreventDefault) {
  48839. evt.preventDefault();
  48840. }
  48841. }
  48842. };
  48843. }
  48844. this._onMouseMove = function (evt) {
  48845. if (!engine.isPointerLock) {
  48846. return;
  48847. }
  48848. if (engine.isInVRExclusivePointerMode) {
  48849. return;
  48850. }
  48851. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48852. if (_this.camera.getScene().useRightHandedSystem) {
  48853. offsetX *= -1;
  48854. }
  48855. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48856. offsetX *= -1;
  48857. }
  48858. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48859. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48860. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48861. _this.previousPosition = null;
  48862. if (!noPreventDefault) {
  48863. evt.preventDefault();
  48864. }
  48865. };
  48866. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48867. element.addEventListener("mousemove", this._onMouseMove, false);
  48868. };
  48869. /**
  48870. * Detach the current controls from the specified dom element.
  48871. * @param element Defines the element to stop listening the inputs from
  48872. */
  48873. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48874. if (this._observer && element) {
  48875. this.camera.getScene().onPointerObservable.remove(this._observer);
  48876. if (this._onMouseMove) {
  48877. element.removeEventListener("mousemove", this._onMouseMove);
  48878. }
  48879. this._observer = null;
  48880. this._onMouseMove = null;
  48881. this.previousPosition = null;
  48882. }
  48883. };
  48884. /**
  48885. * Gets the class name of the current intput.
  48886. * @returns the class name
  48887. */
  48888. FreeCameraMouseInput.prototype.getClassName = function () {
  48889. return "FreeCameraMouseInput";
  48890. };
  48891. /**
  48892. * Get the friendly name associated with the input class.
  48893. * @returns the input friendly name
  48894. */
  48895. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48896. return "mouse";
  48897. };
  48898. __decorate([
  48899. BABYLON.serialize()
  48900. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48901. __decorate([
  48902. BABYLON.serialize()
  48903. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48904. return FreeCameraMouseInput;
  48905. }());
  48906. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48907. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48908. })(BABYLON || (BABYLON = {}));
  48909. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48910. var BABYLON;
  48911. (function (BABYLON) {
  48912. /**
  48913. * Manage the keyboard inputs to control the movement of a free camera.
  48914. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48915. */
  48916. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48917. function FreeCameraKeyboardMoveInput() {
  48918. /**
  48919. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48920. */
  48921. this.keysUp = [38];
  48922. /**
  48923. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48924. */
  48925. this.keysDown = [40];
  48926. /**
  48927. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48928. */
  48929. this.keysLeft = [37];
  48930. /**
  48931. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48932. */
  48933. this.keysRight = [39];
  48934. this._keys = new Array();
  48935. }
  48936. /**
  48937. * Attach the input controls to a specific dom element to get the input from.
  48938. * @param element Defines the element the controls should be listened from
  48939. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48940. */
  48941. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48942. var _this = this;
  48943. if (this._onCanvasBlurObserver) {
  48944. return;
  48945. }
  48946. this._scene = this.camera.getScene();
  48947. this._engine = this._scene.getEngine();
  48948. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48949. _this._keys = [];
  48950. });
  48951. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48952. var evt = info.event;
  48953. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48954. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48955. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48956. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48957. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48958. var index = _this._keys.indexOf(evt.keyCode);
  48959. if (index === -1) {
  48960. _this._keys.push(evt.keyCode);
  48961. }
  48962. if (!noPreventDefault) {
  48963. evt.preventDefault();
  48964. }
  48965. }
  48966. }
  48967. else {
  48968. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48969. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48970. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48971. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48972. var index = _this._keys.indexOf(evt.keyCode);
  48973. if (index >= 0) {
  48974. _this._keys.splice(index, 1);
  48975. }
  48976. if (!noPreventDefault) {
  48977. evt.preventDefault();
  48978. }
  48979. }
  48980. }
  48981. });
  48982. };
  48983. /**
  48984. * Detach the current controls from the specified dom element.
  48985. * @param element Defines the element to stop listening the inputs from
  48986. */
  48987. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48988. if (this._scene) {
  48989. if (this._onKeyboardObserver) {
  48990. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48991. }
  48992. if (this._onCanvasBlurObserver) {
  48993. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48994. }
  48995. this._onKeyboardObserver = null;
  48996. this._onCanvasBlurObserver = null;
  48997. }
  48998. this._keys = [];
  48999. };
  49000. /**
  49001. * Update the current camera state depending on the inputs that have been used this frame.
  49002. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49003. */
  49004. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49005. if (this._onKeyboardObserver) {
  49006. var camera = this.camera;
  49007. // Keyboard
  49008. for (var index = 0; index < this._keys.length; index++) {
  49009. var keyCode = this._keys[index];
  49010. var speed = camera._computeLocalCameraSpeed();
  49011. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49012. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49013. }
  49014. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49015. camera._localDirection.copyFromFloats(0, 0, speed);
  49016. }
  49017. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49018. camera._localDirection.copyFromFloats(speed, 0, 0);
  49019. }
  49020. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49021. camera._localDirection.copyFromFloats(0, 0, -speed);
  49022. }
  49023. if (camera.getScene().useRightHandedSystem) {
  49024. camera._localDirection.z *= -1;
  49025. }
  49026. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49027. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49028. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49029. }
  49030. }
  49031. };
  49032. /**
  49033. * Gets the class name of the current intput.
  49034. * @returns the class name
  49035. */
  49036. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  49037. return "FreeCameraKeyboardMoveInput";
  49038. };
  49039. /** @hidden */
  49040. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  49041. this._keys = [];
  49042. };
  49043. /**
  49044. * Get the friendly name associated with the input class.
  49045. * @returns the input friendly name
  49046. */
  49047. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49048. return "keyboard";
  49049. };
  49050. __decorate([
  49051. BABYLON.serialize()
  49052. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49053. __decorate([
  49054. BABYLON.serialize()
  49055. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49056. __decorate([
  49057. BABYLON.serialize()
  49058. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49059. __decorate([
  49060. BABYLON.serialize()
  49061. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49062. return FreeCameraKeyboardMoveInput;
  49063. }());
  49064. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  49065. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  49066. })(BABYLON || (BABYLON = {}));
  49067. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  49068. var BABYLON;
  49069. (function (BABYLON) {
  49070. /**
  49071. * Default Inputs manager for the FreeCamera.
  49072. * It groups all the default supported inputs for ease of use.
  49073. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49074. */
  49075. var FreeCameraInputsManager = /** @class */ (function (_super) {
  49076. __extends(FreeCameraInputsManager, _super);
  49077. /**
  49078. * Instantiates a new FreeCameraInputsManager.
  49079. * @param camera Defines the camera the inputs belong to
  49080. */
  49081. function FreeCameraInputsManager(camera) {
  49082. return _super.call(this, camera) || this;
  49083. }
  49084. /**
  49085. * Add keyboard input support to the input manager.
  49086. * @returns the current input manager
  49087. */
  49088. FreeCameraInputsManager.prototype.addKeyboard = function () {
  49089. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  49090. return this;
  49091. };
  49092. /**
  49093. * Add mouse input support to the input manager.
  49094. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  49095. * @returns the current input manager
  49096. */
  49097. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49098. if (touchEnabled === void 0) { touchEnabled = true; }
  49099. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  49100. return this;
  49101. };
  49102. /**
  49103. * Add orientation input support to the input manager.
  49104. * @returns the current input manager
  49105. */
  49106. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  49107. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  49108. return this;
  49109. };
  49110. /**
  49111. * Add touch input support to the input manager.
  49112. * @returns the current input manager
  49113. */
  49114. FreeCameraInputsManager.prototype.addTouch = function () {
  49115. this.add(new BABYLON.FreeCameraTouchInput());
  49116. return this;
  49117. };
  49118. /**
  49119. * Add virtual joystick input support to the input manager.
  49120. * @returns the current input manager
  49121. */
  49122. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  49123. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  49124. return this;
  49125. };
  49126. return FreeCameraInputsManager;
  49127. }(BABYLON.CameraInputsManager));
  49128. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  49129. })(BABYLON || (BABYLON = {}));
  49130. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  49131. var BABYLON;
  49132. (function (BABYLON) {
  49133. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  49134. // Forcing to use the Universal camera
  49135. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  49136. });
  49137. /**
  49138. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49139. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  49140. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49141. */
  49142. var FreeCamera = /** @class */ (function (_super) {
  49143. __extends(FreeCamera, _super);
  49144. /**
  49145. * Instantiates a Free Camera.
  49146. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49147. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  49148. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49149. * @param name Define the name of the camera in the scene
  49150. * @param position Define the start position of the camera in the scene
  49151. * @param scene Define the scene the camera belongs to
  49152. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49153. */
  49154. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49155. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49156. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49157. /**
  49158. * Define the collision ellipsoid of the camera.
  49159. * This is helpful to simulate a camera body like the player body around the camera
  49160. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49161. */
  49162. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  49163. /**
  49164. * Define an offset for the position of the ellipsoid around the camera.
  49165. * This can be helpful to determine the center of the body near the gravity center of the body
  49166. * instead of its head.
  49167. */
  49168. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49169. /**
  49170. * Enable or disable collisions of the camera with the rest of the scene objects.
  49171. */
  49172. _this.checkCollisions = false;
  49173. /**
  49174. * Enable or disable gravity on the camera.
  49175. */
  49176. _this.applyGravity = false;
  49177. _this._needMoveForGravity = false;
  49178. _this._oldPosition = BABYLON.Vector3.Zero();
  49179. _this._diffPosition = BABYLON.Vector3.Zero();
  49180. _this._newPosition = BABYLON.Vector3.Zero();
  49181. // Collisions
  49182. _this._collisionMask = -1;
  49183. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49184. if (collidedMesh === void 0) { collidedMesh = null; }
  49185. //TODO move this to the collision coordinator!
  49186. if (_this.getScene().workerCollisions) {
  49187. newPosition.multiplyInPlace(_this._collider._radius);
  49188. }
  49189. var updatePosition = function (newPos) {
  49190. _this._newPosition.copyFrom(newPos);
  49191. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49192. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49193. _this.position.addInPlace(_this._diffPosition);
  49194. if (_this.onCollide && collidedMesh) {
  49195. _this.onCollide(collidedMesh);
  49196. }
  49197. }
  49198. };
  49199. updatePosition(newPosition);
  49200. };
  49201. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  49202. _this.inputs.addKeyboard().addMouse();
  49203. return _this;
  49204. }
  49205. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  49206. /**
  49207. * Gets the input sensibility for a mouse input. (default is 2000.0)
  49208. * Higher values reduce sensitivity.
  49209. */
  49210. get: function () {
  49211. var mouse = this.inputs.attached["mouse"];
  49212. if (mouse) {
  49213. return mouse.angularSensibility;
  49214. }
  49215. return 0;
  49216. },
  49217. /**
  49218. * Sets the input sensibility for a mouse input. (default is 2000.0)
  49219. * Higher values reduce sensitivity.
  49220. */
  49221. set: function (value) {
  49222. var mouse = this.inputs.attached["mouse"];
  49223. if (mouse) {
  49224. mouse.angularSensibility = value;
  49225. }
  49226. },
  49227. enumerable: true,
  49228. configurable: true
  49229. });
  49230. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  49231. /**
  49232. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49233. */
  49234. get: function () {
  49235. var keyboard = this.inputs.attached["keyboard"];
  49236. if (keyboard) {
  49237. return keyboard.keysUp;
  49238. }
  49239. return [];
  49240. },
  49241. set: function (value) {
  49242. var keyboard = this.inputs.attached["keyboard"];
  49243. if (keyboard) {
  49244. keyboard.keysUp = value;
  49245. }
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  49251. /**
  49252. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49253. */
  49254. get: function () {
  49255. var keyboard = this.inputs.attached["keyboard"];
  49256. if (keyboard) {
  49257. return keyboard.keysDown;
  49258. }
  49259. return [];
  49260. },
  49261. set: function (value) {
  49262. var keyboard = this.inputs.attached["keyboard"];
  49263. if (keyboard) {
  49264. keyboard.keysDown = value;
  49265. }
  49266. },
  49267. enumerable: true,
  49268. configurable: true
  49269. });
  49270. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  49271. /**
  49272. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49273. */
  49274. get: function () {
  49275. var keyboard = this.inputs.attached["keyboard"];
  49276. if (keyboard) {
  49277. return keyboard.keysLeft;
  49278. }
  49279. return [];
  49280. },
  49281. set: function (value) {
  49282. var keyboard = this.inputs.attached["keyboard"];
  49283. if (keyboard) {
  49284. keyboard.keysLeft = value;
  49285. }
  49286. },
  49287. enumerable: true,
  49288. configurable: true
  49289. });
  49290. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  49291. /**
  49292. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49293. */
  49294. get: function () {
  49295. var keyboard = this.inputs.attached["keyboard"];
  49296. if (keyboard) {
  49297. return keyboard.keysRight;
  49298. }
  49299. return [];
  49300. },
  49301. set: function (value) {
  49302. var keyboard = this.inputs.attached["keyboard"];
  49303. if (keyboard) {
  49304. keyboard.keysRight = value;
  49305. }
  49306. },
  49307. enumerable: true,
  49308. configurable: true
  49309. });
  49310. /**
  49311. * Attached controls to the current camera.
  49312. * @param element Defines the element the controls should be listened from
  49313. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49314. */
  49315. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49316. this.inputs.attachElement(element, noPreventDefault);
  49317. };
  49318. /**
  49319. * Detach the current controls from the camera.
  49320. * The camera will stop reacting to inputs.
  49321. * @param element Defines the element to stop listening the inputs from
  49322. */
  49323. FreeCamera.prototype.detachControl = function (element) {
  49324. this.inputs.detachElement(element);
  49325. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49326. this.cameraRotation = new BABYLON.Vector2(0, 0);
  49327. };
  49328. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  49329. /**
  49330. * Define a collision mask to limit the list of object the camera can collide with
  49331. */
  49332. get: function () {
  49333. return this._collisionMask;
  49334. },
  49335. set: function (mask) {
  49336. this._collisionMask = !isNaN(mask) ? mask : -1;
  49337. },
  49338. enumerable: true,
  49339. configurable: true
  49340. });
  49341. /** @hidden */
  49342. FreeCamera.prototype._collideWithWorld = function (displacement) {
  49343. var globalPosition;
  49344. if (this.parent) {
  49345. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  49346. }
  49347. else {
  49348. globalPosition = this.position;
  49349. }
  49350. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  49351. this._oldPosition.addInPlace(this.ellipsoidOffset);
  49352. if (!this._collider) {
  49353. this._collider = new BABYLON.Collider();
  49354. }
  49355. this._collider._radius = this.ellipsoid;
  49356. this._collider.collisionMask = this._collisionMask;
  49357. //no need for clone, as long as gravity is not on.
  49358. var actualDisplacement = displacement;
  49359. //add gravity to the direction to prevent the dual-collision checking
  49360. if (this.applyGravity) {
  49361. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49362. actualDisplacement = displacement.add(this.getScene().gravity);
  49363. }
  49364. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49365. };
  49366. /** @hidden */
  49367. FreeCamera.prototype._checkInputs = function () {
  49368. if (!this._localDirection) {
  49369. this._localDirection = BABYLON.Vector3.Zero();
  49370. this._transformedDirection = BABYLON.Vector3.Zero();
  49371. }
  49372. this.inputs.checkInputs();
  49373. _super.prototype._checkInputs.call(this);
  49374. };
  49375. /** @hidden */
  49376. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49377. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49378. };
  49379. /** @hidden */
  49380. FreeCamera.prototype._updatePosition = function () {
  49381. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49382. this._collideWithWorld(this.cameraDirection);
  49383. }
  49384. else {
  49385. _super.prototype._updatePosition.call(this);
  49386. }
  49387. };
  49388. /**
  49389. * Destroy the camera and release the current resources hold by it.
  49390. */
  49391. FreeCamera.prototype.dispose = function () {
  49392. this.inputs.clear();
  49393. _super.prototype.dispose.call(this);
  49394. };
  49395. /**
  49396. * Gets the current object class name.
  49397. * @return the class name
  49398. */
  49399. FreeCamera.prototype.getClassName = function () {
  49400. return "FreeCamera";
  49401. };
  49402. __decorate([
  49403. BABYLON.serializeAsVector3()
  49404. ], FreeCamera.prototype, "ellipsoid", void 0);
  49405. __decorate([
  49406. BABYLON.serializeAsVector3()
  49407. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49408. __decorate([
  49409. BABYLON.serialize()
  49410. ], FreeCamera.prototype, "checkCollisions", void 0);
  49411. __decorate([
  49412. BABYLON.serialize()
  49413. ], FreeCamera.prototype, "applyGravity", void 0);
  49414. return FreeCamera;
  49415. }(BABYLON.TargetCamera));
  49416. BABYLON.FreeCamera = FreeCamera;
  49417. })(BABYLON || (BABYLON = {}));
  49418. //# sourceMappingURL=babylon.freeCamera.js.map
  49419. var BABYLON;
  49420. (function (BABYLON) {
  49421. /**
  49422. * Listen to mouse events to control the camera.
  49423. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49424. */
  49425. var FlyCameraMouseInput = /** @class */ (function () {
  49426. /**
  49427. * Listen to mouse events to control the camera.
  49428. * @param touchEnabled Define if touch is enabled. (Default is true.)
  49429. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49430. */
  49431. function FlyCameraMouseInput(touchEnabled) {
  49432. if (touchEnabled === void 0) { touchEnabled = true; }
  49433. /**
  49434. * Defines the buttons associated with the input to handle camera rotation.
  49435. */
  49436. this.buttons = [0, 1, 2];
  49437. /**
  49438. * Assign buttons for Yaw control.
  49439. */
  49440. this.buttonsYaw = [-1, 0, 1];
  49441. /**
  49442. * Assign buttons for Pitch control.
  49443. */
  49444. this.buttonsPitch = [-1, 0, 1];
  49445. /**
  49446. * Assign buttons for Roll control.
  49447. */
  49448. this.buttonsRoll = [2];
  49449. /**
  49450. * Detect if any button is being pressed while mouse is moved.
  49451. * -1 = Mouse locked.
  49452. * 0 = Left button.
  49453. * 1 = Middle Button.
  49454. * 2 = Right Button.
  49455. */
  49456. this.activeButton = -1;
  49457. /**
  49458. * Defines the pointer's angular sensibility, to control the camera rotation speed.
  49459. * Higher values reduce its sensitivity.
  49460. */
  49461. this.angularSensibility = 1000.0;
  49462. this.previousPosition = null;
  49463. }
  49464. /**
  49465. * Attach the mouse control to the HTML DOM element.
  49466. * @param element Defines the element that listens to the input events.
  49467. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().
  49468. */
  49469. FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49470. var _this = this;
  49471. this.element = element;
  49472. this.noPreventDefault = noPreventDefault;
  49473. this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) {
  49474. _this._pointerInput(p, s);
  49475. }, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49476. // Correct Roll by rate, if enabled.
  49477. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () {
  49478. if (_this.camera.rollCorrect) {
  49479. _this.camera.restoreRoll(_this.camera.rollCorrect);
  49480. }
  49481. });
  49482. // Helper function to keep 'this'.
  49483. this._mousemoveCallback = function (e) {
  49484. _this._onMouseMove(e);
  49485. };
  49486. element.addEventListener("mousemove", this._mousemoveCallback, false);
  49487. };
  49488. /**
  49489. * Detach the current controls from the specified dom element.
  49490. * @param element Defines the element to stop listening the inputs from
  49491. */
  49492. FlyCameraMouseInput.prototype.detachControl = function (element) {
  49493. if (this._observer && element) {
  49494. this.camera.getScene().onPointerObservable.remove(this._observer);
  49495. this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
  49496. if (this._mousemoveCallback) {
  49497. element.removeEventListener("mousemove", this._mousemoveCallback);
  49498. }
  49499. this._observer = null;
  49500. this._rollObserver = null;
  49501. this.previousPosition = null;
  49502. this.noPreventDefault = undefined;
  49503. }
  49504. };
  49505. /**
  49506. * Gets the class name of the current input.
  49507. * @returns the class name.
  49508. */
  49509. FlyCameraMouseInput.prototype.getClassName = function () {
  49510. return "FlyCameraMouseInput";
  49511. };
  49512. /**
  49513. * Get the friendly name associated with the input class.
  49514. * @returns the input's friendly name.
  49515. */
  49516. FlyCameraMouseInput.prototype.getSimpleName = function () {
  49517. return "mouse";
  49518. };
  49519. // Track mouse movement, when the pointer is not locked.
  49520. FlyCameraMouseInput.prototype._pointerInput = function (p, s) {
  49521. var e = p.event;
  49522. var camera = this.camera;
  49523. var engine = camera.getEngine();
  49524. if (engine.isInVRExclusivePointerMode) {
  49525. return;
  49526. }
  49527. if (!this.touchEnabled && e.pointerType === "touch") {
  49528. return;
  49529. }
  49530. // Mouse is moved but an unknown mouse button is pressed.
  49531. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
  49532. return;
  49533. }
  49534. var srcElement = (e.srcElement || e.target);
  49535. // Mouse down.
  49536. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49537. try {
  49538. srcElement.setPointerCapture(e.pointerId);
  49539. }
  49540. catch (e) {
  49541. // Nothing to do with the error. Execution continues.
  49542. }
  49543. this.previousPosition = {
  49544. x: e.clientX,
  49545. y: e.clientY
  49546. };
  49547. this.activeButton = e.button;
  49548. if (!this.noPreventDefault) {
  49549. e.preventDefault();
  49550. this.element.focus();
  49551. }
  49552. }
  49553. else
  49554. // Mouse up.
  49555. if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49556. try {
  49557. srcElement.releasePointerCapture(e.pointerId);
  49558. }
  49559. catch (e) {
  49560. // Nothing to do with the error. Execution continues.
  49561. }
  49562. this.activeButton = -1;
  49563. this.previousPosition = null;
  49564. if (!this.noPreventDefault) {
  49565. e.preventDefault();
  49566. }
  49567. }
  49568. else
  49569. // Mouse move.
  49570. if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49571. if (!this.previousPosition || engine.isPointerLock) {
  49572. return;
  49573. }
  49574. var offsetX = e.clientX - this.previousPosition.x;
  49575. var offsetY = e.clientY - this.previousPosition.y;
  49576. this.rotateCamera(offsetX, offsetY);
  49577. this.previousPosition = {
  49578. x: e.clientX,
  49579. y: e.clientY
  49580. };
  49581. if (!this.noPreventDefault) {
  49582. e.preventDefault();
  49583. }
  49584. }
  49585. };
  49586. // Track mouse movement, when pointer is locked.
  49587. FlyCameraMouseInput.prototype._onMouseMove = function (e) {
  49588. var camera = this.camera;
  49589. var engine = camera.getEngine();
  49590. if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {
  49591. return;
  49592. }
  49593. var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0;
  49594. var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0;
  49595. this.rotateCamera(offsetX, offsetY);
  49596. this.previousPosition = null;
  49597. if (!this.noPreventDefault) {
  49598. e.preventDefault();
  49599. }
  49600. };
  49601. /**
  49602. * Rotate camera by mouse offset.
  49603. */
  49604. FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) {
  49605. var _this = this;
  49606. var camera = this.camera;
  49607. var scene = this.camera.getScene();
  49608. if (scene.useRightHandedSystem) {
  49609. offsetX *= -1;
  49610. }
  49611. if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {
  49612. offsetX *= -1;
  49613. }
  49614. var x = offsetX / this.angularSensibility;
  49615. var y = offsetY / this.angularSensibility;
  49616. // Initialize to current rotation.
  49617. var currentRotation = BABYLON.Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
  49618. var rotationChange;
  49619. // Pitch.
  49620. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) {
  49621. // Apply change in Radians to vector Angle.
  49622. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.X, y);
  49623. // Apply Pitch to quaternion.
  49624. currentRotation.multiplyInPlace(rotationChange);
  49625. }
  49626. // Yaw.
  49627. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) {
  49628. // Apply change in Radians to vector Angle.
  49629. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Y, x);
  49630. // Apply Yaw to quaternion.
  49631. currentRotation.multiplyInPlace(rotationChange);
  49632. // Add Roll, if banked turning is enabled, within Roll limit.
  49633. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll.
  49634. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
  49635. var bankingDelta = camera.bankedTurnMultiplier * -x;
  49636. // Apply change in Radians to vector Angle.
  49637. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, bankingDelta);
  49638. // Apply Yaw to quaternion.
  49639. currentRotation.multiplyInPlace(rotationChange);
  49640. }
  49641. }
  49642. // Roll.
  49643. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) {
  49644. // Apply change in Radians to vector Angle.
  49645. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, -x);
  49646. // Track Rolling.
  49647. camera._trackRoll -= x;
  49648. // Apply Pitch to quaternion.
  49649. currentRotation.multiplyInPlace(rotationChange);
  49650. }
  49651. // Apply rotationQuaternion to Euler camera.rotation.
  49652. currentRotation.toEulerAnglesToRef(camera.rotation);
  49653. };
  49654. __decorate([
  49655. BABYLON.serialize()
  49656. ], FlyCameraMouseInput.prototype, "buttons", void 0);
  49657. __decorate([
  49658. BABYLON.serialize()
  49659. ], FlyCameraMouseInput.prototype, "angularSensibility", void 0);
  49660. return FlyCameraMouseInput;
  49661. }());
  49662. BABYLON.FlyCameraMouseInput = FlyCameraMouseInput;
  49663. BABYLON.CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
  49664. })(BABYLON || (BABYLON = {}));
  49665. //# sourceMappingURL=babylon.flyCameraMouseInput.js.map
  49666. var BABYLON;
  49667. (function (BABYLON) {
  49668. /**
  49669. * Listen to keyboard events to control the camera.
  49670. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49671. */
  49672. var FlyCameraKeyboardInput = /** @class */ (function () {
  49673. function FlyCameraKeyboardInput() {
  49674. /**
  49675. * The list of keyboard keys used to control the forward move of the camera.
  49676. */
  49677. this.keysForward = [87];
  49678. /**
  49679. * The list of keyboard keys used to control the backward move of the camera.
  49680. */
  49681. this.keysBackward = [83];
  49682. /**
  49683. * The list of keyboard keys used to control the forward move of the camera.
  49684. */
  49685. this.keysUp = [69];
  49686. /**
  49687. * The list of keyboard keys used to control the backward move of the camera.
  49688. */
  49689. this.keysDown = [81];
  49690. /**
  49691. * The list of keyboard keys used to control the right strafe move of the camera.
  49692. */
  49693. this.keysRight = [68];
  49694. /**
  49695. * The list of keyboard keys used to control the left strafe move of the camera.
  49696. */
  49697. this.keysLeft = [65];
  49698. this._keys = new Array();
  49699. }
  49700. /**
  49701. * Attach the input controls to a specific dom element to get the input from.
  49702. * @param element Defines the element the controls should be listened from
  49703. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49704. */
  49705. FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) {
  49706. var _this = this;
  49707. if (this._onCanvasBlurObserver) {
  49708. return;
  49709. }
  49710. this._scene = this.camera.getScene();
  49711. this._engine = this._scene.getEngine();
  49712. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49713. _this._keys = [];
  49714. });
  49715. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49716. var evt = info.event;
  49717. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49718. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49719. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49720. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49721. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49722. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49723. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49724. var index = _this._keys.indexOf(evt.keyCode);
  49725. if (index === -1) {
  49726. _this._keys.push(evt.keyCode);
  49727. }
  49728. if (!noPreventDefault) {
  49729. evt.preventDefault();
  49730. }
  49731. }
  49732. }
  49733. else {
  49734. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49735. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49736. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49737. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49738. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49739. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49740. var index = _this._keys.indexOf(evt.keyCode);
  49741. if (index >= 0) {
  49742. _this._keys.splice(index, 1);
  49743. }
  49744. if (!noPreventDefault) {
  49745. evt.preventDefault();
  49746. }
  49747. }
  49748. }
  49749. });
  49750. };
  49751. /**
  49752. * Detach the current controls from the specified dom element.
  49753. * @param element Defines the element to stop listening the inputs from
  49754. */
  49755. FlyCameraKeyboardInput.prototype.detachControl = function (element) {
  49756. if (this._scene) {
  49757. if (this._onKeyboardObserver) {
  49758. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49759. }
  49760. if (this._onCanvasBlurObserver) {
  49761. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49762. }
  49763. this._onKeyboardObserver = null;
  49764. this._onCanvasBlurObserver = null;
  49765. }
  49766. this._keys = [];
  49767. };
  49768. /**
  49769. * Gets the class name of the current intput.
  49770. * @returns the class name
  49771. */
  49772. FlyCameraKeyboardInput.prototype.getClassName = function () {
  49773. return "FlyCameraKeyboardInput";
  49774. };
  49775. /** @hidden */
  49776. FlyCameraKeyboardInput.prototype._onLostFocus = function (e) {
  49777. this._keys = [];
  49778. };
  49779. /**
  49780. * Get the friendly name associated with the input class.
  49781. * @returns the input friendly name
  49782. */
  49783. FlyCameraKeyboardInput.prototype.getSimpleName = function () {
  49784. return "keyboard";
  49785. };
  49786. /**
  49787. * Update the current camera state depending on the inputs that have been used this frame.
  49788. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49789. */
  49790. FlyCameraKeyboardInput.prototype.checkInputs = function () {
  49791. if (this._onKeyboardObserver) {
  49792. var camera = this.camera;
  49793. // Keyboard
  49794. for (var index = 0; index < this._keys.length; index++) {
  49795. var keyCode = this._keys[index];
  49796. var speed = camera._computeLocalCameraSpeed();
  49797. if (this.keysForward.indexOf(keyCode) !== -1) {
  49798. camera._localDirection.copyFromFloats(0, 0, speed);
  49799. }
  49800. else if (this.keysBackward.indexOf(keyCode) !== -1) {
  49801. camera._localDirection.copyFromFloats(0, 0, -speed);
  49802. }
  49803. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49804. camera._localDirection.copyFromFloats(0, speed, 0);
  49805. }
  49806. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49807. camera._localDirection.copyFromFloats(0, -speed, 0);
  49808. }
  49809. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49810. camera._localDirection.copyFromFloats(speed, 0, 0);
  49811. }
  49812. else if (this.keysLeft.indexOf(keyCode) !== -1) {
  49813. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49814. }
  49815. if (camera.getScene().useRightHandedSystem) {
  49816. camera._localDirection.z *= -1;
  49817. }
  49818. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49819. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49820. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49821. }
  49822. }
  49823. };
  49824. __decorate([
  49825. BABYLON.serialize()
  49826. ], FlyCameraKeyboardInput.prototype, "keysForward", void 0);
  49827. __decorate([
  49828. BABYLON.serialize()
  49829. ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0);
  49830. __decorate([
  49831. BABYLON.serialize()
  49832. ], FlyCameraKeyboardInput.prototype, "keysUp", void 0);
  49833. __decorate([
  49834. BABYLON.serialize()
  49835. ], FlyCameraKeyboardInput.prototype, "keysDown", void 0);
  49836. __decorate([
  49837. BABYLON.serialize()
  49838. ], FlyCameraKeyboardInput.prototype, "keysRight", void 0);
  49839. __decorate([
  49840. BABYLON.serialize()
  49841. ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0);
  49842. return FlyCameraKeyboardInput;
  49843. }());
  49844. BABYLON.FlyCameraKeyboardInput = FlyCameraKeyboardInput;
  49845. BABYLON.CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
  49846. })(BABYLON || (BABYLON = {}));
  49847. //# sourceMappingURL=babylon.flyCameraKeyboardInput.js.map
  49848. var BABYLON;
  49849. (function (BABYLON) {
  49850. /**
  49851. * Default Inputs manager for the FlyCamera.
  49852. * It groups all the default supported inputs for ease of use.
  49853. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49854. */
  49855. var FlyCameraInputsManager = /** @class */ (function (_super) {
  49856. __extends(FlyCameraInputsManager, _super);
  49857. /**
  49858. * Instantiates a new FlyCameraInputsManager.
  49859. * @param camera Defines the camera the inputs belong to.
  49860. */
  49861. function FlyCameraInputsManager(camera) {
  49862. return _super.call(this, camera) || this;
  49863. }
  49864. /**
  49865. * Add keyboard input support to the input manager.
  49866. * @returns the new FlyCameraKeyboardMoveInput().
  49867. */
  49868. FlyCameraInputsManager.prototype.addKeyboard = function () {
  49869. this.add(new BABYLON.FlyCameraKeyboardInput());
  49870. return this;
  49871. };
  49872. /**
  49873. * Add mouse input support to the input manager.
  49874. * @param touchEnabled Enable touch screen support.
  49875. * @returns the new FlyCameraMouseInput().
  49876. */
  49877. FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49878. if (touchEnabled === void 0) { touchEnabled = true; }
  49879. this.add(new BABYLON.FlyCameraMouseInput(touchEnabled));
  49880. return this;
  49881. };
  49882. return FlyCameraInputsManager;
  49883. }(BABYLON.CameraInputsManager));
  49884. BABYLON.FlyCameraInputsManager = FlyCameraInputsManager;
  49885. })(BABYLON || (BABYLON = {}));
  49886. //# sourceMappingURL=babylon.flyCameraInputsManager.js.map
  49887. var BABYLON;
  49888. (function (BABYLON) {
  49889. /**
  49890. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49891. * such as in a 3D Space Shooter or a Flight Simulator.
  49892. */
  49893. var FlyCamera = /** @class */ (function (_super) {
  49894. __extends(FlyCamera, _super);
  49895. /**
  49896. * Instantiates a FlyCamera.
  49897. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49898. * such as in a 3D Space Shooter or a Flight Simulator.
  49899. * @param name Define the name of the camera in the scene.
  49900. * @param position Define the starting position of the camera in the scene.
  49901. * @param scene Define the scene the camera belongs to.
  49902. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  49903. */
  49904. function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49905. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49906. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49907. /**
  49908. * Define the collision ellipsoid of the camera.
  49909. * This is helpful for simulating a camera body, like a player's body.
  49910. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49911. */
  49912. _this.ellipsoid = new BABYLON.Vector3(1, 1, 1);
  49913. /**
  49914. * Define an offset for the position of the ellipsoid around the camera.
  49915. * This can be helpful if the camera is attached away from the player's body center,
  49916. * such as at its head.
  49917. */
  49918. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49919. /**
  49920. * Enable or disable collisions of the camera with the rest of the scene objects.
  49921. */
  49922. _this.checkCollisions = false;
  49923. /**
  49924. * Enable or disable gravity on the camera.
  49925. */
  49926. _this.applyGravity = false;
  49927. /**
  49928. * Define the current direction the camera is moving to.
  49929. */
  49930. _this.cameraDirection = BABYLON.Vector3.Zero();
  49931. /**
  49932. * Track Roll to maintain the wanted Rolling when looking around.
  49933. */
  49934. _this._trackRoll = 0;
  49935. /**
  49936. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  49937. */
  49938. _this.rollCorrect = 100;
  49939. /**
  49940. * Mimic a banked turn, Rolling the camera when Yawing.
  49941. * It's recommended to use rollCorrect = 10 for faster banking correction.
  49942. */
  49943. _this.bankedTurn = false;
  49944. /**
  49945. * Limit in radians for how much Roll banking will add. (Default: 90°)
  49946. */
  49947. _this.bankedTurnLimit = Math.PI / 2;
  49948. /**
  49949. * Value of 0 disables the banked Roll.
  49950. * Value of 1 is equal to the Yaw angle in radians.
  49951. */
  49952. _this.bankedTurnMultiplier = 1;
  49953. _this._needMoveForGravity = false;
  49954. _this._oldPosition = BABYLON.Vector3.Zero();
  49955. _this._diffPosition = BABYLON.Vector3.Zero();
  49956. _this._newPosition = BABYLON.Vector3.Zero();
  49957. // Collisions.
  49958. _this._collisionMask = -1;
  49959. /** @hidden */
  49960. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49961. if (collidedMesh === void 0) { collidedMesh = null; }
  49962. // TODO Move this to the collision coordinator!
  49963. if (_this.getScene().workerCollisions) {
  49964. newPosition.multiplyInPlace(_this._collider._radius);
  49965. }
  49966. var updatePosition = function (newPos) {
  49967. _this._newPosition.copyFrom(newPos);
  49968. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49969. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49970. _this.position.addInPlace(_this._diffPosition);
  49971. if (_this.onCollide && collidedMesh) {
  49972. _this.onCollide(collidedMesh);
  49973. }
  49974. }
  49975. };
  49976. updatePosition(newPosition);
  49977. };
  49978. _this.inputs = new BABYLON.FlyCameraInputsManager(_this);
  49979. _this.inputs.addKeyboard().addMouse();
  49980. return _this;
  49981. }
  49982. Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
  49983. /**
  49984. * Gets the input sensibility for mouse input.
  49985. * Higher values reduce sensitivity.
  49986. */
  49987. get: function () {
  49988. var mouse = this.inputs.attached["mouse"];
  49989. if (mouse) {
  49990. return mouse.angularSensibility;
  49991. }
  49992. return 0;
  49993. },
  49994. /**
  49995. * Sets the input sensibility for a mouse input.
  49996. * Higher values reduce sensitivity.
  49997. */
  49998. set: function (value) {
  49999. var mouse = this.inputs.attached["mouse"];
  50000. if (mouse) {
  50001. mouse.angularSensibility = value;
  50002. }
  50003. },
  50004. enumerable: true,
  50005. configurable: true
  50006. });
  50007. Object.defineProperty(FlyCamera.prototype, "keysForward", {
  50008. /**
  50009. * Get the keys for camera movement forward.
  50010. */
  50011. get: function () {
  50012. var keyboard = this.inputs.attached["keyboard"];
  50013. if (keyboard) {
  50014. return keyboard.keysForward;
  50015. }
  50016. return [];
  50017. },
  50018. /**
  50019. * Set the keys for camera movement forward.
  50020. */
  50021. set: function (value) {
  50022. var keyboard = this.inputs.attached["keyboard"];
  50023. if (keyboard) {
  50024. keyboard.keysForward = value;
  50025. }
  50026. },
  50027. enumerable: true,
  50028. configurable: true
  50029. });
  50030. Object.defineProperty(FlyCamera.prototype, "keysBackward", {
  50031. /**
  50032. * Get the keys for camera movement backward.
  50033. */
  50034. get: function () {
  50035. var keyboard = this.inputs.attached["keyboard"];
  50036. if (keyboard) {
  50037. return keyboard.keysBackward;
  50038. }
  50039. return [];
  50040. },
  50041. set: function (value) {
  50042. var keyboard = this.inputs.attached["keyboard"];
  50043. if (keyboard) {
  50044. keyboard.keysBackward = value;
  50045. }
  50046. },
  50047. enumerable: true,
  50048. configurable: true
  50049. });
  50050. Object.defineProperty(FlyCamera.prototype, "keysUp", {
  50051. /**
  50052. * Get the keys for camera movement up.
  50053. */
  50054. get: function () {
  50055. var keyboard = this.inputs.attached["keyboard"];
  50056. if (keyboard) {
  50057. return keyboard.keysUp;
  50058. }
  50059. return [];
  50060. },
  50061. /**
  50062. * Set the keys for camera movement up.
  50063. */
  50064. set: function (value) {
  50065. var keyboard = this.inputs.attached["keyboard"];
  50066. if (keyboard) {
  50067. keyboard.keysUp = value;
  50068. }
  50069. },
  50070. enumerable: true,
  50071. configurable: true
  50072. });
  50073. Object.defineProperty(FlyCamera.prototype, "keysDown", {
  50074. /**
  50075. * Get the keys for camera movement down.
  50076. */
  50077. get: function () {
  50078. var keyboard = this.inputs.attached["keyboard"];
  50079. if (keyboard) {
  50080. return keyboard.keysDown;
  50081. }
  50082. return [];
  50083. },
  50084. /**
  50085. * Set the keys for camera movement down.
  50086. */
  50087. set: function (value) {
  50088. var keyboard = this.inputs.attached["keyboard"];
  50089. if (keyboard) {
  50090. keyboard.keysDown = value;
  50091. }
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(FlyCamera.prototype, "keysLeft", {
  50097. /**
  50098. * Get the keys for camera movement left.
  50099. */
  50100. get: function () {
  50101. var keyboard = this.inputs.attached["keyboard"];
  50102. if (keyboard) {
  50103. return keyboard.keysLeft;
  50104. }
  50105. return [];
  50106. },
  50107. /**
  50108. * Set the keys for camera movement left.
  50109. */
  50110. set: function (value) {
  50111. var keyboard = this.inputs.attached["keyboard"];
  50112. if (keyboard) {
  50113. keyboard.keysLeft = value;
  50114. }
  50115. },
  50116. enumerable: true,
  50117. configurable: true
  50118. });
  50119. Object.defineProperty(FlyCamera.prototype, "keysRight", {
  50120. /**
  50121. * Set the keys for camera movement right.
  50122. */
  50123. get: function () {
  50124. var keyboard = this.inputs.attached["keyboard"];
  50125. if (keyboard) {
  50126. return keyboard.keysRight;
  50127. }
  50128. return [];
  50129. },
  50130. /**
  50131. * Set the keys for camera movement right.
  50132. */
  50133. set: function (value) {
  50134. var keyboard = this.inputs.attached["keyboard"];
  50135. if (keyboard) {
  50136. keyboard.keysRight = value;
  50137. }
  50138. },
  50139. enumerable: true,
  50140. configurable: true
  50141. });
  50142. /**
  50143. * Attach a control to the HTML DOM element.
  50144. * @param element Defines the element that listens to the input events.
  50145. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  50146. */
  50147. FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
  50148. this.inputs.attachElement(element, noPreventDefault);
  50149. };
  50150. /**
  50151. * Detach a control from the HTML DOM element.
  50152. * The camera will stop reacting to that input.
  50153. * @param element Defines the element that listens to the input events.
  50154. */
  50155. FlyCamera.prototype.detachControl = function (element) {
  50156. this.inputs.detachElement(element);
  50157. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  50158. };
  50159. Object.defineProperty(FlyCamera.prototype, "collisionMask", {
  50160. /**
  50161. * Get the mask that the camera ignores in collision events.
  50162. */
  50163. get: function () {
  50164. return this._collisionMask;
  50165. },
  50166. /**
  50167. * Set the mask that the camera ignores in collision events.
  50168. */
  50169. set: function (mask) {
  50170. this._collisionMask = !isNaN(mask) ? mask : -1;
  50171. },
  50172. enumerable: true,
  50173. configurable: true
  50174. });
  50175. /** @hidden */
  50176. FlyCamera.prototype._collideWithWorld = function (displacement) {
  50177. var globalPosition;
  50178. if (this.parent) {
  50179. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50180. }
  50181. else {
  50182. globalPosition = this.position;
  50183. }
  50184. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50185. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50186. if (!this._collider) {
  50187. this._collider = new BABYLON.Collider();
  50188. }
  50189. this._collider._radius = this.ellipsoid;
  50190. this._collider.collisionMask = this._collisionMask;
  50191. // No need for clone, as long as gravity is not on.
  50192. var actualDisplacement = displacement;
  50193. // Add gravity to direction to prevent dual-collision checking.
  50194. if (this.applyGravity) {
  50195. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  50196. actualDisplacement = displacement.add(this.getScene().gravity);
  50197. }
  50198. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50199. };
  50200. /** @hidden */
  50201. FlyCamera.prototype._checkInputs = function () {
  50202. if (!this._localDirection) {
  50203. this._localDirection = BABYLON.Vector3.Zero();
  50204. this._transformedDirection = BABYLON.Vector3.Zero();
  50205. }
  50206. this.inputs.checkInputs();
  50207. _super.prototype._checkInputs.call(this);
  50208. };
  50209. /** @hidden */
  50210. FlyCamera.prototype._decideIfNeedsToMove = function () {
  50211. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50212. };
  50213. /** @hidden */
  50214. FlyCamera.prototype._updatePosition = function () {
  50215. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50216. this._collideWithWorld(this.cameraDirection);
  50217. }
  50218. else {
  50219. _super.prototype._updatePosition.call(this);
  50220. }
  50221. };
  50222. /**
  50223. * Restore the Roll to its target value at the rate specified.
  50224. * @param rate - Higher means slower restoring.
  50225. * @hidden
  50226. */
  50227. FlyCamera.prototype.restoreRoll = function (rate) {
  50228. var limit = this._trackRoll; // Target Roll.
  50229. var z = this.rotation.z; // Current Roll.
  50230. var delta = limit - z; // Difference in Roll.
  50231. var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  50232. // If the difference is noticable, restore the Roll.
  50233. if (Math.abs(delta) >= minRad) {
  50234. // Change Z rotation towards the target Roll.
  50235. this.rotation.z += delta / rate;
  50236. // Match when near enough.
  50237. if (Math.abs(limit - this.rotation.z) <= minRad) {
  50238. this.rotation.z = limit;
  50239. }
  50240. }
  50241. };
  50242. /**
  50243. * Destroy the camera and release the current resources held by it.
  50244. */
  50245. FlyCamera.prototype.dispose = function () {
  50246. this.inputs.clear();
  50247. _super.prototype.dispose.call(this);
  50248. };
  50249. /**
  50250. * Get the current object class name.
  50251. * @returns the class name.
  50252. */
  50253. FlyCamera.prototype.getClassName = function () {
  50254. return "FlyCamera";
  50255. };
  50256. __decorate([
  50257. BABYLON.serializeAsVector3()
  50258. ], FlyCamera.prototype, "ellipsoid", void 0);
  50259. __decorate([
  50260. BABYLON.serializeAsVector3()
  50261. ], FlyCamera.prototype, "ellipsoidOffset", void 0);
  50262. __decorate([
  50263. BABYLON.serialize()
  50264. ], FlyCamera.prototype, "checkCollisions", void 0);
  50265. __decorate([
  50266. BABYLON.serialize()
  50267. ], FlyCamera.prototype, "applyGravity", void 0);
  50268. return FlyCamera;
  50269. }(BABYLON.TargetCamera));
  50270. BABYLON.FlyCamera = FlyCamera;
  50271. })(BABYLON || (BABYLON = {}));
  50272. //# sourceMappingURL=babylon.flyCamera.js.map
  50273. var BABYLON;
  50274. (function (BABYLON) {
  50275. /**
  50276. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  50277. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50278. */
  50279. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  50280. function ArcRotateCameraKeyboardMoveInput() {
  50281. /**
  50282. * Defines the list of key codes associated with the up action (increase alpha)
  50283. */
  50284. this.keysUp = [38];
  50285. /**
  50286. * Defines the list of key codes associated with the down action (decrease alpha)
  50287. */
  50288. this.keysDown = [40];
  50289. /**
  50290. * Defines the list of key codes associated with the left action (increase beta)
  50291. */
  50292. this.keysLeft = [37];
  50293. /**
  50294. * Defines the list of key codes associated with the right action (decrease beta)
  50295. */
  50296. this.keysRight = [39];
  50297. /**
  50298. * Defines the list of key codes associated with the reset action.
  50299. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  50300. */
  50301. this.keysReset = [220];
  50302. /**
  50303. * Defines the panning sensibility of the inputs.
  50304. * (How fast is the camera paning)
  50305. */
  50306. this.panningSensibility = 50.0;
  50307. /**
  50308. * Defines the zooming sensibility of the inputs.
  50309. * (How fast is the camera zooming)
  50310. */
  50311. this.zoomingSensibility = 25.0;
  50312. /**
  50313. * Defines wether maintaining the alt key down switch the movement mode from
  50314. * orientation to zoom.
  50315. */
  50316. this.useAltToZoom = true;
  50317. /**
  50318. * Rotation speed of the camera
  50319. */
  50320. this.angularSpeed = 0.01;
  50321. this._keys = new Array();
  50322. }
  50323. /**
  50324. * Attach the input controls to a specific dom element to get the input from.
  50325. * @param element Defines the element the controls should be listened from
  50326. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50327. */
  50328. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  50329. var _this = this;
  50330. if (this._onCanvasBlurObserver) {
  50331. return;
  50332. }
  50333. this._scene = this.camera.getScene();
  50334. this._engine = this._scene.getEngine();
  50335. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50336. _this._keys = [];
  50337. });
  50338. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50339. var evt = info.event;
  50340. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50341. _this._ctrlPressed = evt.ctrlKey;
  50342. _this._altPressed = evt.altKey;
  50343. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50344. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50345. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50346. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50347. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50348. var index = _this._keys.indexOf(evt.keyCode);
  50349. if (index === -1) {
  50350. _this._keys.push(evt.keyCode);
  50351. }
  50352. if (evt.preventDefault) {
  50353. if (!noPreventDefault) {
  50354. evt.preventDefault();
  50355. }
  50356. }
  50357. }
  50358. }
  50359. else {
  50360. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50361. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50362. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50363. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50364. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50365. var index = _this._keys.indexOf(evt.keyCode);
  50366. if (index >= 0) {
  50367. _this._keys.splice(index, 1);
  50368. }
  50369. if (evt.preventDefault) {
  50370. if (!noPreventDefault) {
  50371. evt.preventDefault();
  50372. }
  50373. }
  50374. }
  50375. }
  50376. });
  50377. };
  50378. /**
  50379. * Detach the current controls from the specified dom element.
  50380. * @param element Defines the element to stop listening the inputs from
  50381. */
  50382. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  50383. if (this._scene) {
  50384. if (this._onKeyboardObserver) {
  50385. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50386. }
  50387. if (this._onCanvasBlurObserver) {
  50388. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50389. }
  50390. this._onKeyboardObserver = null;
  50391. this._onCanvasBlurObserver = null;
  50392. }
  50393. this._keys = [];
  50394. };
  50395. /**
  50396. * Update the current camera state depending on the inputs that have been used this frame.
  50397. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50398. */
  50399. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  50400. if (this._onKeyboardObserver) {
  50401. var camera = this.camera;
  50402. for (var index = 0; index < this._keys.length; index++) {
  50403. var keyCode = this._keys[index];
  50404. if (this.keysLeft.indexOf(keyCode) !== -1) {
  50405. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50406. camera.inertialPanningX -= 1 / this.panningSensibility;
  50407. }
  50408. else {
  50409. camera.inertialAlphaOffset -= this.angularSpeed;
  50410. }
  50411. }
  50412. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50413. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50414. camera.inertialPanningY += 1 / this.panningSensibility;
  50415. }
  50416. else if (this._altPressed && this.useAltToZoom) {
  50417. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  50418. }
  50419. else {
  50420. camera.inertialBetaOffset -= this.angularSpeed;
  50421. }
  50422. }
  50423. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50424. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50425. camera.inertialPanningX += 1 / this.panningSensibility;
  50426. }
  50427. else {
  50428. camera.inertialAlphaOffset += this.angularSpeed;
  50429. }
  50430. }
  50431. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50432. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50433. camera.inertialPanningY -= 1 / this.panningSensibility;
  50434. }
  50435. else if (this._altPressed && this.useAltToZoom) {
  50436. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  50437. }
  50438. else {
  50439. camera.inertialBetaOffset += this.angularSpeed;
  50440. }
  50441. }
  50442. else if (this.keysReset.indexOf(keyCode) !== -1) {
  50443. if (camera.useInputToRestoreState) {
  50444. camera.restoreState();
  50445. }
  50446. }
  50447. }
  50448. }
  50449. };
  50450. /**
  50451. * Gets the class name of the current intput.
  50452. * @returns the class name
  50453. */
  50454. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  50455. return "ArcRotateCameraKeyboardMoveInput";
  50456. };
  50457. /**
  50458. * Get the friendly name associated with the input class.
  50459. * @returns the input friendly name
  50460. */
  50461. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  50462. return "keyboard";
  50463. };
  50464. __decorate([
  50465. BABYLON.serialize()
  50466. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  50467. __decorate([
  50468. BABYLON.serialize()
  50469. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  50470. __decorate([
  50471. BABYLON.serialize()
  50472. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  50473. __decorate([
  50474. BABYLON.serialize()
  50475. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  50476. __decorate([
  50477. BABYLON.serialize()
  50478. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  50479. __decorate([
  50480. BABYLON.serialize()
  50481. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  50482. __decorate([
  50483. BABYLON.serialize()
  50484. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  50485. __decorate([
  50486. BABYLON.serialize()
  50487. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  50488. __decorate([
  50489. BABYLON.serialize()
  50490. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  50491. return ArcRotateCameraKeyboardMoveInput;
  50492. }());
  50493. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  50494. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  50495. })(BABYLON || (BABYLON = {}));
  50496. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  50497. var BABYLON;
  50498. (function (BABYLON) {
  50499. /**
  50500. * Manage the mouse wheel inputs to control an arc rotate camera.
  50501. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50502. */
  50503. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  50504. function ArcRotateCameraMouseWheelInput() {
  50505. /**
  50506. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50507. */
  50508. this.wheelPrecision = 3.0;
  50509. /**
  50510. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  50511. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  50512. */
  50513. this.wheelDeltaPercentage = 0;
  50514. }
  50515. /**
  50516. * Attach the input controls to a specific dom element to get the input from.
  50517. * @param element Defines the element the controls should be listened from
  50518. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50519. */
  50520. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  50521. var _this = this;
  50522. this._wheel = function (p, s) {
  50523. //sanity check - this should be a PointerWheel event.
  50524. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  50525. return;
  50526. }
  50527. var event = p.event;
  50528. var delta = 0;
  50529. if (event.wheelDelta) {
  50530. if (_this.wheelDeltaPercentage) {
  50531. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  50532. if (event.wheelDelta > 0) {
  50533. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  50534. }
  50535. else {
  50536. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  50537. }
  50538. }
  50539. else {
  50540. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  50541. }
  50542. }
  50543. else {
  50544. var deltaValue = event.deltaY || event.detail;
  50545. delta = -deltaValue / _this.wheelPrecision;
  50546. }
  50547. if (delta) {
  50548. _this.camera.inertialRadiusOffset += delta;
  50549. }
  50550. if (event.preventDefault) {
  50551. if (!noPreventDefault) {
  50552. event.preventDefault();
  50553. }
  50554. }
  50555. };
  50556. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  50557. };
  50558. /**
  50559. * Detach the current controls from the specified dom element.
  50560. * @param element Defines the element to stop listening the inputs from
  50561. */
  50562. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  50563. if (this._observer && element) {
  50564. this.camera.getScene().onPointerObservable.remove(this._observer);
  50565. this._observer = null;
  50566. this._wheel = null;
  50567. }
  50568. };
  50569. /**
  50570. * Gets the class name of the current intput.
  50571. * @returns the class name
  50572. */
  50573. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  50574. return "ArcRotateCameraMouseWheelInput";
  50575. };
  50576. /**
  50577. * Get the friendly name associated with the input class.
  50578. * @returns the input friendly name
  50579. */
  50580. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  50581. return "mousewheel";
  50582. };
  50583. __decorate([
  50584. BABYLON.serialize()
  50585. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  50586. __decorate([
  50587. BABYLON.serialize()
  50588. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  50589. return ArcRotateCameraMouseWheelInput;
  50590. }());
  50591. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  50592. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  50593. })(BABYLON || (BABYLON = {}));
  50594. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  50595. var BABYLON;
  50596. (function (BABYLON) {
  50597. /**
  50598. * Manage the pointers inputs to control an arc rotate camera.
  50599. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50600. */
  50601. var ArcRotateCameraPointersInput = /** @class */ (function () {
  50602. function ArcRotateCameraPointersInput() {
  50603. /**
  50604. * Defines the buttons associated with the input to handle camera move.
  50605. */
  50606. this.buttons = [0, 1, 2];
  50607. /**
  50608. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50609. */
  50610. this.angularSensibilityX = 1000.0;
  50611. /**
  50612. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50613. */
  50614. this.angularSensibilityY = 1000.0;
  50615. /**
  50616. * Defines the pointer pinch precision or how fast is the camera zooming.
  50617. */
  50618. this.pinchPrecision = 12.0;
  50619. /**
  50620. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  50621. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50622. */
  50623. this.pinchDeltaPercentage = 0;
  50624. /**
  50625. * Defines the pointer panning sensibility or how fast is the camera moving.
  50626. */
  50627. this.panningSensibility = 1000.0;
  50628. /**
  50629. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  50630. */
  50631. this.multiTouchPanning = true;
  50632. /**
  50633. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  50634. */
  50635. this.multiTouchPanAndZoom = true;
  50636. /**
  50637. * Revers pinch action direction.
  50638. */
  50639. this.pinchInwards = true;
  50640. this._isPanClick = false;
  50641. }
  50642. /**
  50643. * Attach the input controls to a specific dom element to get the input from.
  50644. * @param element Defines the element the controls should be listened from
  50645. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50646. */
  50647. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  50648. var _this = this;
  50649. var engine = this.camera.getEngine();
  50650. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  50651. var pointA = null;
  50652. var pointB = null;
  50653. var previousPinchSquaredDistance = 0;
  50654. var initialDistance = 0;
  50655. var twoFingerActivityCount = 0;
  50656. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  50657. this._pointerInput = function (p, s) {
  50658. var evt = p.event;
  50659. var isTouch = p.event.pointerType === "touch";
  50660. if (engine.isInVRExclusivePointerMode) {
  50661. return;
  50662. }
  50663. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  50664. return;
  50665. }
  50666. var srcElement = (evt.srcElement || evt.target);
  50667. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  50668. try {
  50669. srcElement.setPointerCapture(evt.pointerId);
  50670. }
  50671. catch (e) {
  50672. //Nothing to do with the error. Execution will continue.
  50673. }
  50674. // Manage panning with pan button click
  50675. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  50676. // manage pointers
  50677. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  50678. if (pointA === null) {
  50679. pointA = cacheSoloPointer;
  50680. }
  50681. else if (pointB === null) {
  50682. pointB = cacheSoloPointer;
  50683. }
  50684. if (!noPreventDefault) {
  50685. evt.preventDefault();
  50686. element.focus();
  50687. }
  50688. }
  50689. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  50690. if (_this.camera.useInputToRestoreState) {
  50691. _this.camera.restoreState();
  50692. }
  50693. }
  50694. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  50695. try {
  50696. srcElement.releasePointerCapture(evt.pointerId);
  50697. }
  50698. catch (e) {
  50699. //Nothing to do with the error.
  50700. }
  50701. cacheSoloPointer = null;
  50702. previousPinchSquaredDistance = 0;
  50703. previousMultiTouchPanPosition.isPaning = false;
  50704. previousMultiTouchPanPosition.isPinching = false;
  50705. twoFingerActivityCount = 0;
  50706. initialDistance = 0;
  50707. if (!isTouch) {
  50708. pointB = null; // Mouse and pen are mono pointer
  50709. }
  50710. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  50711. //but emptying completly pointers collection is required to fix a bug on iPhone :
  50712. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  50713. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  50714. if (engine._badOS) {
  50715. pointA = pointB = null;
  50716. }
  50717. else {
  50718. //only remove the impacted pointer in case of multitouch allowing on most
  50719. //platforms switching from rotate to zoom and pan seamlessly.
  50720. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  50721. pointA = pointB;
  50722. pointB = null;
  50723. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50724. }
  50725. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  50726. pointB = null;
  50727. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50728. }
  50729. else {
  50730. pointA = pointB = null;
  50731. }
  50732. }
  50733. if (!noPreventDefault) {
  50734. evt.preventDefault();
  50735. }
  50736. }
  50737. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50738. if (!noPreventDefault) {
  50739. evt.preventDefault();
  50740. }
  50741. // One button down
  50742. if (pointA && pointB === null && cacheSoloPointer) {
  50743. if (_this.panningSensibility !== 0 &&
  50744. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  50745. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  50746. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  50747. }
  50748. else {
  50749. var offsetX = evt.clientX - cacheSoloPointer.x;
  50750. var offsetY = evt.clientY - cacheSoloPointer.y;
  50751. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50752. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50753. }
  50754. cacheSoloPointer.x = evt.clientX;
  50755. cacheSoloPointer.y = evt.clientY;
  50756. }
  50757. // Two buttons down: pinch/pan
  50758. else if (pointA && pointB) {
  50759. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  50760. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  50761. ed.x = evt.clientX;
  50762. ed.y = evt.clientY;
  50763. var direction = _this.pinchInwards ? 1 : -1;
  50764. var distX = pointA.x - pointB.x;
  50765. var distY = pointA.y - pointB.y;
  50766. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  50767. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  50768. if (previousPinchSquaredDistance === 0) {
  50769. initialDistance = pinchDistance;
  50770. previousPinchSquaredDistance = pinchSquaredDistance;
  50771. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  50772. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  50773. return;
  50774. }
  50775. if (_this.multiTouchPanAndZoom) {
  50776. if (_this.pinchDeltaPercentage) {
  50777. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50778. }
  50779. else {
  50780. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50781. (_this.pinchPrecision *
  50782. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50783. direction);
  50784. }
  50785. if (_this.panningSensibility !== 0) {
  50786. var pointersCenterX = (pointA.x + pointB.x) / 2;
  50787. var pointersCenterY = (pointA.y + pointB.y) / 2;
  50788. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  50789. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  50790. previousMultiTouchPanPosition.x = pointersCenterX;
  50791. previousMultiTouchPanPosition.y = pointersCenterY;
  50792. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  50793. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  50794. }
  50795. }
  50796. else {
  50797. twoFingerActivityCount++;
  50798. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  50799. if (_this.pinchDeltaPercentage) {
  50800. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50801. }
  50802. else {
  50803. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50804. (_this.pinchPrecision *
  50805. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50806. direction);
  50807. }
  50808. previousMultiTouchPanPosition.isPaning = false;
  50809. previousMultiTouchPanPosition.isPinching = true;
  50810. }
  50811. else {
  50812. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  50813. if (!previousMultiTouchPanPosition.isPaning) {
  50814. previousMultiTouchPanPosition.isPaning = true;
  50815. previousMultiTouchPanPosition.isPinching = false;
  50816. previousMultiTouchPanPosition.x = ed.x;
  50817. previousMultiTouchPanPosition.y = ed.y;
  50818. return;
  50819. }
  50820. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  50821. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  50822. }
  50823. }
  50824. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  50825. previousMultiTouchPanPosition.x = ed.x;
  50826. previousMultiTouchPanPosition.y = ed.y;
  50827. }
  50828. }
  50829. previousPinchSquaredDistance = pinchSquaredDistance;
  50830. }
  50831. }
  50832. };
  50833. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  50834. this._onContextMenu = function (evt) {
  50835. evt.preventDefault();
  50836. };
  50837. if (!this.camera._useCtrlForPanning) {
  50838. element.addEventListener("contextmenu", this._onContextMenu, false);
  50839. }
  50840. this._onLostFocus = function () {
  50841. //this._keys = [];
  50842. pointA = pointB = null;
  50843. previousPinchSquaredDistance = 0;
  50844. previousMultiTouchPanPosition.isPaning = false;
  50845. previousMultiTouchPanPosition.isPinching = false;
  50846. twoFingerActivityCount = 0;
  50847. cacheSoloPointer = null;
  50848. initialDistance = 0;
  50849. };
  50850. this._onMouseMove = function (evt) {
  50851. if (!engine.isPointerLock) {
  50852. return;
  50853. }
  50854. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  50855. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  50856. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50857. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50858. if (!noPreventDefault) {
  50859. evt.preventDefault();
  50860. }
  50861. };
  50862. this._onGestureStart = function (e) {
  50863. if (window.MSGesture === undefined) {
  50864. return;
  50865. }
  50866. if (!_this._MSGestureHandler) {
  50867. _this._MSGestureHandler = new MSGesture();
  50868. _this._MSGestureHandler.target = element;
  50869. }
  50870. _this._MSGestureHandler.addPointer(e.pointerId);
  50871. };
  50872. this._onGesture = function (e) {
  50873. _this.camera.radius *= e.scale;
  50874. if (e.preventDefault) {
  50875. if (!noPreventDefault) {
  50876. e.stopPropagation();
  50877. e.preventDefault();
  50878. }
  50879. }
  50880. };
  50881. element.addEventListener("mousemove", this._onMouseMove, false);
  50882. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  50883. element.addEventListener("MSGestureChange", this._onGesture, false);
  50884. BABYLON.Tools.RegisterTopRootEvents([
  50885. { name: "blur", handler: this._onLostFocus }
  50886. ]);
  50887. };
  50888. /**
  50889. * Detach the current controls from the specified dom element.
  50890. * @param element Defines the element to stop listening the inputs from
  50891. */
  50892. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  50893. if (this._onLostFocus) {
  50894. BABYLON.Tools.UnregisterTopRootEvents([
  50895. { name: "blur", handler: this._onLostFocus }
  50896. ]);
  50897. }
  50898. if (element && this._observer) {
  50899. this.camera.getScene().onPointerObservable.remove(this._observer);
  50900. this._observer = null;
  50901. if (this._onContextMenu) {
  50902. element.removeEventListener("contextmenu", this._onContextMenu);
  50903. }
  50904. if (this._onMouseMove) {
  50905. element.removeEventListener("mousemove", this._onMouseMove);
  50906. }
  50907. if (this._onGestureStart) {
  50908. element.removeEventListener("MSPointerDown", this._onGestureStart);
  50909. }
  50910. if (this._onGesture) {
  50911. element.removeEventListener("MSGestureChange", this._onGesture);
  50912. }
  50913. this._isPanClick = false;
  50914. this.pinchInwards = true;
  50915. this._onMouseMove = null;
  50916. this._onGestureStart = null;
  50917. this._onGesture = null;
  50918. this._MSGestureHandler = null;
  50919. this._onLostFocus = null;
  50920. this._onContextMenu = null;
  50921. }
  50922. };
  50923. /**
  50924. * Gets the class name of the current intput.
  50925. * @returns the class name
  50926. */
  50927. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  50928. return "ArcRotateCameraPointersInput";
  50929. };
  50930. /**
  50931. * Get the friendly name associated with the input class.
  50932. * @returns the input friendly name
  50933. */
  50934. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  50935. return "pointers";
  50936. };
  50937. __decorate([
  50938. BABYLON.serialize()
  50939. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  50940. __decorate([
  50941. BABYLON.serialize()
  50942. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  50943. __decorate([
  50944. BABYLON.serialize()
  50945. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  50946. __decorate([
  50947. BABYLON.serialize()
  50948. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  50949. __decorate([
  50950. BABYLON.serialize()
  50951. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  50952. __decorate([
  50953. BABYLON.serialize()
  50954. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  50955. __decorate([
  50956. BABYLON.serialize()
  50957. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  50958. __decorate([
  50959. BABYLON.serialize()
  50960. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  50961. return ArcRotateCameraPointersInput;
  50962. }());
  50963. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  50964. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  50965. })(BABYLON || (BABYLON = {}));
  50966. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  50967. var BABYLON;
  50968. (function (BABYLON) {
  50969. /**
  50970. * Default Inputs manager for the ArcRotateCamera.
  50971. * It groups all the default supported inputs for ease of use.
  50972. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50973. */
  50974. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  50975. __extends(ArcRotateCameraInputsManager, _super);
  50976. /**
  50977. * Instantiates a new ArcRotateCameraInputsManager.
  50978. * @param camera Defines the camera the inputs belong to
  50979. */
  50980. function ArcRotateCameraInputsManager(camera) {
  50981. return _super.call(this, camera) || this;
  50982. }
  50983. /**
  50984. * Add mouse wheel input support to the input manager.
  50985. * @returns the current input manager
  50986. */
  50987. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  50988. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  50989. return this;
  50990. };
  50991. /**
  50992. * Add pointers input support to the input manager.
  50993. * @returns the current input manager
  50994. */
  50995. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  50996. this.add(new BABYLON.ArcRotateCameraPointersInput());
  50997. return this;
  50998. };
  50999. /**
  51000. * Add keyboard input support to the input manager.
  51001. * @returns the current input manager
  51002. */
  51003. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  51004. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  51005. return this;
  51006. };
  51007. /**
  51008. * Add orientation input support to the input manager.
  51009. * @returns the current input manager
  51010. */
  51011. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  51012. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  51013. return this;
  51014. };
  51015. return ArcRotateCameraInputsManager;
  51016. }(BABYLON.CameraInputsManager));
  51017. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  51018. })(BABYLON || (BABYLON = {}));
  51019. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  51020. var BABYLON;
  51021. (function (BABYLON) {
  51022. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  51023. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  51024. });
  51025. /**
  51026. * This represents an orbital type of camera.
  51027. *
  51028. * 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.
  51029. * 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.
  51030. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  51031. */
  51032. var ArcRotateCamera = /** @class */ (function (_super) {
  51033. __extends(ArcRotateCamera, _super);
  51034. /**
  51035. * Instantiates a new ArcRotateCamera in a given scene
  51036. * @param name Defines the name of the camera
  51037. * @param alpha Defines the camera rotation along the logitudinal axis
  51038. * @param beta Defines the camera rotation along the latitudinal axis
  51039. * @param radius Defines the camera distance from its target
  51040. * @param target Defines the camera target
  51041. * @param scene Defines the scene the camera belongs to
  51042. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  51043. */
  51044. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  51045. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  51046. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  51047. /**
  51048. * Current inertia value on the longitudinal axis.
  51049. * The bigger this number the longer it will take for the camera to stop.
  51050. */
  51051. _this.inertialAlphaOffset = 0;
  51052. /**
  51053. * Current inertia value on the latitudinal axis.
  51054. * The bigger this number the longer it will take for the camera to stop.
  51055. */
  51056. _this.inertialBetaOffset = 0;
  51057. /**
  51058. * Current inertia value on the radius axis.
  51059. * The bigger this number the longer it will take for the camera to stop.
  51060. */
  51061. _this.inertialRadiusOffset = 0;
  51062. /**
  51063. * Minimum allowed angle on the longitudinal axis.
  51064. * This can help limiting how the Camera is able to move in the scene.
  51065. */
  51066. _this.lowerAlphaLimit = null;
  51067. /**
  51068. * Maximum allowed angle on the longitudinal axis.
  51069. * This can help limiting how the Camera is able to move in the scene.
  51070. */
  51071. _this.upperAlphaLimit = null;
  51072. /**
  51073. * Minimum allowed angle on the latitudinal axis.
  51074. * This can help limiting how the Camera is able to move in the scene.
  51075. */
  51076. _this.lowerBetaLimit = 0.01;
  51077. /**
  51078. * Maximum allowed angle on the latitudinal axis.
  51079. * This can help limiting how the Camera is able to move in the scene.
  51080. */
  51081. _this.upperBetaLimit = Math.PI;
  51082. /**
  51083. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  51084. * This can help limiting how the Camera is able to move in the scene.
  51085. */
  51086. _this.lowerRadiusLimit = null;
  51087. /**
  51088. * Maximum allowed distance of the camera to the target (The camera can not get further).
  51089. * This can help limiting how the Camera is able to move in the scene.
  51090. */
  51091. _this.upperRadiusLimit = null;
  51092. /**
  51093. * Defines the current inertia value used during panning of the camera along the X axis.
  51094. */
  51095. _this.inertialPanningX = 0;
  51096. /**
  51097. * Defines the current inertia value used during panning of the camera along the Y axis.
  51098. */
  51099. _this.inertialPanningY = 0;
  51100. /**
  51101. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  51102. * Basically if your fingers moves away from more than this distance you will be considered
  51103. * in pinch mode.
  51104. */
  51105. _this.pinchToPanMaxDistance = 20;
  51106. /**
  51107. * Defines the maximum distance the camera can pan.
  51108. * This could help keeping the cammera always in your scene.
  51109. */
  51110. _this.panningDistanceLimit = null;
  51111. /**
  51112. * Defines the target of the camera before paning.
  51113. */
  51114. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  51115. /**
  51116. * Defines the value of the inertia used during panning.
  51117. * 0 would mean stop inertia and one would mean no decelleration at all.
  51118. */
  51119. _this.panningInertia = 0.9;
  51120. //-- end properties for backward compatibility for inputs
  51121. /**
  51122. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  51123. */
  51124. _this.zoomOnFactor = 1;
  51125. /**
  51126. * Defines a screen offset for the camera position.
  51127. */
  51128. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  51129. /**
  51130. * Allows the camera to be completely reversed.
  51131. * If false the camera can not arrive upside down.
  51132. */
  51133. _this.allowUpsideDown = true;
  51134. /**
  51135. * Define if double tap/click is used to restore the previously saved state of the camera.
  51136. */
  51137. _this.useInputToRestoreState = true;
  51138. /** @hidden */
  51139. _this._viewMatrix = new BABYLON.Matrix();
  51140. /**
  51141. * Defines the allowed panning axis.
  51142. */
  51143. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  51144. /**
  51145. * Observable triggered when the mesh target has been changed on the camera.
  51146. */
  51147. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  51148. /**
  51149. * Defines whether the camera should check collision with the objects oh the scene.
  51150. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  51151. */
  51152. _this.checkCollisions = false;
  51153. /**
  51154. * Defines the collision radius of the camera.
  51155. * This simulates a sphere around the camera.
  51156. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  51157. */
  51158. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51159. _this._previousPosition = BABYLON.Vector3.Zero();
  51160. _this._collisionVelocity = BABYLON.Vector3.Zero();
  51161. _this._newPosition = BABYLON.Vector3.Zero();
  51162. _this._computationVector = BABYLON.Vector3.Zero();
  51163. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  51164. if (collidedMesh === void 0) { collidedMesh = null; }
  51165. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  51166. newPosition.multiplyInPlace(_this._collider._radius);
  51167. }
  51168. if (!collidedMesh) {
  51169. _this._previousPosition.copyFrom(_this.position);
  51170. }
  51171. else {
  51172. _this.setPosition(newPosition);
  51173. if (_this.onCollide) {
  51174. _this.onCollide(collidedMesh);
  51175. }
  51176. }
  51177. // Recompute because of constraints
  51178. var cosa = Math.cos(_this.alpha);
  51179. var sina = Math.sin(_this.alpha);
  51180. var cosb = Math.cos(_this.beta);
  51181. var sinb = Math.sin(_this.beta);
  51182. if (sinb === 0) {
  51183. sinb = 0.0001;
  51184. }
  51185. var target = _this._getTargetPosition();
  51186. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  51187. target.addToRef(_this._computationVector, _this._newPosition);
  51188. _this.position.copyFrom(_this._newPosition);
  51189. var up = _this.upVector;
  51190. if (_this.allowUpsideDown && _this.beta < 0) {
  51191. up = up.clone();
  51192. up = up.negate();
  51193. }
  51194. _this._computeViewMatrix(_this.position, target, up);
  51195. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  51196. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  51197. _this._collisionTriggered = false;
  51198. };
  51199. _this._target = BABYLON.Vector3.Zero();
  51200. if (target) {
  51201. _this.setTarget(target);
  51202. }
  51203. _this.alpha = alpha;
  51204. _this.beta = beta;
  51205. _this.radius = radius;
  51206. _this.getViewMatrix();
  51207. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  51208. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  51209. return _this;
  51210. }
  51211. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  51212. /**
  51213. * Defines the target point of the camera.
  51214. * The camera looks towards it form the radius distance.
  51215. */
  51216. get: function () {
  51217. return this._target;
  51218. },
  51219. set: function (value) {
  51220. this.setTarget(value);
  51221. },
  51222. enumerable: true,
  51223. configurable: true
  51224. });
  51225. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  51226. //-- begin properties for backward compatibility for inputs
  51227. /**
  51228. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51229. */
  51230. get: function () {
  51231. var pointers = this.inputs.attached["pointers"];
  51232. if (pointers) {
  51233. return pointers.angularSensibilityX;
  51234. }
  51235. return 0;
  51236. },
  51237. set: function (value) {
  51238. var pointers = this.inputs.attached["pointers"];
  51239. if (pointers) {
  51240. pointers.angularSensibilityX = value;
  51241. }
  51242. },
  51243. enumerable: true,
  51244. configurable: true
  51245. });
  51246. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  51247. /**
  51248. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51249. */
  51250. get: function () {
  51251. var pointers = this.inputs.attached["pointers"];
  51252. if (pointers) {
  51253. return pointers.angularSensibilityY;
  51254. }
  51255. return 0;
  51256. },
  51257. set: function (value) {
  51258. var pointers = this.inputs.attached["pointers"];
  51259. if (pointers) {
  51260. pointers.angularSensibilityY = value;
  51261. }
  51262. },
  51263. enumerable: true,
  51264. configurable: true
  51265. });
  51266. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  51267. /**
  51268. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  51269. */
  51270. get: function () {
  51271. var pointers = this.inputs.attached["pointers"];
  51272. if (pointers) {
  51273. return pointers.pinchPrecision;
  51274. }
  51275. return 0;
  51276. },
  51277. set: function (value) {
  51278. var pointers = this.inputs.attached["pointers"];
  51279. if (pointers) {
  51280. pointers.pinchPrecision = value;
  51281. }
  51282. },
  51283. enumerable: true,
  51284. configurable: true
  51285. });
  51286. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  51287. /**
  51288. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  51289. * It will be used instead of pinchDeltaPrecision if different from 0.
  51290. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51291. */
  51292. get: function () {
  51293. var pointers = this.inputs.attached["pointers"];
  51294. if (pointers) {
  51295. return pointers.pinchDeltaPercentage;
  51296. }
  51297. return 0;
  51298. },
  51299. set: function (value) {
  51300. var pointers = this.inputs.attached["pointers"];
  51301. if (pointers) {
  51302. pointers.pinchDeltaPercentage = value;
  51303. }
  51304. },
  51305. enumerable: true,
  51306. configurable: true
  51307. });
  51308. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  51309. /**
  51310. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  51311. */
  51312. get: function () {
  51313. var pointers = this.inputs.attached["pointers"];
  51314. if (pointers) {
  51315. return pointers.panningSensibility;
  51316. }
  51317. return 0;
  51318. },
  51319. set: function (value) {
  51320. var pointers = this.inputs.attached["pointers"];
  51321. if (pointers) {
  51322. pointers.panningSensibility = value;
  51323. }
  51324. },
  51325. enumerable: true,
  51326. configurable: true
  51327. });
  51328. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  51329. /**
  51330. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  51331. */
  51332. get: function () {
  51333. var keyboard = this.inputs.attached["keyboard"];
  51334. if (keyboard) {
  51335. return keyboard.keysUp;
  51336. }
  51337. return [];
  51338. },
  51339. set: function (value) {
  51340. var keyboard = this.inputs.attached["keyboard"];
  51341. if (keyboard) {
  51342. keyboard.keysUp = value;
  51343. }
  51344. },
  51345. enumerable: true,
  51346. configurable: true
  51347. });
  51348. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  51349. /**
  51350. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  51351. */
  51352. get: function () {
  51353. var keyboard = this.inputs.attached["keyboard"];
  51354. if (keyboard) {
  51355. return keyboard.keysDown;
  51356. }
  51357. return [];
  51358. },
  51359. set: function (value) {
  51360. var keyboard = this.inputs.attached["keyboard"];
  51361. if (keyboard) {
  51362. keyboard.keysDown = value;
  51363. }
  51364. },
  51365. enumerable: true,
  51366. configurable: true
  51367. });
  51368. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  51369. /**
  51370. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  51371. */
  51372. get: function () {
  51373. var keyboard = this.inputs.attached["keyboard"];
  51374. if (keyboard) {
  51375. return keyboard.keysLeft;
  51376. }
  51377. return [];
  51378. },
  51379. set: function (value) {
  51380. var keyboard = this.inputs.attached["keyboard"];
  51381. if (keyboard) {
  51382. keyboard.keysLeft = value;
  51383. }
  51384. },
  51385. enumerable: true,
  51386. configurable: true
  51387. });
  51388. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  51389. /**
  51390. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  51391. */
  51392. get: function () {
  51393. var keyboard = this.inputs.attached["keyboard"];
  51394. if (keyboard) {
  51395. return keyboard.keysRight;
  51396. }
  51397. return [];
  51398. },
  51399. set: function (value) {
  51400. var keyboard = this.inputs.attached["keyboard"];
  51401. if (keyboard) {
  51402. keyboard.keysRight = value;
  51403. }
  51404. },
  51405. enumerable: true,
  51406. configurable: true
  51407. });
  51408. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  51409. /**
  51410. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  51411. */
  51412. get: function () {
  51413. var mousewheel = this.inputs.attached["mousewheel"];
  51414. if (mousewheel) {
  51415. return mousewheel.wheelPrecision;
  51416. }
  51417. return 0;
  51418. },
  51419. set: function (value) {
  51420. var mousewheel = this.inputs.attached["mousewheel"];
  51421. if (mousewheel) {
  51422. mousewheel.wheelPrecision = value;
  51423. }
  51424. },
  51425. enumerable: true,
  51426. configurable: true
  51427. });
  51428. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  51429. /**
  51430. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  51431. * It will be used instead of pinchDeltaPrecision if different from 0.
  51432. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51433. */
  51434. get: function () {
  51435. var mousewheel = this.inputs.attached["mousewheel"];
  51436. if (mousewheel) {
  51437. return mousewheel.wheelDeltaPercentage;
  51438. }
  51439. return 0;
  51440. },
  51441. set: function (value) {
  51442. var mousewheel = this.inputs.attached["mousewheel"];
  51443. if (mousewheel) {
  51444. mousewheel.wheelDeltaPercentage = value;
  51445. }
  51446. },
  51447. enumerable: true,
  51448. configurable: true
  51449. });
  51450. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  51451. /**
  51452. * Gets the bouncing behavior of the camera if it has been enabled.
  51453. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51454. */
  51455. get: function () {
  51456. return this._bouncingBehavior;
  51457. },
  51458. enumerable: true,
  51459. configurable: true
  51460. });
  51461. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  51462. /**
  51463. * Defines if the bouncing behavior of the camera is enabled on the camera.
  51464. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51465. */
  51466. get: function () {
  51467. return this._bouncingBehavior != null;
  51468. },
  51469. set: function (value) {
  51470. if (value === this.useBouncingBehavior) {
  51471. return;
  51472. }
  51473. if (value) {
  51474. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  51475. this.addBehavior(this._bouncingBehavior);
  51476. }
  51477. else if (this._bouncingBehavior) {
  51478. this.removeBehavior(this._bouncingBehavior);
  51479. this._bouncingBehavior = null;
  51480. }
  51481. },
  51482. enumerable: true,
  51483. configurable: true
  51484. });
  51485. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  51486. /**
  51487. * Gets the framing behavior of the camera if it has been enabled.
  51488. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51489. */
  51490. get: function () {
  51491. return this._framingBehavior;
  51492. },
  51493. enumerable: true,
  51494. configurable: true
  51495. });
  51496. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  51497. /**
  51498. * Defines if the framing behavior of the camera is enabled on the camera.
  51499. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51500. */
  51501. get: function () {
  51502. return this._framingBehavior != null;
  51503. },
  51504. set: function (value) {
  51505. if (value === this.useFramingBehavior) {
  51506. return;
  51507. }
  51508. if (value) {
  51509. this._framingBehavior = new BABYLON.FramingBehavior();
  51510. this.addBehavior(this._framingBehavior);
  51511. }
  51512. else if (this._framingBehavior) {
  51513. this.removeBehavior(this._framingBehavior);
  51514. this._framingBehavior = null;
  51515. }
  51516. },
  51517. enumerable: true,
  51518. configurable: true
  51519. });
  51520. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  51521. /**
  51522. * Gets the auto rotation behavior of the camera if it has been enabled.
  51523. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51524. */
  51525. get: function () {
  51526. return this._autoRotationBehavior;
  51527. },
  51528. enumerable: true,
  51529. configurable: true
  51530. });
  51531. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  51532. /**
  51533. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  51534. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51535. */
  51536. get: function () {
  51537. return this._autoRotationBehavior != null;
  51538. },
  51539. set: function (value) {
  51540. if (value === this.useAutoRotationBehavior) {
  51541. return;
  51542. }
  51543. if (value) {
  51544. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  51545. this.addBehavior(this._autoRotationBehavior);
  51546. }
  51547. else if (this._autoRotationBehavior) {
  51548. this.removeBehavior(this._autoRotationBehavior);
  51549. this._autoRotationBehavior = null;
  51550. }
  51551. },
  51552. enumerable: true,
  51553. configurable: true
  51554. });
  51555. // Cache
  51556. /** @hidden */
  51557. ArcRotateCamera.prototype._initCache = function () {
  51558. _super.prototype._initCache.call(this);
  51559. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51560. this._cache.alpha = undefined;
  51561. this._cache.beta = undefined;
  51562. this._cache.radius = undefined;
  51563. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  51564. };
  51565. /** @hidden */
  51566. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  51567. if (!ignoreParentClass) {
  51568. _super.prototype._updateCache.call(this);
  51569. }
  51570. this._cache._target.copyFrom(this._getTargetPosition());
  51571. this._cache.alpha = this.alpha;
  51572. this._cache.beta = this.beta;
  51573. this._cache.radius = this.radius;
  51574. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  51575. };
  51576. ArcRotateCamera.prototype._getTargetPosition = function () {
  51577. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  51578. var pos = this._targetHost.getAbsolutePosition();
  51579. if (this._targetBoundingCenter) {
  51580. pos.addToRef(this._targetBoundingCenter, this._target);
  51581. }
  51582. else {
  51583. this._target.copyFrom(pos);
  51584. }
  51585. }
  51586. var lockedTargetPosition = this._getLockedTargetPosition();
  51587. if (lockedTargetPosition) {
  51588. return lockedTargetPosition;
  51589. }
  51590. return this._target;
  51591. };
  51592. /**
  51593. * Stores the current state of the camera (alpha, beta, radius and target)
  51594. * @returns the camera itself
  51595. */
  51596. ArcRotateCamera.prototype.storeState = function () {
  51597. this._storedAlpha = this.alpha;
  51598. this._storedBeta = this.beta;
  51599. this._storedRadius = this.radius;
  51600. this._storedTarget = this._getTargetPosition().clone();
  51601. return _super.prototype.storeState.call(this);
  51602. };
  51603. /**
  51604. * @hidden
  51605. * Restored camera state. You must call storeState() first
  51606. */
  51607. ArcRotateCamera.prototype._restoreStateValues = function () {
  51608. if (!_super.prototype._restoreStateValues.call(this)) {
  51609. return false;
  51610. }
  51611. this.alpha = this._storedAlpha;
  51612. this.beta = this._storedBeta;
  51613. this.radius = this._storedRadius;
  51614. this.setTarget(this._storedTarget.clone());
  51615. this.inertialAlphaOffset = 0;
  51616. this.inertialBetaOffset = 0;
  51617. this.inertialRadiusOffset = 0;
  51618. this.inertialPanningX = 0;
  51619. this.inertialPanningY = 0;
  51620. return true;
  51621. };
  51622. // Synchronized
  51623. /** @hidden */
  51624. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  51625. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  51626. return false;
  51627. }
  51628. return this._cache._target.equals(this._getTargetPosition())
  51629. && this._cache.alpha === this.alpha
  51630. && this._cache.beta === this.beta
  51631. && this._cache.radius === this.radius
  51632. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  51633. };
  51634. /**
  51635. * Attached controls to the current camera.
  51636. * @param element Defines the element the controls should be listened from
  51637. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51638. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  51639. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  51640. */
  51641. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  51642. var _this = this;
  51643. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  51644. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  51645. this._useCtrlForPanning = useCtrlForPanning;
  51646. this._panningMouseButton = panningMouseButton;
  51647. this.inputs.attachElement(element, noPreventDefault);
  51648. this._reset = function () {
  51649. _this.inertialAlphaOffset = 0;
  51650. _this.inertialBetaOffset = 0;
  51651. _this.inertialRadiusOffset = 0;
  51652. _this.inertialPanningX = 0;
  51653. _this.inertialPanningY = 0;
  51654. };
  51655. };
  51656. /**
  51657. * Detach the current controls from the camera.
  51658. * The camera will stop reacting to inputs.
  51659. * @param element Defines the element to stop listening the inputs from
  51660. */
  51661. ArcRotateCamera.prototype.detachControl = function (element) {
  51662. this.inputs.detachElement(element);
  51663. if (this._reset) {
  51664. this._reset();
  51665. }
  51666. };
  51667. /** @hidden */
  51668. ArcRotateCamera.prototype._checkInputs = function () {
  51669. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  51670. if (this._collisionTriggered) {
  51671. return;
  51672. }
  51673. this.inputs.checkInputs();
  51674. // Inertia
  51675. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  51676. var inertialAlphaOffset = this.inertialAlphaOffset;
  51677. if (this.beta <= 0) {
  51678. inertialAlphaOffset *= -1;
  51679. }
  51680. if (this.getScene().useRightHandedSystem) {
  51681. inertialAlphaOffset *= -1;
  51682. }
  51683. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  51684. inertialAlphaOffset *= -1;
  51685. }
  51686. this.alpha += inertialAlphaOffset;
  51687. this.beta += this.inertialBetaOffset;
  51688. this.radius -= this.inertialRadiusOffset;
  51689. this.inertialAlphaOffset *= this.inertia;
  51690. this.inertialBetaOffset *= this.inertia;
  51691. this.inertialRadiusOffset *= this.inertia;
  51692. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  51693. this.inertialAlphaOffset = 0;
  51694. }
  51695. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  51696. this.inertialBetaOffset = 0;
  51697. }
  51698. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  51699. this.inertialRadiusOffset = 0;
  51700. }
  51701. }
  51702. // Panning inertia
  51703. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  51704. if (!this._localDirection) {
  51705. this._localDirection = BABYLON.Vector3.Zero();
  51706. this._transformedDirection = BABYLON.Vector3.Zero();
  51707. }
  51708. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  51709. this._localDirection.multiplyInPlace(this.panningAxis);
  51710. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  51711. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  51712. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  51713. if (!this.panningAxis.y) {
  51714. this._transformedDirection.y = 0;
  51715. }
  51716. if (!this._targetHost) {
  51717. if (this.panningDistanceLimit) {
  51718. this._transformedDirection.addInPlace(this._target);
  51719. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  51720. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  51721. this._target.copyFrom(this._transformedDirection);
  51722. }
  51723. }
  51724. else {
  51725. this._target.addInPlace(this._transformedDirection);
  51726. }
  51727. }
  51728. this.inertialPanningX *= this.panningInertia;
  51729. this.inertialPanningY *= this.panningInertia;
  51730. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  51731. this.inertialPanningX = 0;
  51732. }
  51733. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  51734. this.inertialPanningY = 0;
  51735. }
  51736. }
  51737. // Limits
  51738. this._checkLimits();
  51739. _super.prototype._checkInputs.call(this);
  51740. };
  51741. ArcRotateCamera.prototype._checkLimits = function () {
  51742. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  51743. if (this.allowUpsideDown && this.beta > Math.PI) {
  51744. this.beta = this.beta - (2 * Math.PI);
  51745. }
  51746. }
  51747. else {
  51748. if (this.beta < this.lowerBetaLimit) {
  51749. this.beta = this.lowerBetaLimit;
  51750. }
  51751. }
  51752. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  51753. if (this.allowUpsideDown && this.beta < -Math.PI) {
  51754. this.beta = this.beta + (2 * Math.PI);
  51755. }
  51756. }
  51757. else {
  51758. if (this.beta > this.upperBetaLimit) {
  51759. this.beta = this.upperBetaLimit;
  51760. }
  51761. }
  51762. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  51763. this.alpha = this.lowerAlphaLimit;
  51764. }
  51765. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  51766. this.alpha = this.upperAlphaLimit;
  51767. }
  51768. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  51769. this.radius = this.lowerRadiusLimit;
  51770. }
  51771. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  51772. this.radius = this.upperRadiusLimit;
  51773. }
  51774. };
  51775. /**
  51776. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  51777. */
  51778. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  51779. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  51780. this.radius = this._computationVector.length();
  51781. if (this.radius === 0) {
  51782. this.radius = 0.0001; // Just to avoid division by zero
  51783. }
  51784. // Alpha
  51785. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  51786. if (this._computationVector.z < 0) {
  51787. this.alpha = 2 * Math.PI - this.alpha;
  51788. }
  51789. // Beta
  51790. this.beta = Math.acos(this._computationVector.y / this.radius);
  51791. this._checkLimits();
  51792. };
  51793. /**
  51794. * Use a position to define the current camera related information like aplha, beta and radius
  51795. * @param position Defines the position to set the camera at
  51796. */
  51797. ArcRotateCamera.prototype.setPosition = function (position) {
  51798. if (this.position.equals(position)) {
  51799. return;
  51800. }
  51801. this.position.copyFrom(position);
  51802. this.rebuildAnglesAndRadius();
  51803. };
  51804. /**
  51805. * Defines the target the camera should look at.
  51806. * This will automatically adapt alpha beta and radius to fit within the new target.
  51807. * @param target Defines the new target as a Vector or a mesh
  51808. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  51809. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  51810. */
  51811. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  51812. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  51813. if (allowSamePosition === void 0) { allowSamePosition = false; }
  51814. if (target.getBoundingInfo) {
  51815. if (toBoundingCenter) {
  51816. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  51817. }
  51818. else {
  51819. this._targetBoundingCenter = null;
  51820. }
  51821. this._targetHost = target;
  51822. this._target = this._getTargetPosition();
  51823. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  51824. }
  51825. else {
  51826. var newTarget = target;
  51827. var currentTarget = this._getTargetPosition();
  51828. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  51829. return;
  51830. }
  51831. this._targetHost = null;
  51832. this._target = newTarget;
  51833. this._targetBoundingCenter = null;
  51834. this.onMeshTargetChangedObservable.notifyObservers(null);
  51835. }
  51836. this.rebuildAnglesAndRadius();
  51837. };
  51838. /** @hidden */
  51839. ArcRotateCamera.prototype._getViewMatrix = function () {
  51840. // Compute
  51841. var cosa = Math.cos(this.alpha);
  51842. var sina = Math.sin(this.alpha);
  51843. var cosb = Math.cos(this.beta);
  51844. var sinb = Math.sin(this.beta);
  51845. if (sinb === 0) {
  51846. sinb = 0.0001;
  51847. }
  51848. var target = this._getTargetPosition();
  51849. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  51850. target.addToRef(this._computationVector, this._newPosition);
  51851. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  51852. if (!this._collider) {
  51853. this._collider = new BABYLON.Collider();
  51854. }
  51855. this._collider._radius = this.collisionRadius;
  51856. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  51857. this._collisionTriggered = true;
  51858. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  51859. }
  51860. else {
  51861. this.position.copyFrom(this._newPosition);
  51862. var up = this.upVector;
  51863. if (this.allowUpsideDown && sinb < 0) {
  51864. up = up.clone();
  51865. up = up.negate();
  51866. }
  51867. this._computeViewMatrix(this.position, target, up);
  51868. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  51869. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  51870. }
  51871. this._currentTarget = target;
  51872. return this._viewMatrix;
  51873. };
  51874. /**
  51875. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  51876. * @param meshes Defines the mesh to zoom on
  51877. * @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)
  51878. */
  51879. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  51880. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51881. meshes = meshes || this.getScene().meshes;
  51882. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  51883. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  51884. this.radius = distance * this.zoomOnFactor;
  51885. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  51886. };
  51887. /**
  51888. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  51889. * The target will be changed but the radius
  51890. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  51891. * @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)
  51892. */
  51893. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  51894. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51895. var meshesOrMinMaxVector;
  51896. var distance;
  51897. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  51898. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  51899. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  51900. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  51901. }
  51902. else { //minMaxVector and distance
  51903. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  51904. meshesOrMinMaxVector = minMaxVectorAndDistance;
  51905. distance = minMaxVectorAndDistance.distance;
  51906. }
  51907. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  51908. if (!doNotUpdateMaxZ) {
  51909. this.maxZ = distance * 2;
  51910. }
  51911. };
  51912. /**
  51913. * @override
  51914. * Override Camera.createRigCamera
  51915. */
  51916. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  51917. var alphaShift = 0;
  51918. switch (this.cameraRigMode) {
  51919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51921. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51922. case BABYLON.Camera.RIG_MODE_VR:
  51923. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  51924. break;
  51925. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51926. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  51927. break;
  51928. }
  51929. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  51930. rigCam._cameraRigParams = {};
  51931. return rigCam;
  51932. };
  51933. /**
  51934. * @hidden
  51935. * @override
  51936. * Override Camera._updateRigCameras
  51937. */
  51938. ArcRotateCamera.prototype._updateRigCameras = function () {
  51939. var camLeft = this._rigCameras[0];
  51940. var camRight = this._rigCameras[1];
  51941. camLeft.beta = camRight.beta = this.beta;
  51942. camLeft.radius = camRight.radius = this.radius;
  51943. switch (this.cameraRigMode) {
  51944. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51945. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51946. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51947. case BABYLON.Camera.RIG_MODE_VR:
  51948. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51949. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51950. break;
  51951. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51952. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  51953. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  51954. break;
  51955. }
  51956. _super.prototype._updateRigCameras.call(this);
  51957. };
  51958. /**
  51959. * Destroy the camera and release the current resources hold by it.
  51960. */
  51961. ArcRotateCamera.prototype.dispose = function () {
  51962. this.inputs.clear();
  51963. _super.prototype.dispose.call(this);
  51964. };
  51965. /**
  51966. * Gets the current object class name.
  51967. * @return the class name
  51968. */
  51969. ArcRotateCamera.prototype.getClassName = function () {
  51970. return "ArcRotateCamera";
  51971. };
  51972. __decorate([
  51973. BABYLON.serialize()
  51974. ], ArcRotateCamera.prototype, "alpha", void 0);
  51975. __decorate([
  51976. BABYLON.serialize()
  51977. ], ArcRotateCamera.prototype, "beta", void 0);
  51978. __decorate([
  51979. BABYLON.serialize()
  51980. ], ArcRotateCamera.prototype, "radius", void 0);
  51981. __decorate([
  51982. BABYLON.serializeAsVector3("target")
  51983. ], ArcRotateCamera.prototype, "_target", void 0);
  51984. __decorate([
  51985. BABYLON.serialize()
  51986. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  51987. __decorate([
  51988. BABYLON.serialize()
  51989. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  51990. __decorate([
  51991. BABYLON.serialize()
  51992. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  51993. __decorate([
  51994. BABYLON.serialize()
  51995. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  51996. __decorate([
  51997. BABYLON.serialize()
  51998. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  51999. __decorate([
  52000. BABYLON.serialize()
  52001. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  52002. __decorate([
  52003. BABYLON.serialize()
  52004. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  52005. __decorate([
  52006. BABYLON.serialize()
  52007. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  52008. __decorate([
  52009. BABYLON.serialize()
  52010. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  52011. __decorate([
  52012. BABYLON.serialize()
  52013. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  52014. __decorate([
  52015. BABYLON.serialize()
  52016. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  52017. __decorate([
  52018. BABYLON.serialize()
  52019. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  52020. __decorate([
  52021. BABYLON.serialize()
  52022. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  52023. __decorate([
  52024. BABYLON.serializeAsVector3()
  52025. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  52026. __decorate([
  52027. BABYLON.serialize()
  52028. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  52029. __decorate([
  52030. BABYLON.serialize()
  52031. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  52032. __decorate([
  52033. BABYLON.serialize()
  52034. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  52035. __decorate([
  52036. BABYLON.serialize()
  52037. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  52038. __decorate([
  52039. BABYLON.serialize()
  52040. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  52041. return ArcRotateCamera;
  52042. }(BABYLON.TargetCamera));
  52043. BABYLON.ArcRotateCamera = ArcRotateCamera;
  52044. })(BABYLON || (BABYLON = {}));
  52045. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  52046. var BABYLON;
  52047. (function (BABYLON) {
  52048. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  52049. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  52050. });
  52051. /**
  52052. * The HemisphericLight simulates the ambient environment light,
  52053. * so the passed direction is the light reflection direction, not the incoming direction.
  52054. */
  52055. var HemisphericLight = /** @class */ (function (_super) {
  52056. __extends(HemisphericLight, _super);
  52057. /**
  52058. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  52059. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  52060. * The HemisphericLight can't cast shadows.
  52061. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52062. * @param name The friendly name of the light
  52063. * @param direction The direction of the light reflection
  52064. * @param scene The scene the light belongs to
  52065. */
  52066. function HemisphericLight(name, direction, scene) {
  52067. var _this = _super.call(this, name, scene) || this;
  52068. /**
  52069. * The groundColor is the light in the opposite direction to the one specified during creation.
  52070. * 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.
  52071. */
  52072. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  52073. _this.direction = direction || BABYLON.Vector3.Up();
  52074. return _this;
  52075. }
  52076. HemisphericLight.prototype._buildUniformLayout = function () {
  52077. this._uniformBuffer.addUniform("vLightData", 4);
  52078. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52079. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52080. this._uniformBuffer.addUniform("vLightGround", 3);
  52081. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52082. this._uniformBuffer.addUniform("depthValues", 2);
  52083. this._uniformBuffer.create();
  52084. };
  52085. /**
  52086. * Returns the string "HemisphericLight".
  52087. * @return The class name
  52088. */
  52089. HemisphericLight.prototype.getClassName = function () {
  52090. return "HemisphericLight";
  52091. };
  52092. /**
  52093. * Sets the HemisphericLight direction towards the passed target (Vector3).
  52094. * Returns the updated direction.
  52095. * @param target The target the direction should point to
  52096. * @return The computed direction
  52097. */
  52098. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  52099. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  52100. return this.direction;
  52101. };
  52102. /**
  52103. * Returns the shadow generator associated to the light.
  52104. * @returns Always null for hemispheric lights because it does not support shadows.
  52105. */
  52106. HemisphericLight.prototype.getShadowGenerator = function () {
  52107. return null;
  52108. };
  52109. /**
  52110. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  52111. * @param effect The effect to update
  52112. * @param lightIndex The index of the light in the effect to update
  52113. * @returns The hemispheric light
  52114. */
  52115. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  52116. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52117. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  52118. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  52119. return this;
  52120. };
  52121. /**
  52122. * Computes the world matrix of the node
  52123. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52124. * @param useWasUpdatedFlag defines a reserved property
  52125. * @returns the world matrix
  52126. */
  52127. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  52128. if (!this._worldMatrix) {
  52129. this._worldMatrix = BABYLON.Matrix.Identity();
  52130. }
  52131. return this._worldMatrix;
  52132. };
  52133. /**
  52134. * Returns the integer 3.
  52135. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52136. */
  52137. HemisphericLight.prototype.getTypeID = function () {
  52138. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  52139. };
  52140. /**
  52141. * Prepares the list of defines specific to the light type.
  52142. * @param defines the list of defines
  52143. * @param lightIndex defines the index of the light for the effect
  52144. */
  52145. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52146. defines["HEMILIGHT" + lightIndex] = true;
  52147. };
  52148. __decorate([
  52149. BABYLON.serializeAsColor3()
  52150. ], HemisphericLight.prototype, "groundColor", void 0);
  52151. __decorate([
  52152. BABYLON.serializeAsVector3()
  52153. ], HemisphericLight.prototype, "direction", void 0);
  52154. return HemisphericLight;
  52155. }(BABYLON.Light));
  52156. BABYLON.HemisphericLight = HemisphericLight;
  52157. })(BABYLON || (BABYLON = {}));
  52158. //# sourceMappingURL=babylon.hemisphericLight.js.map
  52159. var BABYLON;
  52160. (function (BABYLON) {
  52161. /**
  52162. * Base implementation IShadowLight
  52163. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  52164. */
  52165. var ShadowLight = /** @class */ (function (_super) {
  52166. __extends(ShadowLight, _super);
  52167. function ShadowLight() {
  52168. var _this = _super !== null && _super.apply(this, arguments) || this;
  52169. _this._needProjectionMatrixCompute = true;
  52170. return _this;
  52171. }
  52172. ShadowLight.prototype._setPosition = function (value) {
  52173. this._position = value;
  52174. };
  52175. Object.defineProperty(ShadowLight.prototype, "position", {
  52176. /**
  52177. * Sets the position the shadow will be casted from. Also use as the light position for both
  52178. * point and spot lights.
  52179. */
  52180. get: function () {
  52181. return this._position;
  52182. },
  52183. /**
  52184. * Sets the position the shadow will be casted from. Also use as the light position for both
  52185. * point and spot lights.
  52186. */
  52187. set: function (value) {
  52188. this._setPosition(value);
  52189. },
  52190. enumerable: true,
  52191. configurable: true
  52192. });
  52193. ShadowLight.prototype._setDirection = function (value) {
  52194. this._direction = value;
  52195. };
  52196. Object.defineProperty(ShadowLight.prototype, "direction", {
  52197. /**
  52198. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  52199. * Also use as the light direction on spot and directional lights.
  52200. */
  52201. get: function () {
  52202. return this._direction;
  52203. },
  52204. /**
  52205. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  52206. * Also use as the light direction on spot and directional lights.
  52207. */
  52208. set: function (value) {
  52209. this._setDirection(value);
  52210. },
  52211. enumerable: true,
  52212. configurable: true
  52213. });
  52214. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  52215. /**
  52216. * Gets the shadow projection clipping minimum z value.
  52217. */
  52218. get: function () {
  52219. return this._shadowMinZ;
  52220. },
  52221. /**
  52222. * Sets the shadow projection clipping minimum z value.
  52223. */
  52224. set: function (value) {
  52225. this._shadowMinZ = value;
  52226. this.forceProjectionMatrixCompute();
  52227. },
  52228. enumerable: true,
  52229. configurable: true
  52230. });
  52231. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  52232. /**
  52233. * Sets the shadow projection clipping maximum z value.
  52234. */
  52235. get: function () {
  52236. return this._shadowMaxZ;
  52237. },
  52238. /**
  52239. * Gets the shadow projection clipping maximum z value.
  52240. */
  52241. set: function (value) {
  52242. this._shadowMaxZ = value;
  52243. this.forceProjectionMatrixCompute();
  52244. },
  52245. enumerable: true,
  52246. configurable: true
  52247. });
  52248. /**
  52249. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  52250. * @returns true if the information has been computed, false if it does not need to (no parenting)
  52251. */
  52252. ShadowLight.prototype.computeTransformedInformation = function () {
  52253. if (this.parent && this.parent.getWorldMatrix) {
  52254. if (!this.transformedPosition) {
  52255. this.transformedPosition = BABYLON.Vector3.Zero();
  52256. }
  52257. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  52258. // In case the direction is present.
  52259. if (this.direction) {
  52260. if (!this.transformedDirection) {
  52261. this.transformedDirection = BABYLON.Vector3.Zero();
  52262. }
  52263. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  52264. }
  52265. return true;
  52266. }
  52267. return false;
  52268. };
  52269. /**
  52270. * Return the depth scale used for the shadow map.
  52271. * @returns the depth scale.
  52272. */
  52273. ShadowLight.prototype.getDepthScale = function () {
  52274. return 50.0;
  52275. };
  52276. /**
  52277. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  52278. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52279. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52280. */
  52281. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  52282. return this.transformedDirection ? this.transformedDirection : this.direction;
  52283. };
  52284. /**
  52285. * Returns the ShadowLight absolute position in the World.
  52286. * @returns the position vector in world space
  52287. */
  52288. ShadowLight.prototype.getAbsolutePosition = function () {
  52289. return this.transformedPosition ? this.transformedPosition : this.position;
  52290. };
  52291. /**
  52292. * Sets the ShadowLight direction toward the passed target.
  52293. * @param target The point tot target in local space
  52294. * @returns the updated ShadowLight direction
  52295. */
  52296. ShadowLight.prototype.setDirectionToTarget = function (target) {
  52297. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  52298. return this.direction;
  52299. };
  52300. /**
  52301. * Returns the light rotation in euler definition.
  52302. * @returns the x y z rotation in local space.
  52303. */
  52304. ShadowLight.prototype.getRotation = function () {
  52305. this.direction.normalize();
  52306. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  52307. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  52308. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  52309. };
  52310. /**
  52311. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  52312. * @returns true if a cube texture needs to be use
  52313. */
  52314. ShadowLight.prototype.needCube = function () {
  52315. return false;
  52316. };
  52317. /**
  52318. * Detects if the projection matrix requires to be recomputed this frame.
  52319. * @returns true if it requires to be recomputed otherwise, false.
  52320. */
  52321. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  52322. return this._needProjectionMatrixCompute;
  52323. };
  52324. /**
  52325. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  52326. */
  52327. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  52328. this._needProjectionMatrixCompute = true;
  52329. };
  52330. /** @hidden */
  52331. ShadowLight.prototype._initCache = function () {
  52332. _super.prototype._initCache.call(this);
  52333. this._cache.position = BABYLON.Vector3.Zero();
  52334. };
  52335. /** @hidden */
  52336. ShadowLight.prototype._isSynchronized = function () {
  52337. if (!this._cache.position.equals(this.position)) {
  52338. return false;
  52339. }
  52340. return true;
  52341. };
  52342. /**
  52343. * Computes the world matrix of the node
  52344. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52345. * @returns the world matrix
  52346. */
  52347. ShadowLight.prototype.computeWorldMatrix = function (force) {
  52348. if (!force && this.isSynchronized()) {
  52349. this._currentRenderId = this.getScene().getRenderId();
  52350. return this._worldMatrix;
  52351. }
  52352. this._updateCache();
  52353. this._cache.position.copyFrom(this.position);
  52354. if (!this._worldMatrix) {
  52355. this._worldMatrix = BABYLON.Matrix.Identity();
  52356. }
  52357. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  52358. if (this.parent && this.parent.getWorldMatrix) {
  52359. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  52360. this._markSyncedWithParent();
  52361. }
  52362. // Cache the determinant
  52363. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  52364. return this._worldMatrix;
  52365. };
  52366. /**
  52367. * Gets the minZ used for shadow according to both the scene and the light.
  52368. * @param activeCamera The camera we are returning the min for
  52369. * @returns the depth min z
  52370. */
  52371. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  52372. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  52373. };
  52374. /**
  52375. * Gets the maxZ used for shadow according to both the scene and the light.
  52376. * @param activeCamera The camera we are returning the max for
  52377. * @returns the depth max z
  52378. */
  52379. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  52380. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  52381. };
  52382. /**
  52383. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  52384. * @param matrix The materix to updated with the projection information
  52385. * @param viewMatrix The transform matrix of the light
  52386. * @param renderList The list of mesh to render in the map
  52387. * @returns The current light
  52388. */
  52389. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52390. if (this.customProjectionMatrixBuilder) {
  52391. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  52392. }
  52393. else {
  52394. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52395. }
  52396. return this;
  52397. };
  52398. __decorate([
  52399. BABYLON.serializeAsVector3()
  52400. ], ShadowLight.prototype, "position", null);
  52401. __decorate([
  52402. BABYLON.serializeAsVector3()
  52403. ], ShadowLight.prototype, "direction", null);
  52404. __decorate([
  52405. BABYLON.serialize()
  52406. ], ShadowLight.prototype, "shadowMinZ", null);
  52407. __decorate([
  52408. BABYLON.serialize()
  52409. ], ShadowLight.prototype, "shadowMaxZ", null);
  52410. return ShadowLight;
  52411. }(BABYLON.Light));
  52412. BABYLON.ShadowLight = ShadowLight;
  52413. })(BABYLON || (BABYLON = {}));
  52414. //# sourceMappingURL=babylon.shadowLight.js.map
  52415. var BABYLON;
  52416. (function (BABYLON) {
  52417. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  52418. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  52419. });
  52420. /**
  52421. * A point light is a light defined by an unique point in world space.
  52422. * The light is emitted in every direction from this point.
  52423. * A good example of a point light is a standard light bulb.
  52424. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52425. */
  52426. var PointLight = /** @class */ (function (_super) {
  52427. __extends(PointLight, _super);
  52428. /**
  52429. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  52430. * A PointLight emits the light in every direction.
  52431. * It can cast shadows.
  52432. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  52433. * ```javascript
  52434. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  52435. * ```
  52436. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52437. * @param name The light friendly name
  52438. * @param position The position of the point light in the scene
  52439. * @param scene The scene the lights belongs to
  52440. */
  52441. function PointLight(name, position, scene) {
  52442. var _this = _super.call(this, name, scene) || this;
  52443. _this._shadowAngle = Math.PI / 2;
  52444. _this.position = position;
  52445. return _this;
  52446. }
  52447. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  52448. /**
  52449. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52450. * This specifies what angle the shadow will use to be created.
  52451. *
  52452. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52453. */
  52454. get: function () {
  52455. return this._shadowAngle;
  52456. },
  52457. /**
  52458. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52459. * This specifies what angle the shadow will use to be created.
  52460. *
  52461. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52462. */
  52463. set: function (value) {
  52464. this._shadowAngle = value;
  52465. this.forceProjectionMatrixCompute();
  52466. },
  52467. enumerable: true,
  52468. configurable: true
  52469. });
  52470. Object.defineProperty(PointLight.prototype, "direction", {
  52471. /**
  52472. * Gets the direction if it has been set.
  52473. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52474. */
  52475. get: function () {
  52476. return this._direction;
  52477. },
  52478. /**
  52479. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52480. */
  52481. set: function (value) {
  52482. var previousNeedCube = this.needCube();
  52483. this._direction = value;
  52484. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  52485. this._shadowGenerator.recreateShadowMap();
  52486. }
  52487. },
  52488. enumerable: true,
  52489. configurable: true
  52490. });
  52491. /**
  52492. * Returns the string "PointLight"
  52493. * @returns the class name
  52494. */
  52495. PointLight.prototype.getClassName = function () {
  52496. return "PointLight";
  52497. };
  52498. /**
  52499. * Returns the integer 0.
  52500. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52501. */
  52502. PointLight.prototype.getTypeID = function () {
  52503. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  52504. };
  52505. /**
  52506. * Specifies wether or not the shadowmap should be a cube texture.
  52507. * @returns true if the shadowmap needs to be a cube texture.
  52508. */
  52509. PointLight.prototype.needCube = function () {
  52510. return !this.direction;
  52511. };
  52512. /**
  52513. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  52514. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52515. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52516. */
  52517. PointLight.prototype.getShadowDirection = function (faceIndex) {
  52518. if (this.direction) {
  52519. return _super.prototype.getShadowDirection.call(this, faceIndex);
  52520. }
  52521. else {
  52522. switch (faceIndex) {
  52523. case 0:
  52524. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  52525. case 1:
  52526. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  52527. case 2:
  52528. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  52529. case 3:
  52530. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  52531. case 4:
  52532. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  52533. case 5:
  52534. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  52535. }
  52536. }
  52537. return BABYLON.Vector3.Zero();
  52538. };
  52539. /**
  52540. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  52541. * - fov = PI / 2
  52542. * - aspect ratio : 1.0
  52543. * - z-near and far equal to the active camera minZ and maxZ.
  52544. * Returns the PointLight.
  52545. */
  52546. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52547. var activeCamera = this.getScene().activeCamera;
  52548. if (!activeCamera) {
  52549. return;
  52550. }
  52551. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52552. };
  52553. PointLight.prototype._buildUniformLayout = function () {
  52554. this._uniformBuffer.addUniform("vLightData", 4);
  52555. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52556. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52557. this._uniformBuffer.addUniform("vLightFalloff", 4);
  52558. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52559. this._uniformBuffer.addUniform("depthValues", 2);
  52560. this._uniformBuffer.create();
  52561. };
  52562. /**
  52563. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  52564. * @param effect The effect to update
  52565. * @param lightIndex The index of the light in the effect to update
  52566. * @returns The point light
  52567. */
  52568. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  52569. if (this.computeTransformedInformation()) {
  52570. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  52571. }
  52572. else {
  52573. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  52574. }
  52575. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  52576. return this;
  52577. };
  52578. /**
  52579. * Prepares the list of defines specific to the light type.
  52580. * @param defines the list of defines
  52581. * @param lightIndex defines the index of the light for the effect
  52582. */
  52583. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52584. defines["POINTLIGHT" + lightIndex] = true;
  52585. };
  52586. __decorate([
  52587. BABYLON.serialize()
  52588. ], PointLight.prototype, "shadowAngle", null);
  52589. return PointLight;
  52590. }(BABYLON.ShadowLight));
  52591. BABYLON.PointLight = PointLight;
  52592. })(BABYLON || (BABYLON = {}));
  52593. //# sourceMappingURL=babylon.pointLight.js.map
  52594. var BABYLON;
  52595. (function (BABYLON) {
  52596. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  52597. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  52598. });
  52599. /**
  52600. * A directional light is defined by a direction (what a surprise!).
  52601. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  52602. * 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.
  52603. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52604. */
  52605. var DirectionalLight = /** @class */ (function (_super) {
  52606. __extends(DirectionalLight, _super);
  52607. /**
  52608. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  52609. * The directional light is emitted from everywhere in the given direction.
  52610. * It can cast shadows.
  52611. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52612. * @param name The friendly name of the light
  52613. * @param direction The direction of the light
  52614. * @param scene The scene the light belongs to
  52615. */
  52616. function DirectionalLight(name, direction, scene) {
  52617. var _this = _super.call(this, name, scene) || this;
  52618. _this._shadowFrustumSize = 0;
  52619. _this._shadowOrthoScale = 0.1;
  52620. /**
  52621. * Automatically compute the projection matrix to best fit (including all the casters)
  52622. * on each frame.
  52623. */
  52624. _this.autoUpdateExtends = true;
  52625. // Cache
  52626. _this._orthoLeft = Number.MAX_VALUE;
  52627. _this._orthoRight = Number.MIN_VALUE;
  52628. _this._orthoTop = Number.MIN_VALUE;
  52629. _this._orthoBottom = Number.MAX_VALUE;
  52630. _this.position = direction.scale(-1.0);
  52631. _this.direction = direction;
  52632. return _this;
  52633. }
  52634. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  52635. /**
  52636. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  52637. */
  52638. get: function () {
  52639. return this._shadowFrustumSize;
  52640. },
  52641. /**
  52642. * Specifies a fix frustum size for the shadow generation.
  52643. */
  52644. set: function (value) {
  52645. this._shadowFrustumSize = value;
  52646. this.forceProjectionMatrixCompute();
  52647. },
  52648. enumerable: true,
  52649. configurable: true
  52650. });
  52651. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  52652. /**
  52653. * Gets the shadow projection scale against the optimal computed one.
  52654. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52655. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52656. */
  52657. get: function () {
  52658. return this._shadowOrthoScale;
  52659. },
  52660. /**
  52661. * Sets the shadow projection scale against the optimal computed one.
  52662. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52663. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52664. */
  52665. set: function (value) {
  52666. this._shadowOrthoScale = value;
  52667. this.forceProjectionMatrixCompute();
  52668. },
  52669. enumerable: true,
  52670. configurable: true
  52671. });
  52672. /**
  52673. * Returns the string "DirectionalLight".
  52674. * @return The class name
  52675. */
  52676. DirectionalLight.prototype.getClassName = function () {
  52677. return "DirectionalLight";
  52678. };
  52679. /**
  52680. * Returns the integer 1.
  52681. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52682. */
  52683. DirectionalLight.prototype.getTypeID = function () {
  52684. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  52685. };
  52686. /**
  52687. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  52688. * Returns the DirectionalLight Shadow projection matrix.
  52689. */
  52690. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52691. if (this.shadowFrustumSize > 0) {
  52692. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  52693. }
  52694. else {
  52695. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52696. }
  52697. };
  52698. /**
  52699. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  52700. * Returns the DirectionalLight Shadow projection matrix.
  52701. */
  52702. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  52703. var activeCamera = this.getScene().activeCamera;
  52704. if (!activeCamera) {
  52705. return;
  52706. }
  52707. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  52708. };
  52709. /**
  52710. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  52711. * Returns the DirectionalLight Shadow projection matrix.
  52712. */
  52713. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52714. var activeCamera = this.getScene().activeCamera;
  52715. if (!activeCamera) {
  52716. return;
  52717. }
  52718. // Check extends
  52719. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  52720. var tempVector3 = BABYLON.Vector3.Zero();
  52721. this._orthoLeft = Number.MAX_VALUE;
  52722. this._orthoRight = Number.MIN_VALUE;
  52723. this._orthoTop = Number.MIN_VALUE;
  52724. this._orthoBottom = Number.MAX_VALUE;
  52725. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  52726. var mesh = renderList[meshIndex];
  52727. if (!mesh) {
  52728. continue;
  52729. }
  52730. var boundingInfo = mesh.getBoundingInfo();
  52731. var boundingBox = boundingInfo.boundingBox;
  52732. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  52733. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  52734. if (tempVector3.x < this._orthoLeft) {
  52735. this._orthoLeft = tempVector3.x;
  52736. }
  52737. if (tempVector3.y < this._orthoBottom) {
  52738. this._orthoBottom = tempVector3.y;
  52739. }
  52740. if (tempVector3.x > this._orthoRight) {
  52741. this._orthoRight = tempVector3.x;
  52742. }
  52743. if (tempVector3.y > this._orthoTop) {
  52744. this._orthoTop = tempVector3.y;
  52745. }
  52746. }
  52747. }
  52748. }
  52749. var xOffset = this._orthoRight - this._orthoLeft;
  52750. var yOffset = this._orthoTop - this._orthoBottom;
  52751. 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);
  52752. };
  52753. DirectionalLight.prototype._buildUniformLayout = function () {
  52754. this._uniformBuffer.addUniform("vLightData", 4);
  52755. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52756. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52757. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52758. this._uniformBuffer.addUniform("depthValues", 2);
  52759. this._uniformBuffer.create();
  52760. };
  52761. /**
  52762. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  52763. * @param effect The effect to update
  52764. * @param lightIndex The index of the light in the effect to update
  52765. * @returns The directional light
  52766. */
  52767. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  52768. if (this.computeTransformedInformation()) {
  52769. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  52770. return this;
  52771. }
  52772. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  52773. return this;
  52774. };
  52775. /**
  52776. * Gets the minZ used for shadow according to both the scene and the light.
  52777. *
  52778. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52779. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52780. * @param activeCamera The camera we are returning the min for
  52781. * @returns the depth min z
  52782. */
  52783. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  52784. return 1;
  52785. };
  52786. /**
  52787. * Gets the maxZ used for shadow according to both the scene and the light.
  52788. *
  52789. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52790. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52791. * @param activeCamera The camera we are returning the max for
  52792. * @returns the depth max z
  52793. */
  52794. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  52795. return 1;
  52796. };
  52797. /**
  52798. * Prepares the list of defines specific to the light type.
  52799. * @param defines the list of defines
  52800. * @param lightIndex defines the index of the light for the effect
  52801. */
  52802. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52803. defines["DIRLIGHT" + lightIndex] = true;
  52804. };
  52805. __decorate([
  52806. BABYLON.serialize()
  52807. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  52808. __decorate([
  52809. BABYLON.serialize()
  52810. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  52811. __decorate([
  52812. BABYLON.serialize()
  52813. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  52814. return DirectionalLight;
  52815. }(BABYLON.ShadowLight));
  52816. BABYLON.DirectionalLight = DirectionalLight;
  52817. })(BABYLON || (BABYLON = {}));
  52818. //# sourceMappingURL=babylon.directionalLight.js.map
  52819. var BABYLON;
  52820. (function (BABYLON) {
  52821. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  52822. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  52823. });
  52824. /**
  52825. * A spot light is defined by a position, a direction, an angle, and an exponent.
  52826. * These values define a cone of light starting from the position, emitting toward the direction.
  52827. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  52828. * and the exponent defines the speed of the decay of the light with distance (reach).
  52829. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52830. */
  52831. var SpotLight = /** @class */ (function (_super) {
  52832. __extends(SpotLight, _super);
  52833. /**
  52834. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  52835. * It can cast shadows.
  52836. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52837. * @param name The light friendly name
  52838. * @param position The position of the spot light in the scene
  52839. * @param direction The direction of the light in the scene
  52840. * @param angle The cone angle of the light in Radians
  52841. * @param exponent The light decay speed with the distance from the emission spot
  52842. * @param scene The scene the lights belongs to
  52843. */
  52844. function SpotLight(name, position, direction, angle, exponent, scene) {
  52845. var _this = _super.call(this, name, scene) || this;
  52846. _this._innerAngle = 0;
  52847. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  52848. _this._projectionTextureLightNear = 1e-6;
  52849. _this._projectionTextureLightFar = 1000.0;
  52850. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  52851. _this._projectionTextureViewLightDirty = true;
  52852. _this._projectionTextureProjectionLightDirty = true;
  52853. _this._projectionTextureDirty = true;
  52854. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  52855. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  52856. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  52857. _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);
  52858. _this.position = position;
  52859. _this.direction = direction;
  52860. _this.angle = angle;
  52861. _this.exponent = exponent;
  52862. return _this;
  52863. }
  52864. Object.defineProperty(SpotLight.prototype, "angle", {
  52865. /**
  52866. * Gets the cone angle of the spot light in Radians.
  52867. */
  52868. get: function () {
  52869. return this._angle;
  52870. },
  52871. /**
  52872. * Sets the cone angle of the spot light in Radians.
  52873. */
  52874. set: function (value) {
  52875. this._angle = value;
  52876. this._cosHalfAngle = Math.cos(value * 0.5);
  52877. this._projectionTextureProjectionLightDirty = true;
  52878. this.forceProjectionMatrixCompute();
  52879. this._computeAngleValues();
  52880. },
  52881. enumerable: true,
  52882. configurable: true
  52883. });
  52884. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  52885. /**
  52886. * Only used in gltf falloff mode, this defines the angle where
  52887. * the directional falloff will start before cutting at angle which could be seen
  52888. * as outer angle.
  52889. */
  52890. get: function () {
  52891. return this._innerAngle;
  52892. },
  52893. /**
  52894. * Only used in gltf falloff mode, this defines the angle where
  52895. * the directional falloff will start before cutting at angle which could be seen
  52896. * as outer angle.
  52897. */
  52898. set: function (value) {
  52899. this._innerAngle = value;
  52900. this._computeAngleValues();
  52901. },
  52902. enumerable: true,
  52903. configurable: true
  52904. });
  52905. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  52906. /**
  52907. * Allows scaling the angle of the light for shadow generation only.
  52908. */
  52909. get: function () {
  52910. return this._shadowAngleScale;
  52911. },
  52912. /**
  52913. * Allows scaling the angle of the light for shadow generation only.
  52914. */
  52915. set: function (value) {
  52916. this._shadowAngleScale = value;
  52917. this.forceProjectionMatrixCompute();
  52918. },
  52919. enumerable: true,
  52920. configurable: true
  52921. });
  52922. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  52923. /**
  52924. * Allows reading the projecton texture
  52925. */
  52926. get: function () {
  52927. return this._projectionTextureMatrix;
  52928. },
  52929. enumerable: true,
  52930. configurable: true
  52931. });
  52932. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  52933. /**
  52934. * Gets the near clip of the Spotlight for texture projection.
  52935. */
  52936. get: function () {
  52937. return this._projectionTextureLightNear;
  52938. },
  52939. /**
  52940. * Sets the near clip of the Spotlight for texture projection.
  52941. */
  52942. set: function (value) {
  52943. this._projectionTextureLightNear = value;
  52944. this._projectionTextureProjectionLightDirty = true;
  52945. },
  52946. enumerable: true,
  52947. configurable: true
  52948. });
  52949. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  52950. /**
  52951. * Gets the far clip of the Spotlight for texture projection.
  52952. */
  52953. get: function () {
  52954. return this._projectionTextureLightFar;
  52955. },
  52956. /**
  52957. * Sets the far clip of the Spotlight for texture projection.
  52958. */
  52959. set: function (value) {
  52960. this._projectionTextureLightFar = value;
  52961. this._projectionTextureProjectionLightDirty = true;
  52962. },
  52963. enumerable: true,
  52964. configurable: true
  52965. });
  52966. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  52967. /**
  52968. * Gets the Up vector of the Spotlight for texture projection.
  52969. */
  52970. get: function () {
  52971. return this._projectionTextureUpDirection;
  52972. },
  52973. /**
  52974. * Sets the Up vector of the Spotlight for texture projection.
  52975. */
  52976. set: function (value) {
  52977. this._projectionTextureUpDirection = value;
  52978. this._projectionTextureProjectionLightDirty = true;
  52979. },
  52980. enumerable: true,
  52981. configurable: true
  52982. });
  52983. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  52984. /**
  52985. * Gets the projection texture of the light.
  52986. */
  52987. get: function () {
  52988. return this._projectionTexture;
  52989. },
  52990. /**
  52991. * Sets the projection texture of the light.
  52992. */
  52993. set: function (value) {
  52994. this._projectionTexture = value;
  52995. this._projectionTextureDirty = true;
  52996. },
  52997. enumerable: true,
  52998. configurable: true
  52999. });
  53000. /**
  53001. * Returns the string "SpotLight".
  53002. * @returns the class name
  53003. */
  53004. SpotLight.prototype.getClassName = function () {
  53005. return "SpotLight";
  53006. };
  53007. /**
  53008. * Returns the integer 2.
  53009. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  53010. */
  53011. SpotLight.prototype.getTypeID = function () {
  53012. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  53013. };
  53014. /**
  53015. * Overrides the direction setter to recompute the projection texture view light Matrix.
  53016. */
  53017. SpotLight.prototype._setDirection = function (value) {
  53018. _super.prototype._setDirection.call(this, value);
  53019. this._projectionTextureViewLightDirty = true;
  53020. };
  53021. /**
  53022. * Overrides the position setter to recompute the projection texture view light Matrix.
  53023. */
  53024. SpotLight.prototype._setPosition = function (value) {
  53025. _super.prototype._setPosition.call(this, value);
  53026. this._projectionTextureViewLightDirty = true;
  53027. };
  53028. /**
  53029. * 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.
  53030. * Returns the SpotLight.
  53031. */
  53032. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53033. var activeCamera = this.getScene().activeCamera;
  53034. if (!activeCamera) {
  53035. return;
  53036. }
  53037. this._shadowAngleScale = this._shadowAngleScale || 1;
  53038. var angle = this._shadowAngleScale * this._angle;
  53039. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  53040. };
  53041. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  53042. this._projectionTextureViewLightDirty = false;
  53043. this._projectionTextureDirty = true;
  53044. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  53045. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  53046. };
  53047. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  53048. this._projectionTextureProjectionLightDirty = false;
  53049. this._projectionTextureDirty = true;
  53050. var light_far = this.projectionTextureLightFar;
  53051. var light_near = this.projectionTextureLightNear;
  53052. var P = light_far / (light_far - light_near);
  53053. var Q = -P * light_near;
  53054. var S = 1.0 / Math.tan(this._angle / 2.0);
  53055. var A = 1.0;
  53056. 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);
  53057. };
  53058. /**
  53059. * Main function for light texture projection matrix computing.
  53060. */
  53061. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  53062. this._projectionTextureDirty = false;
  53063. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  53064. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  53065. };
  53066. SpotLight.prototype._buildUniformLayout = function () {
  53067. this._uniformBuffer.addUniform("vLightData", 4);
  53068. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53069. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53070. this._uniformBuffer.addUniform("vLightDirection", 3);
  53071. this._uniformBuffer.addUniform("vLightFalloff", 4);
  53072. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53073. this._uniformBuffer.addUniform("depthValues", 2);
  53074. this._uniformBuffer.create();
  53075. };
  53076. SpotLight.prototype._computeAngleValues = function () {
  53077. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  53078. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  53079. };
  53080. /**
  53081. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  53082. * @param effect The effect to update
  53083. * @param lightIndex The index of the light in the effect to update
  53084. * @returns The spot light
  53085. */
  53086. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  53087. var normalizeDirection;
  53088. if (this.computeTransformedInformation()) {
  53089. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  53090. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  53091. }
  53092. else {
  53093. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  53094. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  53095. }
  53096. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  53097. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  53098. if (this.projectionTexture && this.projectionTexture.isReady()) {
  53099. if (this._projectionTextureViewLightDirty) {
  53100. this._computeProjectionTextureViewLightMatrix();
  53101. }
  53102. if (this._projectionTextureProjectionLightDirty) {
  53103. this._computeProjectionTextureProjectionLightMatrix();
  53104. }
  53105. if (this._projectionTextureDirty) {
  53106. this._computeProjectionTextureMatrix();
  53107. }
  53108. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  53109. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  53110. }
  53111. return this;
  53112. };
  53113. /**
  53114. * Disposes the light and the associated resources.
  53115. */
  53116. SpotLight.prototype.dispose = function () {
  53117. _super.prototype.dispose.call(this);
  53118. if (this._projectionTexture) {
  53119. this._projectionTexture.dispose();
  53120. }
  53121. };
  53122. /**
  53123. * Prepares the list of defines specific to the light type.
  53124. * @param defines the list of defines
  53125. * @param lightIndex defines the index of the light for the effect
  53126. */
  53127. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53128. defines["SPOTLIGHT" + lightIndex] = true;
  53129. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  53130. };
  53131. __decorate([
  53132. BABYLON.serialize()
  53133. ], SpotLight.prototype, "angle", null);
  53134. __decorate([
  53135. BABYLON.serialize()
  53136. ], SpotLight.prototype, "innerAngle", null);
  53137. __decorate([
  53138. BABYLON.serialize()
  53139. ], SpotLight.prototype, "shadowAngleScale", null);
  53140. __decorate([
  53141. BABYLON.serialize()
  53142. ], SpotLight.prototype, "exponent", void 0);
  53143. __decorate([
  53144. BABYLON.serialize()
  53145. ], SpotLight.prototype, "projectionTextureLightNear", null);
  53146. __decorate([
  53147. BABYLON.serialize()
  53148. ], SpotLight.prototype, "projectionTextureLightFar", null);
  53149. __decorate([
  53150. BABYLON.serialize()
  53151. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  53152. __decorate([
  53153. BABYLON.serializeAsTexture("projectedLightTexture")
  53154. ], SpotLight.prototype, "_projectionTexture", void 0);
  53155. return SpotLight;
  53156. }(BABYLON.ShadowLight));
  53157. BABYLON.SpotLight = SpotLight;
  53158. })(BABYLON || (BABYLON = {}));
  53159. //# sourceMappingURL=babylon.spotLight.js.map
  53160. var BABYLON;
  53161. (function (BABYLON) {
  53162. /**
  53163. * Class used to override all child animations of a given target
  53164. */
  53165. var AnimationPropertiesOverride = /** @class */ (function () {
  53166. function AnimationPropertiesOverride() {
  53167. /**
  53168. * Gets or sets a value indicating if animation blending must be used
  53169. */
  53170. this.enableBlending = false;
  53171. /**
  53172. * Gets or sets the blending speed to use when enableBlending is true
  53173. */
  53174. this.blendingSpeed = 0.01;
  53175. /**
  53176. * Gets or sets the default loop mode to use
  53177. */
  53178. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  53179. }
  53180. return AnimationPropertiesOverride;
  53181. }());
  53182. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  53183. })(BABYLON || (BABYLON = {}));
  53184. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  53185. var BABYLON;
  53186. (function (BABYLON) {
  53187. /**
  53188. * Represents the range of an animation
  53189. */
  53190. var AnimationRange = /** @class */ (function () {
  53191. /**
  53192. * Initializes the range of an animation
  53193. * @param name The name of the animation range
  53194. * @param from The starting frame of the animation
  53195. * @param to The ending frame of the animation
  53196. */
  53197. function AnimationRange(
  53198. /**The name of the animation range**/
  53199. name,
  53200. /**The starting frame of the animation */
  53201. from,
  53202. /**The ending frame of the animation*/
  53203. to) {
  53204. this.name = name;
  53205. this.from = from;
  53206. this.to = to;
  53207. }
  53208. /**
  53209. * Makes a copy of the animation range
  53210. * @returns A copy of the animation range
  53211. */
  53212. AnimationRange.prototype.clone = function () {
  53213. return new AnimationRange(this.name, this.from, this.to);
  53214. };
  53215. return AnimationRange;
  53216. }());
  53217. BABYLON.AnimationRange = AnimationRange;
  53218. /**
  53219. * Composed of a frame, and an action function
  53220. */
  53221. var AnimationEvent = /** @class */ (function () {
  53222. /**
  53223. * Initializes the animation event
  53224. * @param frame The frame for which the event is triggered
  53225. * @param action The event to perform when triggered
  53226. * @param onlyOnce Specifies if the event should be triggered only once
  53227. */
  53228. function AnimationEvent(
  53229. /** The frame for which the event is triggered **/
  53230. frame,
  53231. /** The event to perform when triggered **/
  53232. action,
  53233. /** Specifies if the event should be triggered only once**/
  53234. onlyOnce) {
  53235. this.frame = frame;
  53236. this.action = action;
  53237. this.onlyOnce = onlyOnce;
  53238. /**
  53239. * Specifies if the animation event is done
  53240. */
  53241. this.isDone = false;
  53242. }
  53243. /** @hidden */
  53244. AnimationEvent.prototype._clone = function () {
  53245. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  53246. };
  53247. return AnimationEvent;
  53248. }());
  53249. BABYLON.AnimationEvent = AnimationEvent;
  53250. /**
  53251. * A cursor which tracks a point on a path
  53252. */
  53253. var PathCursor = /** @class */ (function () {
  53254. /**
  53255. * Initializes the path cursor
  53256. * @param path The path to track
  53257. */
  53258. function PathCursor(path) {
  53259. this.path = path;
  53260. /**
  53261. * Stores path cursor callbacks for when an onchange event is triggered
  53262. */
  53263. this._onchange = new Array();
  53264. /**
  53265. * The value of the path cursor
  53266. */
  53267. this.value = 0;
  53268. /**
  53269. * The animation array of the path cursor
  53270. */
  53271. this.animations = new Array();
  53272. }
  53273. /**
  53274. * Gets the cursor point on the path
  53275. * @returns A point on the path cursor at the cursor location
  53276. */
  53277. PathCursor.prototype.getPoint = function () {
  53278. var point = this.path.getPointAtLengthPosition(this.value);
  53279. return new BABYLON.Vector3(point.x, 0, point.y);
  53280. };
  53281. /**
  53282. * Moves the cursor ahead by the step amount
  53283. * @param step The amount to move the cursor forward
  53284. * @returns This path cursor
  53285. */
  53286. PathCursor.prototype.moveAhead = function (step) {
  53287. if (step === void 0) { step = 0.002; }
  53288. this.move(step);
  53289. return this;
  53290. };
  53291. /**
  53292. * Moves the cursor behind by the step amount
  53293. * @param step The amount to move the cursor back
  53294. * @returns This path cursor
  53295. */
  53296. PathCursor.prototype.moveBack = function (step) {
  53297. if (step === void 0) { step = 0.002; }
  53298. this.move(-step);
  53299. return this;
  53300. };
  53301. /**
  53302. * Moves the cursor by the step amount
  53303. * If the step amount is greater than one, an exception is thrown
  53304. * @param step The amount to move the cursor
  53305. * @returns This path cursor
  53306. */
  53307. PathCursor.prototype.move = function (step) {
  53308. if (Math.abs(step) > 1) {
  53309. throw "step size should be less than 1.";
  53310. }
  53311. this.value += step;
  53312. this.ensureLimits();
  53313. this.raiseOnChange();
  53314. return this;
  53315. };
  53316. /**
  53317. * Ensures that the value is limited between zero and one
  53318. * @returns This path cursor
  53319. */
  53320. PathCursor.prototype.ensureLimits = function () {
  53321. while (this.value > 1) {
  53322. this.value -= 1;
  53323. }
  53324. while (this.value < 0) {
  53325. this.value += 1;
  53326. }
  53327. return this;
  53328. };
  53329. /**
  53330. * Runs onchange callbacks on change (used by the animation engine)
  53331. * @returns This path cursor
  53332. */
  53333. PathCursor.prototype.raiseOnChange = function () {
  53334. var _this = this;
  53335. this._onchange.forEach(function (f) { return f(_this); });
  53336. return this;
  53337. };
  53338. /**
  53339. * Executes a function on change
  53340. * @param f A path cursor onchange callback
  53341. * @returns This path cursor
  53342. */
  53343. PathCursor.prototype.onchange = function (f) {
  53344. this._onchange.push(f);
  53345. return this;
  53346. };
  53347. return PathCursor;
  53348. }());
  53349. BABYLON.PathCursor = PathCursor;
  53350. /**
  53351. * Enum for the animation key frame interpolation type
  53352. */
  53353. var AnimationKeyInterpolation;
  53354. (function (AnimationKeyInterpolation) {
  53355. /**
  53356. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  53357. */
  53358. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  53359. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  53360. /**
  53361. * Class used to store any kind of animation
  53362. */
  53363. var Animation = /** @class */ (function () {
  53364. /**
  53365. * Initializes the animation
  53366. * @param name Name of the animation
  53367. * @param targetProperty Property to animate
  53368. * @param framePerSecond The frames per second of the animation
  53369. * @param dataType The data type of the animation
  53370. * @param loopMode The loop mode of the animation
  53371. * @param enableBlendings Specifies if blending should be enabled
  53372. */
  53373. function Animation(
  53374. /**Name of the animation */
  53375. name,
  53376. /**Property to animate */
  53377. targetProperty,
  53378. /**The frames per second of the animation */
  53379. framePerSecond,
  53380. /**The data type of the animation */
  53381. dataType,
  53382. /**The loop mode of the animation */
  53383. loopMode,
  53384. /**Specifies if blending should be enabled */
  53385. enableBlending) {
  53386. this.name = name;
  53387. this.targetProperty = targetProperty;
  53388. this.framePerSecond = framePerSecond;
  53389. this.dataType = dataType;
  53390. this.loopMode = loopMode;
  53391. this.enableBlending = enableBlending;
  53392. /**
  53393. * @hidden Internal use only
  53394. */
  53395. this._runtimeAnimations = new Array();
  53396. /**
  53397. * The set of event that will be linked to this animation
  53398. */
  53399. this._events = new Array();
  53400. /**
  53401. * Stores the blending speed of the animation
  53402. */
  53403. this.blendingSpeed = 0.01;
  53404. /**
  53405. * Stores the animation ranges for the animation
  53406. */
  53407. this._ranges = {};
  53408. this.targetPropertyPath = targetProperty.split(".");
  53409. this.dataType = dataType;
  53410. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  53411. }
  53412. /**
  53413. * @hidden Internal use
  53414. */
  53415. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  53416. var dataType = undefined;
  53417. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  53418. dataType = Animation.ANIMATIONTYPE_FLOAT;
  53419. }
  53420. else if (from instanceof BABYLON.Quaternion) {
  53421. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  53422. }
  53423. else if (from instanceof BABYLON.Vector3) {
  53424. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  53425. }
  53426. else if (from instanceof BABYLON.Vector2) {
  53427. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  53428. }
  53429. else if (from instanceof BABYLON.Color3) {
  53430. dataType = Animation.ANIMATIONTYPE_COLOR3;
  53431. }
  53432. else if (from instanceof BABYLON.Size) {
  53433. dataType = Animation.ANIMATIONTYPE_SIZE;
  53434. }
  53435. if (dataType == undefined) {
  53436. return null;
  53437. }
  53438. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  53439. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  53440. animation.setKeys(keys);
  53441. if (easingFunction !== undefined) {
  53442. animation.setEasingFunction(easingFunction);
  53443. }
  53444. return animation;
  53445. };
  53446. /**
  53447. * Sets up an animation
  53448. * @param property The property to animate
  53449. * @param animationType The animation type to apply
  53450. * @param framePerSecond The frames per second of the animation
  53451. * @param easingFunction The easing function used in the animation
  53452. * @returns The created animation
  53453. */
  53454. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  53455. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  53456. animation.setEasingFunction(easingFunction);
  53457. return animation;
  53458. };
  53459. /**
  53460. * Create and start an animation on a node
  53461. * @param name defines the name of the global animation that will be run on all nodes
  53462. * @param node defines the root node where the animation will take place
  53463. * @param targetProperty defines property to animate
  53464. * @param framePerSecond defines the number of frame per second yo use
  53465. * @param totalFrame defines the number of frames in total
  53466. * @param from defines the initial value
  53467. * @param to defines the final value
  53468. * @param loopMode defines which loop mode you want to use (off by default)
  53469. * @param easingFunction defines the easing function to use (linear by default)
  53470. * @param onAnimationEnd defines the callback to call when animation end
  53471. * @returns the animatable created for this animation
  53472. */
  53473. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53474. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53475. if (!animation) {
  53476. return null;
  53477. }
  53478. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53479. };
  53480. /**
  53481. * Create and start an animation on a node and its descendants
  53482. * @param name defines the name of the global animation that will be run on all nodes
  53483. * @param node defines the root node where the animation will take place
  53484. * @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
  53485. * @param targetProperty defines property to animate
  53486. * @param framePerSecond defines the number of frame per second to use
  53487. * @param totalFrame defines the number of frames in total
  53488. * @param from defines the initial value
  53489. * @param to defines the final value
  53490. * @param loopMode defines which loop mode you want to use (off by default)
  53491. * @param easingFunction defines the easing function to use (linear by default)
  53492. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  53493. * @returns the list of animatables created for all nodes
  53494. * @example https://www.babylonjs-playground.com/#MH0VLI
  53495. */
  53496. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53497. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53498. if (!animation) {
  53499. return null;
  53500. }
  53501. var scene = node.getScene();
  53502. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53503. };
  53504. /**
  53505. * Creates a new animation, merges it with the existing animations and starts it
  53506. * @param name Name of the animation
  53507. * @param node Node which contains the scene that begins the animations
  53508. * @param targetProperty Specifies which property to animate
  53509. * @param framePerSecond The frames per second of the animation
  53510. * @param totalFrame The total number of frames
  53511. * @param from The frame at the beginning of the animation
  53512. * @param to The frame at the end of the animation
  53513. * @param loopMode Specifies the loop mode of the animation
  53514. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  53515. * @param onAnimationEnd Callback to run once the animation is complete
  53516. * @returns Nullable animation
  53517. */
  53518. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53519. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53520. if (!animation) {
  53521. return null;
  53522. }
  53523. node.animations.push(animation);
  53524. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53525. };
  53526. /**
  53527. * Transition property of an host to the target Value
  53528. * @param property The property to transition
  53529. * @param targetValue The target Value of the property
  53530. * @param host The object where the property to animate belongs
  53531. * @param scene Scene used to run the animation
  53532. * @param frameRate Framerate (in frame/s) to use
  53533. * @param transition The transition type we want to use
  53534. * @param duration The duration of the animation, in milliseconds
  53535. * @param onAnimationEnd Callback trigger at the end of the animation
  53536. * @returns Nullable animation
  53537. */
  53538. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  53539. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  53540. if (duration <= 0) {
  53541. host[property] = targetValue;
  53542. if (onAnimationEnd) {
  53543. onAnimationEnd();
  53544. }
  53545. return null;
  53546. }
  53547. var endFrame = frameRate * (duration / 1000);
  53548. transition.setKeys([{
  53549. frame: 0,
  53550. value: host[property].clone ? host[property].clone() : host[property]
  53551. },
  53552. {
  53553. frame: endFrame,
  53554. value: targetValue
  53555. }]);
  53556. if (!host.animations) {
  53557. host.animations = [];
  53558. }
  53559. host.animations.push(transition);
  53560. var animation = scene.beginAnimation(host, 0, endFrame, false);
  53561. animation.onAnimationEnd = onAnimationEnd;
  53562. return animation;
  53563. };
  53564. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  53565. /**
  53566. * Return the array of runtime animations currently using this animation
  53567. */
  53568. get: function () {
  53569. return this._runtimeAnimations;
  53570. },
  53571. enumerable: true,
  53572. configurable: true
  53573. });
  53574. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  53575. /**
  53576. * Specifies if any of the runtime animations are currently running
  53577. */
  53578. get: function () {
  53579. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  53580. var runtimeAnimation = _a[_i];
  53581. if (!runtimeAnimation.isStopped) {
  53582. return true;
  53583. }
  53584. }
  53585. return false;
  53586. },
  53587. enumerable: true,
  53588. configurable: true
  53589. });
  53590. // Methods
  53591. /**
  53592. * Converts the animation to a string
  53593. * @param fullDetails support for multiple levels of logging within scene loading
  53594. * @returns String form of the animation
  53595. */
  53596. Animation.prototype.toString = function (fullDetails) {
  53597. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  53598. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  53599. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  53600. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53601. if (fullDetails) {
  53602. ret += ", Ranges: {";
  53603. var first = true;
  53604. for (var name in this._ranges) {
  53605. if (first) {
  53606. ret += ", ";
  53607. first = false;
  53608. }
  53609. ret += name;
  53610. }
  53611. ret += "}";
  53612. }
  53613. return ret;
  53614. };
  53615. /**
  53616. * Add an event to this animation
  53617. * @param event Event to add
  53618. */
  53619. Animation.prototype.addEvent = function (event) {
  53620. this._events.push(event);
  53621. };
  53622. /**
  53623. * Remove all events found at the given frame
  53624. * @param frame The frame to remove events from
  53625. */
  53626. Animation.prototype.removeEvents = function (frame) {
  53627. for (var index = 0; index < this._events.length; index++) {
  53628. if (this._events[index].frame === frame) {
  53629. this._events.splice(index, 1);
  53630. index--;
  53631. }
  53632. }
  53633. };
  53634. /**
  53635. * Retrieves all the events from the animation
  53636. * @returns Events from the animation
  53637. */
  53638. Animation.prototype.getEvents = function () {
  53639. return this._events;
  53640. };
  53641. /**
  53642. * Creates an animation range
  53643. * @param name Name of the animation range
  53644. * @param from Starting frame of the animation range
  53645. * @param to Ending frame of the animation
  53646. */
  53647. Animation.prototype.createRange = function (name, from, to) {
  53648. // check name not already in use; could happen for bones after serialized
  53649. if (!this._ranges[name]) {
  53650. this._ranges[name] = new AnimationRange(name, from, to);
  53651. }
  53652. };
  53653. /**
  53654. * Deletes an animation range by name
  53655. * @param name Name of the animation range to delete
  53656. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  53657. */
  53658. Animation.prototype.deleteRange = function (name, deleteFrames) {
  53659. if (deleteFrames === void 0) { deleteFrames = true; }
  53660. var range = this._ranges[name];
  53661. if (!range) {
  53662. return;
  53663. }
  53664. if (deleteFrames) {
  53665. var from = range.from;
  53666. var to = range.to;
  53667. // this loop MUST go high to low for multiple splices to work
  53668. for (var key = this._keys.length - 1; key >= 0; key--) {
  53669. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  53670. this._keys.splice(key, 1);
  53671. }
  53672. }
  53673. }
  53674. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  53675. };
  53676. /**
  53677. * Gets the animation range by name, or null if not defined
  53678. * @param name Name of the animation range
  53679. * @returns Nullable animation range
  53680. */
  53681. Animation.prototype.getRange = function (name) {
  53682. return this._ranges[name];
  53683. };
  53684. /**
  53685. * Gets the key frames from the animation
  53686. * @returns The key frames of the animation
  53687. */
  53688. Animation.prototype.getKeys = function () {
  53689. return this._keys;
  53690. };
  53691. /**
  53692. * Gets the highest frame rate of the animation
  53693. * @returns Highest frame rate of the animation
  53694. */
  53695. Animation.prototype.getHighestFrame = function () {
  53696. var ret = 0;
  53697. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  53698. if (ret < this._keys[key].frame) {
  53699. ret = this._keys[key].frame;
  53700. }
  53701. }
  53702. return ret;
  53703. };
  53704. /**
  53705. * Gets the easing function of the animation
  53706. * @returns Easing function of the animation
  53707. */
  53708. Animation.prototype.getEasingFunction = function () {
  53709. return this._easingFunction;
  53710. };
  53711. /**
  53712. * Sets the easing function of the animation
  53713. * @param easingFunction A custom mathematical formula for animation
  53714. */
  53715. Animation.prototype.setEasingFunction = function (easingFunction) {
  53716. this._easingFunction = easingFunction;
  53717. };
  53718. /**
  53719. * Interpolates a scalar linearly
  53720. * @param startValue Start value of the animation curve
  53721. * @param endValue End value of the animation curve
  53722. * @param gradient Scalar amount to interpolate
  53723. * @returns Interpolated scalar value
  53724. */
  53725. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  53726. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  53727. };
  53728. /**
  53729. * Interpolates a scalar cubically
  53730. * @param startValue Start value of the animation curve
  53731. * @param outTangent End tangent of the animation
  53732. * @param endValue End value of the animation curve
  53733. * @param inTangent Start tangent of the animation curve
  53734. * @param gradient Scalar amount to interpolate
  53735. * @returns Interpolated scalar value
  53736. */
  53737. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53738. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53739. };
  53740. /**
  53741. * Interpolates a quaternion using a spherical linear interpolation
  53742. * @param startValue Start value of the animation curve
  53743. * @param endValue End value of the animation curve
  53744. * @param gradient Scalar amount to interpolate
  53745. * @returns Interpolated quaternion value
  53746. */
  53747. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  53748. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  53749. };
  53750. /**
  53751. * Interpolates a quaternion cubically
  53752. * @param startValue Start value of the animation curve
  53753. * @param outTangent End tangent of the animation curve
  53754. * @param endValue End value of the animation curve
  53755. * @param inTangent Start tangent of the animation curve
  53756. * @param gradient Scalar amount to interpolate
  53757. * @returns Interpolated quaternion value
  53758. */
  53759. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53760. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  53761. };
  53762. /**
  53763. * Interpolates a Vector3 linearl
  53764. * @param startValue Start value of the animation curve
  53765. * @param endValue End value of the animation curve
  53766. * @param gradient Scalar amount to interpolate
  53767. * @returns Interpolated scalar value
  53768. */
  53769. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  53770. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  53771. };
  53772. /**
  53773. * Interpolates a Vector3 cubically
  53774. * @param startValue Start value of the animation curve
  53775. * @param outTangent End tangent of the animation
  53776. * @param endValue End value of the animation curve
  53777. * @param inTangent Start tangent of the animation curve
  53778. * @param gradient Scalar amount to interpolate
  53779. * @returns InterpolatedVector3 value
  53780. */
  53781. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53782. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53783. };
  53784. /**
  53785. * Interpolates a Vector2 linearly
  53786. * @param startValue Start value of the animation curve
  53787. * @param endValue End value of the animation curve
  53788. * @param gradient Scalar amount to interpolate
  53789. * @returns Interpolated Vector2 value
  53790. */
  53791. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  53792. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  53793. };
  53794. /**
  53795. * Interpolates a Vector2 cubically
  53796. * @param startValue Start value of the animation curve
  53797. * @param outTangent End tangent of the animation
  53798. * @param endValue End value of the animation curve
  53799. * @param inTangent Start tangent of the animation curve
  53800. * @param gradient Scalar amount to interpolate
  53801. * @returns Interpolated Vector2 value
  53802. */
  53803. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53804. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53805. };
  53806. /**
  53807. * Interpolates a size linearly
  53808. * @param startValue Start value of the animation curve
  53809. * @param endValue End value of the animation curve
  53810. * @param gradient Scalar amount to interpolate
  53811. * @returns Interpolated Size value
  53812. */
  53813. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  53814. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  53815. };
  53816. /**
  53817. * Interpolates a Color3 linearly
  53818. * @param startValue Start value of the animation curve
  53819. * @param endValue End value of the animation curve
  53820. * @param gradient Scalar amount to interpolate
  53821. * @returns Interpolated Color3 value
  53822. */
  53823. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  53824. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  53825. };
  53826. /**
  53827. * @hidden Internal use only
  53828. */
  53829. Animation.prototype._getKeyValue = function (value) {
  53830. if (typeof value === "function") {
  53831. return value();
  53832. }
  53833. return value;
  53834. };
  53835. /**
  53836. * @hidden Internal use only
  53837. */
  53838. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  53839. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  53840. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  53841. }
  53842. var keys = this.getKeys();
  53843. // Try to get a hash to find the right key
  53844. 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));
  53845. if (keys[startKeyIndex].frame >= currentFrame) {
  53846. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  53847. startKeyIndex--;
  53848. }
  53849. }
  53850. for (var key = startKeyIndex; key < keys.length; key++) {
  53851. var endKey = keys[key + 1];
  53852. if (endKey.frame >= currentFrame) {
  53853. var startKey = keys[key];
  53854. var startValue = this._getKeyValue(startKey.value);
  53855. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  53856. return startValue;
  53857. }
  53858. var endValue = this._getKeyValue(endKey.value);
  53859. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  53860. var frameDelta = endKey.frame - startKey.frame;
  53861. // gradient : percent of currentFrame between the frame inf and the frame sup
  53862. var gradient = (currentFrame - startKey.frame) / frameDelta;
  53863. // check for easingFunction and correction of gradient
  53864. var easingFunction = this.getEasingFunction();
  53865. if (easingFunction != null) {
  53866. gradient = easingFunction.ease(gradient);
  53867. }
  53868. switch (this.dataType) {
  53869. // Float
  53870. case Animation.ANIMATIONTYPE_FLOAT:
  53871. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  53872. switch (loopMode) {
  53873. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53874. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53875. return floatValue;
  53876. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53877. return offsetValue * repeatCount + floatValue;
  53878. }
  53879. break;
  53880. // Quaternion
  53881. case Animation.ANIMATIONTYPE_QUATERNION:
  53882. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  53883. switch (loopMode) {
  53884. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53885. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53886. return quatValue;
  53887. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53888. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  53889. }
  53890. return quatValue;
  53891. // Vector3
  53892. case Animation.ANIMATIONTYPE_VECTOR3:
  53893. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  53894. switch (loopMode) {
  53895. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53896. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53897. return vec3Value;
  53898. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53899. return vec3Value.add(offsetValue.scale(repeatCount));
  53900. }
  53901. // Vector2
  53902. case Animation.ANIMATIONTYPE_VECTOR2:
  53903. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  53904. switch (loopMode) {
  53905. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53906. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53907. return vec2Value;
  53908. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53909. return vec2Value.add(offsetValue.scale(repeatCount));
  53910. }
  53911. // Size
  53912. case Animation.ANIMATIONTYPE_SIZE:
  53913. switch (loopMode) {
  53914. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53915. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53916. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  53917. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53918. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53919. }
  53920. // Color3
  53921. case Animation.ANIMATIONTYPE_COLOR3:
  53922. switch (loopMode) {
  53923. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53924. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53925. return this.color3InterpolateFunction(startValue, endValue, gradient);
  53926. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53927. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53928. }
  53929. // Matrix
  53930. case Animation.ANIMATIONTYPE_MATRIX:
  53931. switch (loopMode) {
  53932. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53933. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53934. if (Animation.AllowMatricesInterpolation) {
  53935. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  53936. }
  53937. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53938. return startValue;
  53939. }
  53940. default:
  53941. break;
  53942. }
  53943. break;
  53944. }
  53945. }
  53946. return this._getKeyValue(keys[keys.length - 1].value);
  53947. };
  53948. /**
  53949. * Defines the function to use to interpolate matrices
  53950. * @param startValue defines the start matrix
  53951. * @param endValue defines the end matrix
  53952. * @param gradient defines the gradient between both matrices
  53953. * @param result defines an optional target matrix where to store the interpolation
  53954. * @returns the interpolated matrix
  53955. */
  53956. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  53957. if (Animation.AllowMatrixDecomposeForInterpolation) {
  53958. if (result) {
  53959. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  53960. return result;
  53961. }
  53962. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  53963. }
  53964. if (result) {
  53965. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  53966. return result;
  53967. }
  53968. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  53969. };
  53970. /**
  53971. * Makes a copy of the animation
  53972. * @returns Cloned animation
  53973. */
  53974. Animation.prototype.clone = function () {
  53975. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  53976. clone.enableBlending = this.enableBlending;
  53977. clone.blendingSpeed = this.blendingSpeed;
  53978. if (this._keys) {
  53979. clone.setKeys(this._keys);
  53980. }
  53981. if (this._ranges) {
  53982. clone._ranges = {};
  53983. for (var name in this._ranges) {
  53984. var range = this._ranges[name];
  53985. if (!range) {
  53986. continue;
  53987. }
  53988. clone._ranges[name] = range.clone();
  53989. }
  53990. }
  53991. return clone;
  53992. };
  53993. /**
  53994. * Sets the key frames of the animation
  53995. * @param values The animation key frames to set
  53996. */
  53997. Animation.prototype.setKeys = function (values) {
  53998. this._keys = values.slice(0);
  53999. };
  54000. /**
  54001. * Serializes the animation to an object
  54002. * @returns Serialized object
  54003. */
  54004. Animation.prototype.serialize = function () {
  54005. var serializationObject = {};
  54006. serializationObject.name = this.name;
  54007. serializationObject.property = this.targetProperty;
  54008. serializationObject.framePerSecond = this.framePerSecond;
  54009. serializationObject.dataType = this.dataType;
  54010. serializationObject.loopBehavior = this.loopMode;
  54011. serializationObject.enableBlending = this.enableBlending;
  54012. serializationObject.blendingSpeed = this.blendingSpeed;
  54013. var dataType = this.dataType;
  54014. serializationObject.keys = [];
  54015. var keys = this.getKeys();
  54016. for (var index = 0; index < keys.length; index++) {
  54017. var animationKey = keys[index];
  54018. var key = {};
  54019. key.frame = animationKey.frame;
  54020. switch (dataType) {
  54021. case Animation.ANIMATIONTYPE_FLOAT:
  54022. key.values = [animationKey.value];
  54023. break;
  54024. case Animation.ANIMATIONTYPE_QUATERNION:
  54025. case Animation.ANIMATIONTYPE_MATRIX:
  54026. case Animation.ANIMATIONTYPE_VECTOR3:
  54027. case Animation.ANIMATIONTYPE_COLOR3:
  54028. key.values = animationKey.value.asArray();
  54029. break;
  54030. }
  54031. serializationObject.keys.push(key);
  54032. }
  54033. serializationObject.ranges = [];
  54034. for (var name in this._ranges) {
  54035. var source = this._ranges[name];
  54036. if (!source) {
  54037. continue;
  54038. }
  54039. var range = {};
  54040. range.name = name;
  54041. range.from = source.from;
  54042. range.to = source.to;
  54043. serializationObject.ranges.push(range);
  54044. }
  54045. return serializationObject;
  54046. };
  54047. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  54048. /**
  54049. * Get the float animation type
  54050. */
  54051. get: function () {
  54052. return Animation._ANIMATIONTYPE_FLOAT;
  54053. },
  54054. enumerable: true,
  54055. configurable: true
  54056. });
  54057. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  54058. /**
  54059. * Get the Vector3 animation type
  54060. */
  54061. get: function () {
  54062. return Animation._ANIMATIONTYPE_VECTOR3;
  54063. },
  54064. enumerable: true,
  54065. configurable: true
  54066. });
  54067. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  54068. /**
  54069. * Get the Vector2 animation type
  54070. */
  54071. get: function () {
  54072. return Animation._ANIMATIONTYPE_VECTOR2;
  54073. },
  54074. enumerable: true,
  54075. configurable: true
  54076. });
  54077. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  54078. /**
  54079. * Get the Size animation type
  54080. */
  54081. get: function () {
  54082. return Animation._ANIMATIONTYPE_SIZE;
  54083. },
  54084. enumerable: true,
  54085. configurable: true
  54086. });
  54087. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  54088. /**
  54089. * Get the Quaternion animation type
  54090. */
  54091. get: function () {
  54092. return Animation._ANIMATIONTYPE_QUATERNION;
  54093. },
  54094. enumerable: true,
  54095. configurable: true
  54096. });
  54097. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  54098. /**
  54099. * Get the Matrix animation type
  54100. */
  54101. get: function () {
  54102. return Animation._ANIMATIONTYPE_MATRIX;
  54103. },
  54104. enumerable: true,
  54105. configurable: true
  54106. });
  54107. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  54108. /**
  54109. * Get the Color3 animation type
  54110. */
  54111. get: function () {
  54112. return Animation._ANIMATIONTYPE_COLOR3;
  54113. },
  54114. enumerable: true,
  54115. configurable: true
  54116. });
  54117. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  54118. /**
  54119. * Get the Relative Loop Mode
  54120. */
  54121. get: function () {
  54122. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  54123. },
  54124. enumerable: true,
  54125. configurable: true
  54126. });
  54127. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  54128. /**
  54129. * Get the Cycle Loop Mode
  54130. */
  54131. get: function () {
  54132. return Animation._ANIMATIONLOOPMODE_CYCLE;
  54133. },
  54134. enumerable: true,
  54135. configurable: true
  54136. });
  54137. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  54138. /**
  54139. * Get the Constant Loop Mode
  54140. */
  54141. get: function () {
  54142. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  54143. },
  54144. enumerable: true,
  54145. configurable: true
  54146. });
  54147. /** @hidden */
  54148. Animation._UniversalLerp = function (left, right, amount) {
  54149. var constructor = left.constructor;
  54150. if (constructor.Lerp) { // Lerp supported
  54151. return constructor.Lerp(left, right, amount);
  54152. }
  54153. else if (constructor.Slerp) { // Slerp supported
  54154. return constructor.Slerp(left, right, amount);
  54155. }
  54156. else if (left.toFixed) { // Number
  54157. return left * (1.0 - amount) + amount * right;
  54158. }
  54159. else { // Blending not supported
  54160. return right;
  54161. }
  54162. };
  54163. /**
  54164. * Parses an animation object and creates an animation
  54165. * @param parsedAnimation Parsed animation object
  54166. * @returns Animation object
  54167. */
  54168. Animation.Parse = function (parsedAnimation) {
  54169. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  54170. var dataType = parsedAnimation.dataType;
  54171. var keys = [];
  54172. var data;
  54173. var index;
  54174. if (parsedAnimation.enableBlending) {
  54175. animation.enableBlending = parsedAnimation.enableBlending;
  54176. }
  54177. if (parsedAnimation.blendingSpeed) {
  54178. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  54179. }
  54180. for (index = 0; index < parsedAnimation.keys.length; index++) {
  54181. var key = parsedAnimation.keys[index];
  54182. var inTangent;
  54183. var outTangent;
  54184. switch (dataType) {
  54185. case Animation.ANIMATIONTYPE_FLOAT:
  54186. data = key.values[0];
  54187. if (key.values.length >= 1) {
  54188. inTangent = key.values[1];
  54189. }
  54190. if (key.values.length >= 2) {
  54191. outTangent = key.values[2];
  54192. }
  54193. break;
  54194. case Animation.ANIMATIONTYPE_QUATERNION:
  54195. data = BABYLON.Quaternion.FromArray(key.values);
  54196. if (key.values.length >= 8) {
  54197. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  54198. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  54199. inTangent = _inTangent;
  54200. }
  54201. }
  54202. if (key.values.length >= 12) {
  54203. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  54204. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  54205. outTangent = _outTangent;
  54206. }
  54207. }
  54208. break;
  54209. case Animation.ANIMATIONTYPE_MATRIX:
  54210. data = BABYLON.Matrix.FromArray(key.values);
  54211. break;
  54212. case Animation.ANIMATIONTYPE_COLOR3:
  54213. data = BABYLON.Color3.FromArray(key.values);
  54214. break;
  54215. case Animation.ANIMATIONTYPE_VECTOR3:
  54216. default:
  54217. data = BABYLON.Vector3.FromArray(key.values);
  54218. break;
  54219. }
  54220. var keyData = {};
  54221. keyData.frame = key.frame;
  54222. keyData.value = data;
  54223. if (inTangent != undefined) {
  54224. keyData.inTangent = inTangent;
  54225. }
  54226. if (outTangent != undefined) {
  54227. keyData.outTangent = outTangent;
  54228. }
  54229. keys.push(keyData);
  54230. }
  54231. animation.setKeys(keys);
  54232. if (parsedAnimation.ranges) {
  54233. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  54234. data = parsedAnimation.ranges[index];
  54235. animation.createRange(data.name, data.from, data.to);
  54236. }
  54237. }
  54238. return animation;
  54239. };
  54240. /**
  54241. * Appends the serialized animations from the source animations
  54242. * @param source Source containing the animations
  54243. * @param destination Target to store the animations
  54244. */
  54245. Animation.AppendSerializedAnimations = function (source, destination) {
  54246. if (source.animations) {
  54247. destination.animations = [];
  54248. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  54249. var animation = source.animations[animationIndex];
  54250. destination.animations.push(animation.serialize());
  54251. }
  54252. }
  54253. };
  54254. /**
  54255. * Use matrix interpolation instead of using direct key value when animating matrices
  54256. */
  54257. Animation.AllowMatricesInterpolation = false;
  54258. /**
  54259. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  54260. */
  54261. Animation.AllowMatrixDecomposeForInterpolation = true;
  54262. // Statics
  54263. /**
  54264. * Float animation type
  54265. */
  54266. Animation._ANIMATIONTYPE_FLOAT = 0;
  54267. /**
  54268. * Vector3 animation type
  54269. */
  54270. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  54271. /**
  54272. * Quaternion animation type
  54273. */
  54274. Animation._ANIMATIONTYPE_QUATERNION = 2;
  54275. /**
  54276. * Matrix animation type
  54277. */
  54278. Animation._ANIMATIONTYPE_MATRIX = 3;
  54279. /**
  54280. * Color3 animation type
  54281. */
  54282. Animation._ANIMATIONTYPE_COLOR3 = 4;
  54283. /**
  54284. * Vector2 animation type
  54285. */
  54286. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  54287. /**
  54288. * Size animation type
  54289. */
  54290. Animation._ANIMATIONTYPE_SIZE = 6;
  54291. /**
  54292. * Relative Loop Mode
  54293. */
  54294. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  54295. /**
  54296. * Cycle Loop Mode
  54297. */
  54298. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  54299. /**
  54300. * Constant Loop Mode
  54301. */
  54302. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  54303. return Animation;
  54304. }());
  54305. BABYLON.Animation = Animation;
  54306. })(BABYLON || (BABYLON = {}));
  54307. //# sourceMappingURL=babylon.animation.js.map
  54308. var BABYLON;
  54309. (function (BABYLON) {
  54310. /**
  54311. * This class defines the direct association between an animation and a target
  54312. */
  54313. var TargetedAnimation = /** @class */ (function () {
  54314. function TargetedAnimation() {
  54315. }
  54316. return TargetedAnimation;
  54317. }());
  54318. BABYLON.TargetedAnimation = TargetedAnimation;
  54319. /**
  54320. * Use this class to create coordinated animations on multiple targets
  54321. */
  54322. var AnimationGroup = /** @class */ (function () {
  54323. /**
  54324. * Instantiates a new Animation Group.
  54325. * This helps managing several animations at once.
  54326. * @see http://doc.babylonjs.com/how_to/group
  54327. * @param name Defines the name of the group
  54328. * @param scene Defines the scene the group belongs to
  54329. */
  54330. function AnimationGroup(
  54331. /** The name of the animation group */
  54332. name, scene) {
  54333. if (scene === void 0) { scene = null; }
  54334. this.name = name;
  54335. this._targetedAnimations = new Array();
  54336. this._animatables = new Array();
  54337. this._from = Number.MAX_VALUE;
  54338. this._to = -Number.MAX_VALUE;
  54339. this._speedRatio = 1;
  54340. /**
  54341. * This observable will notify when one animation have ended.
  54342. */
  54343. this.onAnimationEndObservable = new BABYLON.Observable();
  54344. /**
  54345. * This observable will notify when all animations have ended.
  54346. */
  54347. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  54348. /**
  54349. * This observable will notify when all animations have paused.
  54350. */
  54351. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  54352. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54353. this._scene.animationGroups.push(this);
  54354. }
  54355. Object.defineProperty(AnimationGroup.prototype, "from", {
  54356. /**
  54357. * Gets the first frame
  54358. */
  54359. get: function () {
  54360. return this._from;
  54361. },
  54362. enumerable: true,
  54363. configurable: true
  54364. });
  54365. Object.defineProperty(AnimationGroup.prototype, "to", {
  54366. /**
  54367. * Gets the last frame
  54368. */
  54369. get: function () {
  54370. return this._to;
  54371. },
  54372. enumerable: true,
  54373. configurable: true
  54374. });
  54375. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  54376. /**
  54377. * Define if the animations are started
  54378. */
  54379. get: function () {
  54380. return this._isStarted;
  54381. },
  54382. enumerable: true,
  54383. configurable: true
  54384. });
  54385. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  54386. /**
  54387. * Gets or sets the speed ratio to use for all animations
  54388. */
  54389. get: function () {
  54390. return this._speedRatio;
  54391. },
  54392. /**
  54393. * Gets or sets the speed ratio to use for all animations
  54394. */
  54395. set: function (value) {
  54396. if (this._speedRatio === value) {
  54397. return;
  54398. }
  54399. this._speedRatio = value;
  54400. for (var index = 0; index < this._animatables.length; index++) {
  54401. var animatable = this._animatables[index];
  54402. animatable.speedRatio = this._speedRatio;
  54403. }
  54404. },
  54405. enumerable: true,
  54406. configurable: true
  54407. });
  54408. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  54409. /**
  54410. * Gets the targeted animations for this animation group
  54411. */
  54412. get: function () {
  54413. return this._targetedAnimations;
  54414. },
  54415. enumerable: true,
  54416. configurable: true
  54417. });
  54418. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  54419. /**
  54420. * returning the list of animatables controlled by this animation group.
  54421. */
  54422. get: function () {
  54423. return this._animatables;
  54424. },
  54425. enumerable: true,
  54426. configurable: true
  54427. });
  54428. /**
  54429. * Add an animation (with its target) in the group
  54430. * @param animation defines the animation we want to add
  54431. * @param target defines the target of the animation
  54432. * @returns the TargetedAnimation object
  54433. */
  54434. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  54435. var targetedAnimation = {
  54436. animation: animation,
  54437. target: target
  54438. };
  54439. var keys = animation.getKeys();
  54440. if (this._from > keys[0].frame) {
  54441. this._from = keys[0].frame;
  54442. }
  54443. if (this._to < keys[keys.length - 1].frame) {
  54444. this._to = keys[keys.length - 1].frame;
  54445. }
  54446. this._targetedAnimations.push(targetedAnimation);
  54447. return targetedAnimation;
  54448. };
  54449. /**
  54450. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  54451. * It can add constant keys at begin or end
  54452. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  54453. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  54454. * @returns the animation group
  54455. */
  54456. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  54457. if (beginFrame === void 0) { beginFrame = null; }
  54458. if (endFrame === void 0) { endFrame = null; }
  54459. if (beginFrame == null) {
  54460. beginFrame = this._from;
  54461. }
  54462. if (endFrame == null) {
  54463. endFrame = this._to;
  54464. }
  54465. for (var index = 0; index < this._targetedAnimations.length; index++) {
  54466. var targetedAnimation = this._targetedAnimations[index];
  54467. var keys = targetedAnimation.animation.getKeys();
  54468. var startKey = keys[0];
  54469. var endKey = keys[keys.length - 1];
  54470. if (startKey.frame > beginFrame) {
  54471. var newKey = {
  54472. frame: beginFrame,
  54473. value: startKey.value,
  54474. inTangent: startKey.inTangent,
  54475. outTangent: startKey.outTangent,
  54476. interpolation: startKey.interpolation
  54477. };
  54478. keys.splice(0, 0, newKey);
  54479. }
  54480. if (endKey.frame < endFrame) {
  54481. var newKey = {
  54482. frame: endFrame,
  54483. value: endKey.value,
  54484. inTangent: endKey.outTangent,
  54485. outTangent: endKey.outTangent,
  54486. interpolation: endKey.interpolation
  54487. };
  54488. keys.push(newKey);
  54489. }
  54490. }
  54491. this._from = beginFrame;
  54492. this._to = endFrame;
  54493. return this;
  54494. };
  54495. /**
  54496. * Start all animations on given targets
  54497. * @param loop defines if animations must loop
  54498. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  54499. * @param from defines the from key (optional)
  54500. * @param to defines the to key (optional)
  54501. * @returns the current animation group
  54502. */
  54503. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  54504. var _this = this;
  54505. if (loop === void 0) { loop = false; }
  54506. if (speedRatio === void 0) { speedRatio = 1; }
  54507. if (this._isStarted || this._targetedAnimations.length === 0) {
  54508. return this;
  54509. }
  54510. var _loop_1 = function (targetedAnimation) {
  54511. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  54512. animatable.onAnimationEnd = function () {
  54513. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  54514. _this._checkAnimationGroupEnded(animatable);
  54515. };
  54516. this_1._animatables.push(animatable);
  54517. };
  54518. var this_1 = this;
  54519. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  54520. var targetedAnimation = _a[_i];
  54521. _loop_1(targetedAnimation);
  54522. }
  54523. this._speedRatio = speedRatio;
  54524. this._isStarted = true;
  54525. return this;
  54526. };
  54527. /**
  54528. * Pause all animations
  54529. * @returns the animation group
  54530. */
  54531. AnimationGroup.prototype.pause = function () {
  54532. if (!this._isStarted) {
  54533. return this;
  54534. }
  54535. for (var index = 0; index < this._animatables.length; index++) {
  54536. var animatable = this._animatables[index];
  54537. animatable.pause();
  54538. }
  54539. this.onAnimationGroupPauseObservable.notifyObservers(this);
  54540. return this;
  54541. };
  54542. /**
  54543. * Play all animations to initial state
  54544. * This function will start() the animations if they were not started or will restart() them if they were paused
  54545. * @param loop defines if animations must loop
  54546. * @returns the animation group
  54547. */
  54548. AnimationGroup.prototype.play = function (loop) {
  54549. // only if all animatables are ready and exist
  54550. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  54551. if (loop !== undefined) {
  54552. for (var index = 0; index < this._animatables.length; index++) {
  54553. var animatable = this._animatables[index];
  54554. animatable.loopAnimation = loop;
  54555. }
  54556. }
  54557. this.restart();
  54558. }
  54559. else {
  54560. this.stop();
  54561. this.start(loop, this._speedRatio);
  54562. }
  54563. return this;
  54564. };
  54565. /**
  54566. * Reset all animations to initial state
  54567. * @returns the animation group
  54568. */
  54569. AnimationGroup.prototype.reset = function () {
  54570. if (!this._isStarted) {
  54571. return this;
  54572. }
  54573. for (var index = 0; index < this._animatables.length; index++) {
  54574. var animatable = this._animatables[index];
  54575. animatable.reset();
  54576. }
  54577. return this;
  54578. };
  54579. /**
  54580. * Restart animations from key 0
  54581. * @returns the animation group
  54582. */
  54583. AnimationGroup.prototype.restart = function () {
  54584. if (!this._isStarted) {
  54585. return this;
  54586. }
  54587. for (var index = 0; index < this._animatables.length; index++) {
  54588. var animatable = this._animatables[index];
  54589. animatable.restart();
  54590. }
  54591. return this;
  54592. };
  54593. /**
  54594. * Stop all animations
  54595. * @returns the animation group
  54596. */
  54597. AnimationGroup.prototype.stop = function () {
  54598. if (!this._isStarted) {
  54599. return this;
  54600. }
  54601. var list = this._animatables.slice();
  54602. for (var index = 0; index < list.length; index++) {
  54603. list[index].stop();
  54604. }
  54605. this._isStarted = false;
  54606. return this;
  54607. };
  54608. /**
  54609. * Set animation weight for all animatables
  54610. * @param weight defines the weight to use
  54611. * @return the animationGroup
  54612. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54613. */
  54614. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  54615. for (var index = 0; index < this._animatables.length; index++) {
  54616. var animatable = this._animatables[index];
  54617. animatable.weight = weight;
  54618. }
  54619. return this;
  54620. };
  54621. /**
  54622. * Synchronize and normalize all animatables with a source animatable
  54623. * @param root defines the root animatable to synchronize with
  54624. * @return the animationGroup
  54625. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54626. */
  54627. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  54628. for (var index = 0; index < this._animatables.length; index++) {
  54629. var animatable = this._animatables[index];
  54630. animatable.syncWith(root);
  54631. }
  54632. return this;
  54633. };
  54634. /**
  54635. * Goes to a specific frame in this animation group
  54636. * @param frame the frame number to go to
  54637. * @return the animationGroup
  54638. */
  54639. AnimationGroup.prototype.goToFrame = function (frame) {
  54640. if (!this._isStarted) {
  54641. return this;
  54642. }
  54643. for (var index = 0; index < this._animatables.length; index++) {
  54644. var animatable = this._animatables[index];
  54645. animatable.goToFrame(frame);
  54646. }
  54647. return this;
  54648. };
  54649. /**
  54650. * Dispose all associated resources
  54651. */
  54652. AnimationGroup.prototype.dispose = function () {
  54653. this._targetedAnimations = [];
  54654. this._animatables = [];
  54655. var index = this._scene.animationGroups.indexOf(this);
  54656. if (index > -1) {
  54657. this._scene.animationGroups.splice(index, 1);
  54658. }
  54659. };
  54660. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  54661. // animatable should be taken out of the array
  54662. var idx = this._animatables.indexOf(animatable);
  54663. if (idx > -1) {
  54664. this._animatables.splice(idx, 1);
  54665. }
  54666. // all animatables were removed? animation group ended!
  54667. if (this._animatables.length === 0) {
  54668. this._isStarted = false;
  54669. this.onAnimationGroupEndObservable.notifyObservers(this);
  54670. }
  54671. };
  54672. // Statics
  54673. /**
  54674. * Returns a new AnimationGroup object parsed from the source provided.
  54675. * @param parsedAnimationGroup defines the source
  54676. * @param scene defines the scene that will receive the animationGroup
  54677. * @returns a new AnimationGroup
  54678. */
  54679. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  54680. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  54681. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  54682. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  54683. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  54684. var id = targetedAnimation.targetId;
  54685. var targetNode = scene.getNodeByID(id);
  54686. if (targetNode != null) {
  54687. animationGroup.addTargetedAnimation(animation, targetNode);
  54688. }
  54689. }
  54690. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  54691. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  54692. }
  54693. return animationGroup;
  54694. };
  54695. /**
  54696. * Returns the string "AnimationGroup"
  54697. * @returns "AnimationGroup"
  54698. */
  54699. AnimationGroup.prototype.getClassName = function () {
  54700. return "AnimationGroup";
  54701. };
  54702. /**
  54703. * Creates a detailled string about the object
  54704. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  54705. * @returns a string representing the object
  54706. */
  54707. AnimationGroup.prototype.toString = function (fullDetails) {
  54708. var ret = "Name: " + this.name;
  54709. ret += ", type: " + this.getClassName();
  54710. if (fullDetails) {
  54711. ret += ", from: " + this._from;
  54712. ret += ", to: " + this._to;
  54713. ret += ", isStarted: " + this._isStarted;
  54714. ret += ", speedRatio: " + this._speedRatio;
  54715. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  54716. ret += ", animatables length: " + this._animatables;
  54717. }
  54718. return ret;
  54719. };
  54720. return AnimationGroup;
  54721. }());
  54722. BABYLON.AnimationGroup = AnimationGroup;
  54723. })(BABYLON || (BABYLON = {}));
  54724. //# sourceMappingURL=babylon.animationGroup.js.map
  54725. var BABYLON;
  54726. (function (BABYLON) {
  54727. // Static values to help the garbage collector
  54728. // Quaternion
  54729. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  54730. // Vector3
  54731. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  54732. // Vector2
  54733. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  54734. // Size
  54735. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  54736. // Color3
  54737. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  54738. /**
  54739. * Defines a runtime animation
  54740. */
  54741. var RuntimeAnimation = /** @class */ (function () {
  54742. /**
  54743. * Create a new RuntimeAnimation object
  54744. * @param target defines the target of the animation
  54745. * @param animation defines the source animation object
  54746. * @param scene defines the hosting scene
  54747. * @param host defines the initiating Animatable
  54748. */
  54749. function RuntimeAnimation(target, animation, scene, host) {
  54750. var _this = this;
  54751. this._events = new Array();
  54752. /**
  54753. * The current frame of the runtime animation
  54754. */
  54755. this._currentFrame = 0;
  54756. /**
  54757. * The original value of the runtime animation
  54758. */
  54759. this._originalValue = new Array();
  54760. /**
  54761. * The offsets cache of the runtime animation
  54762. */
  54763. this._offsetsCache = {};
  54764. /**
  54765. * The high limits cache of the runtime animation
  54766. */
  54767. this._highLimitsCache = {};
  54768. /**
  54769. * Specifies if the runtime animation has been stopped
  54770. */
  54771. this._stopped = false;
  54772. /**
  54773. * The blending factor of the runtime animation
  54774. */
  54775. this._blendingFactor = 0;
  54776. /**
  54777. * The target path of the runtime animation
  54778. */
  54779. this._targetPath = "";
  54780. /**
  54781. * The weight of the runtime animation
  54782. */
  54783. this._weight = 1.0;
  54784. /**
  54785. * The ratio offset of the runtime animation
  54786. */
  54787. this._ratioOffset = 0;
  54788. /**
  54789. * The previous delay of the runtime animation
  54790. */
  54791. this._previousDelay = 0;
  54792. /**
  54793. * The previous ratio of the runtime animation
  54794. */
  54795. this._previousRatio = 0;
  54796. this._animation = animation;
  54797. this._target = target;
  54798. this._scene = scene;
  54799. this._host = host;
  54800. animation._runtimeAnimations.push(this);
  54801. // Cloning events locally
  54802. var events = animation.getEvents();
  54803. if (events && events.length > 0) {
  54804. events.forEach(function (e) {
  54805. _this._events.push(e._clone());
  54806. });
  54807. }
  54808. }
  54809. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  54810. /**
  54811. * Gets the current frame of the runtime animation
  54812. */
  54813. get: function () {
  54814. return this._currentFrame;
  54815. },
  54816. enumerable: true,
  54817. configurable: true
  54818. });
  54819. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  54820. /**
  54821. * Gets the weight of the runtime animation
  54822. */
  54823. get: function () {
  54824. return this._weight;
  54825. },
  54826. enumerable: true,
  54827. configurable: true
  54828. });
  54829. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  54830. /**
  54831. * Gets the current value of the runtime animation
  54832. */
  54833. get: function () {
  54834. return this._currentValue;
  54835. },
  54836. enumerable: true,
  54837. configurable: true
  54838. });
  54839. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  54840. /**
  54841. * Gets the target path of the runtime animation
  54842. */
  54843. get: function () {
  54844. return this._targetPath;
  54845. },
  54846. enumerable: true,
  54847. configurable: true
  54848. });
  54849. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  54850. /**
  54851. * Gets the actual target of the runtime animation
  54852. */
  54853. get: function () {
  54854. return this._activeTarget;
  54855. },
  54856. enumerable: true,
  54857. configurable: true
  54858. });
  54859. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  54860. /**
  54861. * Gets the animation from the runtime animation
  54862. */
  54863. get: function () {
  54864. return this._animation;
  54865. },
  54866. enumerable: true,
  54867. configurable: true
  54868. });
  54869. /**
  54870. * Resets the runtime animation to the beginning
  54871. * @param restoreOriginal defines whether to restore the target property to the original value
  54872. */
  54873. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  54874. if (restoreOriginal === void 0) { restoreOriginal = false; }
  54875. if (restoreOriginal) {
  54876. if (this._target instanceof Array) {
  54877. var index = 0;
  54878. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54879. var target = _a[_i];
  54880. if (this._originalValue[index] !== undefined) {
  54881. this._setValue(target, this._originalValue[index], -1);
  54882. }
  54883. index++;
  54884. }
  54885. }
  54886. else {
  54887. if (this._originalValue[0] !== undefined) {
  54888. this._setValue(this._target, this._originalValue[0], -1);
  54889. }
  54890. }
  54891. }
  54892. this._offsetsCache = {};
  54893. this._highLimitsCache = {};
  54894. this._currentFrame = 0;
  54895. this._blendingFactor = 0;
  54896. this._originalValue = new Array();
  54897. // Events
  54898. for (var index = 0; index < this._events.length; index++) {
  54899. this._events[index].isDone = false;
  54900. }
  54901. };
  54902. /**
  54903. * Specifies if the runtime animation is stopped
  54904. * @returns Boolean specifying if the runtime animation is stopped
  54905. */
  54906. RuntimeAnimation.prototype.isStopped = function () {
  54907. return this._stopped;
  54908. };
  54909. /**
  54910. * Disposes of the runtime animation
  54911. */
  54912. RuntimeAnimation.prototype.dispose = function () {
  54913. var index = this._animation.runtimeAnimations.indexOf(this);
  54914. if (index > -1) {
  54915. this._animation.runtimeAnimations.splice(index, 1);
  54916. }
  54917. };
  54918. /**
  54919. * Interpolates the animation from the current frame
  54920. * @param currentFrame The frame to interpolate the animation to
  54921. * @param repeatCount The number of times that the animation should loop
  54922. * @param loopMode The type of looping mode to use
  54923. * @param offsetValue Animation offset value
  54924. * @param highLimitValue The high limit value
  54925. * @returns The interpolated value
  54926. */
  54927. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  54928. this._currentFrame = currentFrame;
  54929. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  54930. this._workValue = BABYLON.Matrix.Zero();
  54931. }
  54932. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  54933. };
  54934. /**
  54935. * Apply the interpolated value to the target
  54936. * @param currentValue defines the value computed by the animation
  54937. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  54938. */
  54939. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  54940. if (weight === void 0) { weight = 1.0; }
  54941. if (this._target instanceof Array) {
  54942. var index = 0;
  54943. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54944. var target = _a[_i];
  54945. this._setValue(target, currentValue, weight, index);
  54946. index++;
  54947. }
  54948. }
  54949. else {
  54950. this._setValue(this._target, currentValue, weight);
  54951. }
  54952. };
  54953. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  54954. if (targetIndex === void 0) { targetIndex = 0; }
  54955. // Set value
  54956. var path;
  54957. var destination;
  54958. var targetPropertyPath = this._animation.targetPropertyPath;
  54959. if (targetPropertyPath.length > 1) {
  54960. var property = target[targetPropertyPath[0]];
  54961. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  54962. property = property[targetPropertyPath[index]];
  54963. }
  54964. path = targetPropertyPath[targetPropertyPath.length - 1];
  54965. destination = property;
  54966. }
  54967. else {
  54968. path = targetPropertyPath[0];
  54969. destination = target;
  54970. }
  54971. this._targetPath = path;
  54972. this._activeTarget = destination;
  54973. this._weight = weight;
  54974. if (this._originalValue[targetIndex] === undefined) {
  54975. var originalValue = void 0;
  54976. if (destination.getRestPose && path === "_matrix") { // For bones
  54977. originalValue = destination.getRestPose();
  54978. }
  54979. else {
  54980. originalValue = destination[path];
  54981. }
  54982. if (originalValue && originalValue.clone) {
  54983. this._originalValue[targetIndex] = originalValue.clone();
  54984. }
  54985. else {
  54986. this._originalValue[targetIndex] = originalValue;
  54987. }
  54988. }
  54989. // Blending
  54990. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  54991. if (enableBlending && this._blendingFactor <= 1.0) {
  54992. if (!this._originalBlendValue) {
  54993. var originalValue = destination[path];
  54994. if (originalValue.clone) {
  54995. this._originalBlendValue = originalValue.clone();
  54996. }
  54997. else {
  54998. this._originalBlendValue = originalValue;
  54999. }
  55000. }
  55001. if (this._originalBlendValue.m) { // Matrix
  55002. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  55003. if (this._currentValue) {
  55004. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55005. }
  55006. else {
  55007. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55008. }
  55009. }
  55010. else {
  55011. if (this._currentValue) {
  55012. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55013. }
  55014. else {
  55015. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55016. }
  55017. }
  55018. }
  55019. else {
  55020. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55021. }
  55022. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  55023. this._blendingFactor += blendingSpeed;
  55024. }
  55025. else {
  55026. this._currentValue = currentValue;
  55027. }
  55028. if (weight !== -1.0) {
  55029. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  55030. }
  55031. else {
  55032. destination[path] = this._currentValue;
  55033. }
  55034. if (target.markAsDirty) {
  55035. target.markAsDirty(this._animation.targetProperty);
  55036. }
  55037. };
  55038. /**
  55039. * Gets the loop pmode of the runtime animation
  55040. * @returns Loop Mode
  55041. */
  55042. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  55043. if (this._target && this._target.animationPropertiesOverride) {
  55044. return this._target.animationPropertiesOverride.loopMode;
  55045. }
  55046. return this._animation.loopMode;
  55047. };
  55048. /**
  55049. * Move the current animation to a given frame
  55050. * @param frame defines the frame to move to
  55051. */
  55052. RuntimeAnimation.prototype.goToFrame = function (frame) {
  55053. var keys = this._animation.getKeys();
  55054. if (frame < keys[0].frame) {
  55055. frame = keys[0].frame;
  55056. }
  55057. else if (frame > keys[keys.length - 1].frame) {
  55058. frame = keys[keys.length - 1].frame;
  55059. }
  55060. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  55061. this.setValue(currentValue, -1);
  55062. };
  55063. /**
  55064. * @hidden Internal use only
  55065. */
  55066. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  55067. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  55068. this._ratioOffset = this._previousRatio - newRatio;
  55069. };
  55070. /**
  55071. * Execute the current animation
  55072. * @param delay defines the delay to add to the current frame
  55073. * @param from defines the lower bound of the animation range
  55074. * @param to defines the upper bound of the animation range
  55075. * @param loop defines if the current animation must loop
  55076. * @param speedRatio defines the current speed ratio
  55077. * @param weight defines the weight of the animation (default is -1 so no weight)
  55078. * @returns a boolean indicating if the animation is running
  55079. */
  55080. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  55081. if (weight === void 0) { weight = -1.0; }
  55082. var targetPropertyPath = this._animation.targetPropertyPath;
  55083. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  55084. this._stopped = true;
  55085. return false;
  55086. }
  55087. var returnValue = true;
  55088. var keys = this._animation.getKeys();
  55089. // Adding a start key at frame 0 if missing
  55090. if (keys[0].frame !== 0) {
  55091. var newKey = { frame: 0, value: keys[0].value };
  55092. keys.splice(0, 0, newKey);
  55093. }
  55094. // Adding a duplicate key when there is only one key at frame zero
  55095. else if (keys.length === 1) {
  55096. var newKey = { frame: 0.001, value: keys[0].value };
  55097. keys.push(newKey);
  55098. }
  55099. // Check limits
  55100. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  55101. from = keys[0].frame;
  55102. }
  55103. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  55104. to = keys[keys.length - 1].frame;
  55105. }
  55106. //to and from cannot be the same key
  55107. if (from === to) {
  55108. if (from > keys[0].frame) {
  55109. from--;
  55110. }
  55111. else if (to < keys[keys.length - 1].frame) {
  55112. to++;
  55113. }
  55114. }
  55115. // Compute ratio
  55116. var range = to - from;
  55117. var offsetValue;
  55118. // ratio represents the frame delta between from and to
  55119. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  55120. var highLimitValue = 0;
  55121. this._previousDelay = delay;
  55122. this._previousRatio = ratio;
  55123. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  55124. returnValue = false;
  55125. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  55126. }
  55127. else {
  55128. // Get max value if required
  55129. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  55130. var keyOffset = to.toString() + from.toString();
  55131. if (!this._offsetsCache[keyOffset]) {
  55132. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55133. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55134. switch (this._animation.dataType) {
  55135. // Float
  55136. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55137. this._offsetsCache[keyOffset] = toValue - fromValue;
  55138. break;
  55139. // Quaternion
  55140. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55141. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55142. break;
  55143. // Vector3
  55144. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55145. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55146. // Vector2
  55147. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55148. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55149. // Size
  55150. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55151. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55152. // Color3
  55153. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55154. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55155. default:
  55156. break;
  55157. }
  55158. this._highLimitsCache[keyOffset] = toValue;
  55159. }
  55160. highLimitValue = this._highLimitsCache[keyOffset];
  55161. offsetValue = this._offsetsCache[keyOffset];
  55162. }
  55163. }
  55164. if (offsetValue === undefined) {
  55165. switch (this._animation.dataType) {
  55166. // Float
  55167. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55168. offsetValue = 0;
  55169. break;
  55170. // Quaternion
  55171. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55172. offsetValue = _staticOffsetValueQuaternion;
  55173. break;
  55174. // Vector3
  55175. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55176. offsetValue = _staticOffsetValueVector3;
  55177. break;
  55178. // Vector2
  55179. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55180. offsetValue = _staticOffsetValueVector2;
  55181. break;
  55182. // Size
  55183. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55184. offsetValue = _staticOffsetValueSize;
  55185. break;
  55186. // Color3
  55187. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55188. offsetValue = _staticOffsetValueColor3;
  55189. }
  55190. }
  55191. // Compute value
  55192. var repeatCount = (ratio / range) >> 0;
  55193. var currentFrame = returnValue ? from + ratio % range : to;
  55194. // Need to normalize?
  55195. if (this._host && this._host.syncRoot) {
  55196. var syncRoot = this._host.syncRoot;
  55197. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  55198. currentFrame = from + (to - from) * hostNormalizedFrame;
  55199. }
  55200. // Reset events if looping
  55201. var events = this._events;
  55202. if (range > 0 && this.currentFrame > currentFrame ||
  55203. range < 0 && this.currentFrame < currentFrame) {
  55204. // Need to reset animation events
  55205. for (var index = 0; index < events.length; index++) {
  55206. if (!events[index].onlyOnce) {
  55207. // reset event, the animation is looping
  55208. events[index].isDone = false;
  55209. }
  55210. }
  55211. }
  55212. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  55213. // Set value
  55214. this.setValue(currentValue, weight);
  55215. // Check events
  55216. for (var index = 0; index < events.length; index++) {
  55217. // Make sure current frame has passed event frame and that event frame is within the current range
  55218. // Also, handle both forward and reverse animations
  55219. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  55220. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  55221. var event = events[index];
  55222. if (!event.isDone) {
  55223. // If event should be done only once, remove it.
  55224. if (event.onlyOnce) {
  55225. events.splice(index, 1);
  55226. index--;
  55227. }
  55228. event.isDone = true;
  55229. event.action(currentFrame);
  55230. } // Don't do anything if the event has already be done.
  55231. }
  55232. }
  55233. if (!returnValue) {
  55234. this._stopped = true;
  55235. }
  55236. return returnValue;
  55237. };
  55238. return RuntimeAnimation;
  55239. }());
  55240. BABYLON.RuntimeAnimation = RuntimeAnimation;
  55241. })(BABYLON || (BABYLON = {}));
  55242. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  55243. var BABYLON;
  55244. (function (BABYLON) {
  55245. /**
  55246. * Class used to store an actual running animation
  55247. */
  55248. var Animatable = /** @class */ (function () {
  55249. /**
  55250. * Creates a new Animatable
  55251. * @param scene defines the hosting scene
  55252. * @param target defines the target object
  55253. * @param fromFrame defines the starting frame number (default is 0)
  55254. * @param toFrame defines the ending frame number (default is 100)
  55255. * @param loopAnimation defines if the animation must loop (default is false)
  55256. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  55257. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  55258. * @param animations defines a group of animation to add to the new Animatable
  55259. */
  55260. function Animatable(scene,
  55261. /** defines the target object */
  55262. target,
  55263. /** defines the starting frame number (default is 0) */
  55264. fromFrame,
  55265. /** defines the ending frame number (default is 100) */
  55266. toFrame,
  55267. /** defines if the animation must loop (default is false) */
  55268. loopAnimation, speedRatio,
  55269. /** defines a callback to call when animation ends if it is not looping */
  55270. onAnimationEnd, animations) {
  55271. if (fromFrame === void 0) { fromFrame = 0; }
  55272. if (toFrame === void 0) { toFrame = 100; }
  55273. if (loopAnimation === void 0) { loopAnimation = false; }
  55274. if (speedRatio === void 0) { speedRatio = 1.0; }
  55275. this.target = target;
  55276. this.fromFrame = fromFrame;
  55277. this.toFrame = toFrame;
  55278. this.loopAnimation = loopAnimation;
  55279. this.onAnimationEnd = onAnimationEnd;
  55280. this._localDelayOffset = null;
  55281. this._pausedDelay = null;
  55282. this._runtimeAnimations = new Array();
  55283. this._paused = false;
  55284. this._speedRatio = 1;
  55285. this._weight = -1.0;
  55286. /**
  55287. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  55288. * This will only apply for non looping animation (default is true)
  55289. */
  55290. this.disposeOnEnd = true;
  55291. /**
  55292. * Gets a boolean indicating if the animation has started
  55293. */
  55294. this.animationStarted = false;
  55295. /**
  55296. * Observer raised when the animation ends
  55297. */
  55298. this.onAnimationEndObservable = new BABYLON.Observable();
  55299. this._scene = scene;
  55300. if (animations) {
  55301. this.appendAnimations(target, animations);
  55302. }
  55303. this._speedRatio = speedRatio;
  55304. scene._activeAnimatables.push(this);
  55305. }
  55306. Object.defineProperty(Animatable.prototype, "syncRoot", {
  55307. /**
  55308. * Gets the root Animatable used to synchronize and normalize animations
  55309. */
  55310. get: function () {
  55311. return this._syncRoot;
  55312. },
  55313. enumerable: true,
  55314. configurable: true
  55315. });
  55316. Object.defineProperty(Animatable.prototype, "masterFrame", {
  55317. /**
  55318. * Gets the current frame of the first RuntimeAnimation
  55319. * Used to synchronize Animatables
  55320. */
  55321. get: function () {
  55322. if (this._runtimeAnimations.length === 0) {
  55323. return 0;
  55324. }
  55325. return this._runtimeAnimations[0].currentFrame;
  55326. },
  55327. enumerable: true,
  55328. configurable: true
  55329. });
  55330. Object.defineProperty(Animatable.prototype, "weight", {
  55331. /**
  55332. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  55333. */
  55334. get: function () {
  55335. return this._weight;
  55336. },
  55337. set: function (value) {
  55338. if (value === -1) { // -1 is ok and means no weight
  55339. this._weight = -1;
  55340. return;
  55341. }
  55342. // Else weight must be in [0, 1] range
  55343. this._weight = Math.min(Math.max(value, 0), 1.0);
  55344. },
  55345. enumerable: true,
  55346. configurable: true
  55347. });
  55348. Object.defineProperty(Animatable.prototype, "speedRatio", {
  55349. /**
  55350. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  55351. */
  55352. get: function () {
  55353. return this._speedRatio;
  55354. },
  55355. set: function (value) {
  55356. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  55357. var animation = this._runtimeAnimations[index];
  55358. animation._prepareForSpeedRatioChange(value);
  55359. }
  55360. this._speedRatio = value;
  55361. },
  55362. enumerable: true,
  55363. configurable: true
  55364. });
  55365. // Methods
  55366. /**
  55367. * Synchronize and normalize current Animatable with a source Animatable
  55368. * This is useful when using animation weights and when animations are not of the same length
  55369. * @param root defines the root Animatable to synchronize with
  55370. * @returns the current Animatable
  55371. */
  55372. Animatable.prototype.syncWith = function (root) {
  55373. this._syncRoot = root;
  55374. if (root) {
  55375. // Make sure this animatable will animate after the root
  55376. var index = this._scene._activeAnimatables.indexOf(this);
  55377. if (index > -1) {
  55378. this._scene._activeAnimatables.splice(index, 1);
  55379. this._scene._activeAnimatables.push(this);
  55380. }
  55381. }
  55382. return this;
  55383. };
  55384. /**
  55385. * Gets the list of runtime animations
  55386. * @returns an array of RuntimeAnimation
  55387. */
  55388. Animatable.prototype.getAnimations = function () {
  55389. return this._runtimeAnimations;
  55390. };
  55391. /**
  55392. * Adds more animations to the current animatable
  55393. * @param target defines the target of the animations
  55394. * @param animations defines the new animations to add
  55395. */
  55396. Animatable.prototype.appendAnimations = function (target, animations) {
  55397. for (var index = 0; index < animations.length; index++) {
  55398. var animation = animations[index];
  55399. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  55400. }
  55401. };
  55402. /**
  55403. * Gets the source animation for a specific property
  55404. * @param property defines the propertyu to look for
  55405. * @returns null or the source animation for the given property
  55406. */
  55407. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  55408. var runtimeAnimations = this._runtimeAnimations;
  55409. for (var index = 0; index < runtimeAnimations.length; index++) {
  55410. if (runtimeAnimations[index].animation.targetProperty === property) {
  55411. return runtimeAnimations[index].animation;
  55412. }
  55413. }
  55414. return null;
  55415. };
  55416. /**
  55417. * Gets the runtime animation for a specific property
  55418. * @param property defines the propertyu to look for
  55419. * @returns null or the runtime animation for the given property
  55420. */
  55421. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  55422. var runtimeAnimations = this._runtimeAnimations;
  55423. for (var index = 0; index < runtimeAnimations.length; index++) {
  55424. if (runtimeAnimations[index].animation.targetProperty === property) {
  55425. return runtimeAnimations[index];
  55426. }
  55427. }
  55428. return null;
  55429. };
  55430. /**
  55431. * Resets the animatable to its original state
  55432. */
  55433. Animatable.prototype.reset = function () {
  55434. var runtimeAnimations = this._runtimeAnimations;
  55435. for (var index = 0; index < runtimeAnimations.length; index++) {
  55436. runtimeAnimations[index].reset(true);
  55437. }
  55438. this._localDelayOffset = null;
  55439. this._pausedDelay = null;
  55440. };
  55441. /**
  55442. * Allows the animatable to blend with current running animations
  55443. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55444. * @param blendingSpeed defines the blending speed to use
  55445. */
  55446. Animatable.prototype.enableBlending = function (blendingSpeed) {
  55447. var runtimeAnimations = this._runtimeAnimations;
  55448. for (var index = 0; index < runtimeAnimations.length; index++) {
  55449. runtimeAnimations[index].animation.enableBlending = true;
  55450. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  55451. }
  55452. };
  55453. /**
  55454. * Disable animation blending
  55455. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55456. */
  55457. Animatable.prototype.disableBlending = function () {
  55458. var runtimeAnimations = this._runtimeAnimations;
  55459. for (var index = 0; index < runtimeAnimations.length; index++) {
  55460. runtimeAnimations[index].animation.enableBlending = false;
  55461. }
  55462. };
  55463. /**
  55464. * Jump directly to a given frame
  55465. * @param frame defines the frame to jump to
  55466. */
  55467. Animatable.prototype.goToFrame = function (frame) {
  55468. var runtimeAnimations = this._runtimeAnimations;
  55469. if (runtimeAnimations[0]) {
  55470. var fps = runtimeAnimations[0].animation.framePerSecond;
  55471. var currentFrame = runtimeAnimations[0].currentFrame;
  55472. var adjustTime = frame - currentFrame;
  55473. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  55474. if (this._localDelayOffset === null) {
  55475. this._localDelayOffset = 0;
  55476. }
  55477. this._localDelayOffset -= delay;
  55478. }
  55479. for (var index = 0; index < runtimeAnimations.length; index++) {
  55480. runtimeAnimations[index].goToFrame(frame);
  55481. }
  55482. };
  55483. /**
  55484. * Pause the animation
  55485. */
  55486. Animatable.prototype.pause = function () {
  55487. if (this._paused) {
  55488. return;
  55489. }
  55490. this._paused = true;
  55491. };
  55492. /**
  55493. * Restart the animation
  55494. */
  55495. Animatable.prototype.restart = function () {
  55496. this._paused = false;
  55497. };
  55498. Animatable.prototype._raiseOnAnimationEnd = function () {
  55499. if (this.onAnimationEnd) {
  55500. this.onAnimationEnd();
  55501. }
  55502. this.onAnimationEndObservable.notifyObservers(this);
  55503. };
  55504. /**
  55505. * Stop and delete the current animation
  55506. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  55507. * @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)
  55508. */
  55509. Animatable.prototype.stop = function (animationName, targetMask) {
  55510. if (animationName || targetMask) {
  55511. var idx = this._scene._activeAnimatables.indexOf(this);
  55512. if (idx > -1) {
  55513. var runtimeAnimations = this._runtimeAnimations;
  55514. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  55515. var runtimeAnimation = runtimeAnimations[index];
  55516. if (animationName && runtimeAnimation.animation.name != animationName) {
  55517. continue;
  55518. }
  55519. if (targetMask && !targetMask(runtimeAnimation.target)) {
  55520. continue;
  55521. }
  55522. runtimeAnimation.dispose();
  55523. runtimeAnimations.splice(index, 1);
  55524. }
  55525. if (runtimeAnimations.length == 0) {
  55526. this._scene._activeAnimatables.splice(idx, 1);
  55527. this._raiseOnAnimationEnd();
  55528. }
  55529. }
  55530. }
  55531. else {
  55532. var index = this._scene._activeAnimatables.indexOf(this);
  55533. if (index > -1) {
  55534. this._scene._activeAnimatables.splice(index, 1);
  55535. var runtimeAnimations = this._runtimeAnimations;
  55536. for (var index = 0; index < runtimeAnimations.length; index++) {
  55537. runtimeAnimations[index].dispose();
  55538. }
  55539. this._raiseOnAnimationEnd();
  55540. }
  55541. }
  55542. };
  55543. /**
  55544. * Wait asynchronously for the animation to end
  55545. * @returns a promise which will be fullfilled when the animation ends
  55546. */
  55547. Animatable.prototype.waitAsync = function () {
  55548. var _this = this;
  55549. return new Promise(function (resolve, reject) {
  55550. _this.onAnimationEndObservable.add(function () {
  55551. resolve(_this);
  55552. }, undefined, undefined, _this, true);
  55553. });
  55554. };
  55555. /** @hidden */
  55556. Animatable.prototype._animate = function (delay) {
  55557. if (this._paused) {
  55558. this.animationStarted = false;
  55559. if (this._pausedDelay === null) {
  55560. this._pausedDelay = delay;
  55561. }
  55562. return true;
  55563. }
  55564. if (this._localDelayOffset === null) {
  55565. this._localDelayOffset = delay;
  55566. this._pausedDelay = null;
  55567. }
  55568. else if (this._pausedDelay !== null) {
  55569. this._localDelayOffset += delay - this._pausedDelay;
  55570. this._pausedDelay = null;
  55571. }
  55572. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  55573. return true;
  55574. }
  55575. // Animating
  55576. var running = false;
  55577. var runtimeAnimations = this._runtimeAnimations;
  55578. var index;
  55579. for (index = 0; index < runtimeAnimations.length; index++) {
  55580. var animation = runtimeAnimations[index];
  55581. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  55582. running = running || isRunning;
  55583. }
  55584. this.animationStarted = running;
  55585. if (!running) {
  55586. if (this.disposeOnEnd) {
  55587. // Remove from active animatables
  55588. index = this._scene._activeAnimatables.indexOf(this);
  55589. this._scene._activeAnimatables.splice(index, 1);
  55590. // Dispose all runtime animations
  55591. for (index = 0; index < runtimeAnimations.length; index++) {
  55592. runtimeAnimations[index].dispose();
  55593. }
  55594. }
  55595. this._raiseOnAnimationEnd();
  55596. if (this.disposeOnEnd) {
  55597. this.onAnimationEnd = null;
  55598. this.onAnimationEndObservable.clear();
  55599. }
  55600. }
  55601. return running;
  55602. };
  55603. return Animatable;
  55604. }());
  55605. BABYLON.Animatable = Animatable;
  55606. })(BABYLON || (BABYLON = {}));
  55607. //# sourceMappingURL=babylon.animatable.js.map
  55608. var BABYLON;
  55609. (function (BABYLON) {
  55610. /**
  55611. * Base class used for every default easing function.
  55612. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55613. */
  55614. var EasingFunction = /** @class */ (function () {
  55615. function EasingFunction() {
  55616. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  55617. }
  55618. /**
  55619. * Sets the easing mode of the current function.
  55620. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  55621. */
  55622. EasingFunction.prototype.setEasingMode = function (easingMode) {
  55623. var n = Math.min(Math.max(easingMode, 0), 2);
  55624. this._easingMode = n;
  55625. };
  55626. /**
  55627. * Gets the current easing mode.
  55628. * @returns the easing mode
  55629. */
  55630. EasingFunction.prototype.getEasingMode = function () {
  55631. return this._easingMode;
  55632. };
  55633. /**
  55634. * @hidden
  55635. */
  55636. EasingFunction.prototype.easeInCore = function (gradient) {
  55637. throw new Error('You must implement this method');
  55638. };
  55639. /**
  55640. * Given an input gradient between 0 and 1, this returns the corrseponding value
  55641. * of the easing function.
  55642. * @param gradient Defines the value between 0 and 1 we want the easing value for
  55643. * @returns the corresponding value on the curve defined by the easing function
  55644. */
  55645. EasingFunction.prototype.ease = function (gradient) {
  55646. switch (this._easingMode) {
  55647. case EasingFunction.EASINGMODE_EASEIN:
  55648. return this.easeInCore(gradient);
  55649. case EasingFunction.EASINGMODE_EASEOUT:
  55650. return (1 - this.easeInCore(1 - gradient));
  55651. }
  55652. if (gradient >= 0.5) {
  55653. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  55654. }
  55655. return (this.easeInCore(gradient * 2) * 0.5);
  55656. };
  55657. /**
  55658. * Interpolation follows the mathematical formula associated with the easing function.
  55659. */
  55660. EasingFunction.EASINGMODE_EASEIN = 0;
  55661. /**
  55662. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  55663. */
  55664. EasingFunction.EASINGMODE_EASEOUT = 1;
  55665. /**
  55666. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  55667. */
  55668. EasingFunction.EASINGMODE_EASEINOUT = 2;
  55669. return EasingFunction;
  55670. }());
  55671. BABYLON.EasingFunction = EasingFunction;
  55672. /**
  55673. * Easing function with a circle shape (see link below).
  55674. * @see https://easings.net/#easeInCirc
  55675. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55676. */
  55677. var CircleEase = /** @class */ (function (_super) {
  55678. __extends(CircleEase, _super);
  55679. function CircleEase() {
  55680. return _super !== null && _super.apply(this, arguments) || this;
  55681. }
  55682. /** @hidden */
  55683. CircleEase.prototype.easeInCore = function (gradient) {
  55684. gradient = Math.max(0, Math.min(1, gradient));
  55685. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  55686. };
  55687. return CircleEase;
  55688. }(EasingFunction));
  55689. BABYLON.CircleEase = CircleEase;
  55690. /**
  55691. * Easing function with a ease back shape (see link below).
  55692. * @see https://easings.net/#easeInBack
  55693. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55694. */
  55695. var BackEase = /** @class */ (function (_super) {
  55696. __extends(BackEase, _super);
  55697. /**
  55698. * Instantiates a back ease easing
  55699. * @see https://easings.net/#easeInBack
  55700. * @param amplitude Defines the amplitude of the function
  55701. */
  55702. function BackEase(
  55703. /** Defines the amplitude of the function */
  55704. amplitude) {
  55705. if (amplitude === void 0) { amplitude = 1; }
  55706. var _this = _super.call(this) || this;
  55707. _this.amplitude = amplitude;
  55708. return _this;
  55709. }
  55710. /** @hidden */
  55711. BackEase.prototype.easeInCore = function (gradient) {
  55712. var num = Math.max(0, this.amplitude);
  55713. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  55714. };
  55715. return BackEase;
  55716. }(EasingFunction));
  55717. BABYLON.BackEase = BackEase;
  55718. /**
  55719. * Easing function with a bouncing shape (see link below).
  55720. * @see https://easings.net/#easeInBounce
  55721. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55722. */
  55723. var BounceEase = /** @class */ (function (_super) {
  55724. __extends(BounceEase, _super);
  55725. /**
  55726. * Instantiates a bounce easing
  55727. * @see https://easings.net/#easeInBounce
  55728. * @param bounces Defines the number of bounces
  55729. * @param bounciness Defines the amplitude of the bounce
  55730. */
  55731. function BounceEase(
  55732. /** Defines the number of bounces */
  55733. bounces,
  55734. /** Defines the amplitude of the bounce */
  55735. bounciness) {
  55736. if (bounces === void 0) { bounces = 3; }
  55737. if (bounciness === void 0) { bounciness = 2; }
  55738. var _this = _super.call(this) || this;
  55739. _this.bounces = bounces;
  55740. _this.bounciness = bounciness;
  55741. return _this;
  55742. }
  55743. /** @hidden */
  55744. BounceEase.prototype.easeInCore = function (gradient) {
  55745. var y = Math.max(0.0, this.bounces);
  55746. var bounciness = this.bounciness;
  55747. if (bounciness <= 1.0) {
  55748. bounciness = 1.001;
  55749. }
  55750. var num9 = Math.pow(bounciness, y);
  55751. var num5 = 1.0 - bounciness;
  55752. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  55753. var num15 = gradient * num4;
  55754. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  55755. var num3 = Math.floor(num65);
  55756. var num13 = num3 + 1.0;
  55757. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  55758. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  55759. var num7 = (num8 + num12) * 0.5;
  55760. var num6 = gradient - num7;
  55761. var num2 = num7 - num8;
  55762. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  55763. };
  55764. return BounceEase;
  55765. }(EasingFunction));
  55766. BABYLON.BounceEase = BounceEase;
  55767. /**
  55768. * Easing function with a power of 3 shape (see link below).
  55769. * @see https://easings.net/#easeInCubic
  55770. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55771. */
  55772. var CubicEase = /** @class */ (function (_super) {
  55773. __extends(CubicEase, _super);
  55774. function CubicEase() {
  55775. return _super !== null && _super.apply(this, arguments) || this;
  55776. }
  55777. /** @hidden */
  55778. CubicEase.prototype.easeInCore = function (gradient) {
  55779. return (gradient * gradient * gradient);
  55780. };
  55781. return CubicEase;
  55782. }(EasingFunction));
  55783. BABYLON.CubicEase = CubicEase;
  55784. /**
  55785. * Easing function with an elastic shape (see link below).
  55786. * @see https://easings.net/#easeInElastic
  55787. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55788. */
  55789. var ElasticEase = /** @class */ (function (_super) {
  55790. __extends(ElasticEase, _super);
  55791. /**
  55792. * Instantiates an elastic easing function
  55793. * @see https://easings.net/#easeInElastic
  55794. * @param oscillations Defines the number of oscillations
  55795. * @param springiness Defines the amplitude of the oscillations
  55796. */
  55797. function ElasticEase(
  55798. /** Defines the number of oscillations*/
  55799. oscillations,
  55800. /** Defines the amplitude of the oscillations*/
  55801. springiness) {
  55802. if (oscillations === void 0) { oscillations = 3; }
  55803. if (springiness === void 0) { springiness = 3; }
  55804. var _this = _super.call(this) || this;
  55805. _this.oscillations = oscillations;
  55806. _this.springiness = springiness;
  55807. return _this;
  55808. }
  55809. /** @hidden */
  55810. ElasticEase.prototype.easeInCore = function (gradient) {
  55811. var num2;
  55812. var num3 = Math.max(0.0, this.oscillations);
  55813. var num = Math.max(0.0, this.springiness);
  55814. if (num == 0) {
  55815. num2 = gradient;
  55816. }
  55817. else {
  55818. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  55819. }
  55820. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  55821. };
  55822. return ElasticEase;
  55823. }(EasingFunction));
  55824. BABYLON.ElasticEase = ElasticEase;
  55825. /**
  55826. * Easing function with an exponential shape (see link below).
  55827. * @see https://easings.net/#easeInExpo
  55828. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55829. */
  55830. var ExponentialEase = /** @class */ (function (_super) {
  55831. __extends(ExponentialEase, _super);
  55832. /**
  55833. * Instantiates an exponential easing function
  55834. * @see https://easings.net/#easeInExpo
  55835. * @param exponent Defines the exponent of the function
  55836. */
  55837. function ExponentialEase(
  55838. /** Defines the exponent of the function */
  55839. exponent) {
  55840. if (exponent === void 0) { exponent = 2; }
  55841. var _this = _super.call(this) || this;
  55842. _this.exponent = exponent;
  55843. return _this;
  55844. }
  55845. /** @hidden */
  55846. ExponentialEase.prototype.easeInCore = function (gradient) {
  55847. if (this.exponent <= 0) {
  55848. return gradient;
  55849. }
  55850. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  55851. };
  55852. return ExponentialEase;
  55853. }(EasingFunction));
  55854. BABYLON.ExponentialEase = ExponentialEase;
  55855. /**
  55856. * Easing function with a power shape (see link below).
  55857. * @see https://easings.net/#easeInQuad
  55858. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55859. */
  55860. var PowerEase = /** @class */ (function (_super) {
  55861. __extends(PowerEase, _super);
  55862. /**
  55863. * Instantiates an power base easing function
  55864. * @see https://easings.net/#easeInQuad
  55865. * @param power Defines the power of the function
  55866. */
  55867. function PowerEase(
  55868. /** Defines the power of the function */
  55869. power) {
  55870. if (power === void 0) { power = 2; }
  55871. var _this = _super.call(this) || this;
  55872. _this.power = power;
  55873. return _this;
  55874. }
  55875. /** @hidden */
  55876. PowerEase.prototype.easeInCore = function (gradient) {
  55877. var y = Math.max(0.0, this.power);
  55878. return Math.pow(gradient, y);
  55879. };
  55880. return PowerEase;
  55881. }(EasingFunction));
  55882. BABYLON.PowerEase = PowerEase;
  55883. /**
  55884. * Easing function with a power of 2 shape (see link below).
  55885. * @see https://easings.net/#easeInQuad
  55886. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55887. */
  55888. var QuadraticEase = /** @class */ (function (_super) {
  55889. __extends(QuadraticEase, _super);
  55890. function QuadraticEase() {
  55891. return _super !== null && _super.apply(this, arguments) || this;
  55892. }
  55893. /** @hidden */
  55894. QuadraticEase.prototype.easeInCore = function (gradient) {
  55895. return (gradient * gradient);
  55896. };
  55897. return QuadraticEase;
  55898. }(EasingFunction));
  55899. BABYLON.QuadraticEase = QuadraticEase;
  55900. /**
  55901. * Easing function with a power of 4 shape (see link below).
  55902. * @see https://easings.net/#easeInQuart
  55903. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55904. */
  55905. var QuarticEase = /** @class */ (function (_super) {
  55906. __extends(QuarticEase, _super);
  55907. function QuarticEase() {
  55908. return _super !== null && _super.apply(this, arguments) || this;
  55909. }
  55910. /** @hidden */
  55911. QuarticEase.prototype.easeInCore = function (gradient) {
  55912. return (gradient * gradient * gradient * gradient);
  55913. };
  55914. return QuarticEase;
  55915. }(EasingFunction));
  55916. BABYLON.QuarticEase = QuarticEase;
  55917. /**
  55918. * Easing function with a power of 5 shape (see link below).
  55919. * @see https://easings.net/#easeInQuint
  55920. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55921. */
  55922. var QuinticEase = /** @class */ (function (_super) {
  55923. __extends(QuinticEase, _super);
  55924. function QuinticEase() {
  55925. return _super !== null && _super.apply(this, arguments) || this;
  55926. }
  55927. /** @hidden */
  55928. QuinticEase.prototype.easeInCore = function (gradient) {
  55929. return (gradient * gradient * gradient * gradient * gradient);
  55930. };
  55931. return QuinticEase;
  55932. }(EasingFunction));
  55933. BABYLON.QuinticEase = QuinticEase;
  55934. /**
  55935. * Easing function with a sin shape (see link below).
  55936. * @see https://easings.net/#easeInSine
  55937. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55938. */
  55939. var SineEase = /** @class */ (function (_super) {
  55940. __extends(SineEase, _super);
  55941. function SineEase() {
  55942. return _super !== null && _super.apply(this, arguments) || this;
  55943. }
  55944. /** @hidden */
  55945. SineEase.prototype.easeInCore = function (gradient) {
  55946. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  55947. };
  55948. return SineEase;
  55949. }(EasingFunction));
  55950. BABYLON.SineEase = SineEase;
  55951. /**
  55952. * Easing function with a bezier shape (see link below).
  55953. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55954. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55955. */
  55956. var BezierCurveEase = /** @class */ (function (_super) {
  55957. __extends(BezierCurveEase, _super);
  55958. /**
  55959. * Instantiates a bezier function
  55960. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  55961. * @param x1 Defines the x component of the start tangent in the bezier curve
  55962. * @param y1 Defines the y component of the start tangent in the bezier curve
  55963. * @param x2 Defines the x component of the end tangent in the bezier curve
  55964. * @param y2 Defines the y component of the end tangent in the bezier curve
  55965. */
  55966. function BezierCurveEase(
  55967. /** Defines the x component of the start tangent in the bezier curve */
  55968. x1,
  55969. /** Defines the y component of the start tangent in the bezier curve */
  55970. y1,
  55971. /** Defines the x component of the end tangent in the bezier curve */
  55972. x2,
  55973. /** Defines the y component of the end tangent in the bezier curve */
  55974. y2) {
  55975. if (x1 === void 0) { x1 = 0; }
  55976. if (y1 === void 0) { y1 = 0; }
  55977. if (x2 === void 0) { x2 = 1; }
  55978. if (y2 === void 0) { y2 = 1; }
  55979. var _this = _super.call(this) || this;
  55980. _this.x1 = x1;
  55981. _this.y1 = y1;
  55982. _this.x2 = x2;
  55983. _this.y2 = y2;
  55984. return _this;
  55985. }
  55986. /** @hidden */
  55987. BezierCurveEase.prototype.easeInCore = function (gradient) {
  55988. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  55989. };
  55990. return BezierCurveEase;
  55991. }(EasingFunction));
  55992. BABYLON.BezierCurveEase = BezierCurveEase;
  55993. })(BABYLON || (BABYLON = {}));
  55994. //# sourceMappingURL=babylon.easing.js.map
  55995. var BABYLON;
  55996. (function (BABYLON) {
  55997. /**
  55998. * A Condition applied to an Action
  55999. */
  56000. var Condition = /** @class */ (function () {
  56001. /**
  56002. * Creates a new Condition
  56003. * @param actionManager the manager of the action the condition is applied to
  56004. */
  56005. function Condition(actionManager) {
  56006. this._actionManager = actionManager;
  56007. }
  56008. /**
  56009. * Check if the current condition is valid
  56010. * @returns a boolean
  56011. */
  56012. Condition.prototype.isValid = function () {
  56013. return true;
  56014. };
  56015. /**
  56016. * Internal only
  56017. * @hidden
  56018. */
  56019. Condition.prototype._getProperty = function (propertyPath) {
  56020. return this._actionManager._getProperty(propertyPath);
  56021. };
  56022. /**
  56023. * Internal only
  56024. * @hidden
  56025. */
  56026. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  56027. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56028. };
  56029. /**
  56030. * Serialize placeholder for child classes
  56031. * @returns the serialized object
  56032. */
  56033. Condition.prototype.serialize = function () {
  56034. };
  56035. /**
  56036. * Internal only
  56037. * @hidden
  56038. */
  56039. Condition.prototype._serialize = function (serializedCondition) {
  56040. return {
  56041. type: 2,
  56042. children: [],
  56043. name: serializedCondition.name,
  56044. properties: serializedCondition.properties
  56045. };
  56046. };
  56047. return Condition;
  56048. }());
  56049. BABYLON.Condition = Condition;
  56050. /**
  56051. * Defines specific conditional operators as extensions of Condition
  56052. */
  56053. var ValueCondition = /** @class */ (function (_super) {
  56054. __extends(ValueCondition, _super);
  56055. /**
  56056. * Creates a new ValueCondition
  56057. * @param actionManager manager for the action the condition applies to
  56058. * @param target for the action
  56059. * @param propertyPath path to specify the property of the target the conditional operator uses
  56060. * @param value the value compared by the conditional operator against the current value of the property
  56061. * @param operator the conditional operator, default ValueCondition.IsEqual
  56062. */
  56063. function ValueCondition(actionManager, target,
  56064. /** path to specify the property of the target the conditional operator uses */
  56065. propertyPath,
  56066. /** the value compared by the conditional operator against the current value of the property */
  56067. value,
  56068. /** the conditional operator, default ValueCondition.IsEqual */
  56069. operator) {
  56070. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  56071. var _this = _super.call(this, actionManager) || this;
  56072. _this.propertyPath = propertyPath;
  56073. _this.value = value;
  56074. _this.operator = operator;
  56075. _this._target = target;
  56076. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  56077. _this._property = _this._getProperty(_this.propertyPath);
  56078. return _this;
  56079. }
  56080. Object.defineProperty(ValueCondition, "IsEqual", {
  56081. /**
  56082. * returns the number for IsEqual
  56083. */
  56084. get: function () {
  56085. return ValueCondition._IsEqual;
  56086. },
  56087. enumerable: true,
  56088. configurable: true
  56089. });
  56090. Object.defineProperty(ValueCondition, "IsDifferent", {
  56091. /**
  56092. * Returns the number for IsDifferent
  56093. */
  56094. get: function () {
  56095. return ValueCondition._IsDifferent;
  56096. },
  56097. enumerable: true,
  56098. configurable: true
  56099. });
  56100. Object.defineProperty(ValueCondition, "IsGreater", {
  56101. /**
  56102. * Returns the number for IsGreater
  56103. */
  56104. get: function () {
  56105. return ValueCondition._IsGreater;
  56106. },
  56107. enumerable: true,
  56108. configurable: true
  56109. });
  56110. Object.defineProperty(ValueCondition, "IsLesser", {
  56111. /**
  56112. * Returns the number for IsLesser
  56113. */
  56114. get: function () {
  56115. return ValueCondition._IsLesser;
  56116. },
  56117. enumerable: true,
  56118. configurable: true
  56119. });
  56120. /**
  56121. * Compares the given value with the property value for the specified conditional operator
  56122. * @returns the result of the comparison
  56123. */
  56124. ValueCondition.prototype.isValid = function () {
  56125. switch (this.operator) {
  56126. case ValueCondition.IsGreater:
  56127. return this._effectiveTarget[this._property] > this.value;
  56128. case ValueCondition.IsLesser:
  56129. return this._effectiveTarget[this._property] < this.value;
  56130. case ValueCondition.IsEqual:
  56131. case ValueCondition.IsDifferent:
  56132. var check;
  56133. if (this.value.equals) {
  56134. check = this.value.equals(this._effectiveTarget[this._property]);
  56135. }
  56136. else {
  56137. check = this.value === this._effectiveTarget[this._property];
  56138. }
  56139. return this.operator === ValueCondition.IsEqual ? check : !check;
  56140. }
  56141. return false;
  56142. };
  56143. /**
  56144. * Serialize the ValueCondition into a JSON compatible object
  56145. * @returns serialization object
  56146. */
  56147. ValueCondition.prototype.serialize = function () {
  56148. return this._serialize({
  56149. name: "ValueCondition",
  56150. properties: [
  56151. BABYLON.Action._GetTargetProperty(this._target),
  56152. { name: "propertyPath", value: this.propertyPath },
  56153. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56154. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  56155. ]
  56156. });
  56157. };
  56158. /**
  56159. * Gets the name of the conditional operator for the ValueCondition
  56160. * @param operator the conditional operator
  56161. * @returns the name
  56162. */
  56163. ValueCondition.GetOperatorName = function (operator) {
  56164. switch (operator) {
  56165. case ValueCondition._IsEqual: return "IsEqual";
  56166. case ValueCondition._IsDifferent: return "IsDifferent";
  56167. case ValueCondition._IsGreater: return "IsGreater";
  56168. case ValueCondition._IsLesser: return "IsLesser";
  56169. default: return "";
  56170. }
  56171. };
  56172. /**
  56173. * Internal only
  56174. * @hidden
  56175. */
  56176. ValueCondition._IsEqual = 0;
  56177. /**
  56178. * Internal only
  56179. * @hidden
  56180. */
  56181. ValueCondition._IsDifferent = 1;
  56182. /**
  56183. * Internal only
  56184. * @hidden
  56185. */
  56186. ValueCondition._IsGreater = 2;
  56187. /**
  56188. * Internal only
  56189. * @hidden
  56190. */
  56191. ValueCondition._IsLesser = 3;
  56192. return ValueCondition;
  56193. }(Condition));
  56194. BABYLON.ValueCondition = ValueCondition;
  56195. /**
  56196. * Defines a predicate condition as an extension of Condition
  56197. */
  56198. var PredicateCondition = /** @class */ (function (_super) {
  56199. __extends(PredicateCondition, _super);
  56200. /**
  56201. * Creates a new PredicateCondition
  56202. * @param actionManager manager for the action the condition applies to
  56203. * @param predicate defines the predicate function used to validate the condition
  56204. */
  56205. function PredicateCondition(actionManager,
  56206. /** defines the predicate function used to validate the condition */
  56207. predicate) {
  56208. var _this = _super.call(this, actionManager) || this;
  56209. _this.predicate = predicate;
  56210. return _this;
  56211. }
  56212. /**
  56213. * @returns the validity of the predicate condition
  56214. */
  56215. PredicateCondition.prototype.isValid = function () {
  56216. return this.predicate();
  56217. };
  56218. return PredicateCondition;
  56219. }(Condition));
  56220. BABYLON.PredicateCondition = PredicateCondition;
  56221. /**
  56222. * Defines a state condition as an extension of Condition
  56223. */
  56224. var StateCondition = /** @class */ (function (_super) {
  56225. __extends(StateCondition, _super);
  56226. /**
  56227. * Creates a new StateCondition
  56228. * @param actionManager manager for the action the condition applies to
  56229. * @param target of the condition
  56230. * @param value to compare with target state
  56231. */
  56232. function StateCondition(actionManager, target,
  56233. /** Value to compare with target state */
  56234. value) {
  56235. var _this = _super.call(this, actionManager) || this;
  56236. _this.value = value;
  56237. _this._target = target;
  56238. return _this;
  56239. }
  56240. /**
  56241. * Gets a boolean indicating if the current condition is met
  56242. * @returns the validity of the state
  56243. */
  56244. StateCondition.prototype.isValid = function () {
  56245. return this._target.state === this.value;
  56246. };
  56247. /**
  56248. * Serialize the StateCondition into a JSON compatible object
  56249. * @returns serialization object
  56250. */
  56251. StateCondition.prototype.serialize = function () {
  56252. return this._serialize({
  56253. name: "StateCondition",
  56254. properties: [
  56255. BABYLON.Action._GetTargetProperty(this._target),
  56256. { name: "value", value: this.value }
  56257. ]
  56258. });
  56259. };
  56260. return StateCondition;
  56261. }(Condition));
  56262. BABYLON.StateCondition = StateCondition;
  56263. })(BABYLON || (BABYLON = {}));
  56264. //# sourceMappingURL=babylon.condition.js.map
  56265. var BABYLON;
  56266. (function (BABYLON) {
  56267. /**
  56268. * The action to be carried out following a trigger
  56269. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  56270. */
  56271. var Action = /** @class */ (function () {
  56272. /**
  56273. * Creates a new Action
  56274. * @param triggerOptions the trigger, with or without parameters, for the action
  56275. * @param condition an optional determinant of action
  56276. */
  56277. function Action(
  56278. /** the trigger, with or without parameters, for the action */
  56279. triggerOptions, condition) {
  56280. this.triggerOptions = triggerOptions;
  56281. /**
  56282. * An event triggered prior to action being executed.
  56283. */
  56284. this.onBeforeExecuteObservable = new BABYLON.Observable();
  56285. if (triggerOptions.parameter) {
  56286. this.trigger = triggerOptions.trigger;
  56287. this._triggerParameter = triggerOptions.parameter;
  56288. }
  56289. else if (triggerOptions.trigger) {
  56290. this.trigger = triggerOptions.trigger;
  56291. }
  56292. else {
  56293. this.trigger = triggerOptions;
  56294. }
  56295. this._nextActiveAction = this;
  56296. this._condition = condition;
  56297. }
  56298. /**
  56299. * Internal only
  56300. * @hidden
  56301. */
  56302. Action.prototype._prepare = function () {
  56303. };
  56304. /**
  56305. * Gets the trigger parameters
  56306. * @returns the trigger parameters
  56307. */
  56308. Action.prototype.getTriggerParameter = function () {
  56309. return this._triggerParameter;
  56310. };
  56311. /**
  56312. * Internal only - executes current action event
  56313. * @hidden
  56314. */
  56315. Action.prototype._executeCurrent = function (evt) {
  56316. if (this._nextActiveAction._condition) {
  56317. var condition = this._nextActiveAction._condition;
  56318. var currentRenderId = this._actionManager.getScene().getRenderId();
  56319. // We cache the current evaluation for the current frame
  56320. if (condition._evaluationId === currentRenderId) {
  56321. if (!condition._currentResult) {
  56322. return;
  56323. }
  56324. }
  56325. else {
  56326. condition._evaluationId = currentRenderId;
  56327. if (!condition.isValid()) {
  56328. condition._currentResult = false;
  56329. return;
  56330. }
  56331. condition._currentResult = true;
  56332. }
  56333. }
  56334. this.onBeforeExecuteObservable.notifyObservers(this);
  56335. this._nextActiveAction.execute(evt);
  56336. this.skipToNextActiveAction();
  56337. };
  56338. /**
  56339. * Execute placeholder for child classes
  56340. * @param evt optional action event
  56341. */
  56342. Action.prototype.execute = function (evt) {
  56343. };
  56344. /**
  56345. * Skips to next active action
  56346. */
  56347. Action.prototype.skipToNextActiveAction = function () {
  56348. if (this._nextActiveAction._child) {
  56349. if (!this._nextActiveAction._child._actionManager) {
  56350. this._nextActiveAction._child._actionManager = this._actionManager;
  56351. }
  56352. this._nextActiveAction = this._nextActiveAction._child;
  56353. }
  56354. else {
  56355. this._nextActiveAction = this;
  56356. }
  56357. };
  56358. /**
  56359. * Adds action to chain of actions, may be a DoNothingAction
  56360. * @param action defines the next action to execute
  56361. * @returns The action passed in
  56362. * @see https://www.babylonjs-playground.com/#1T30HR#0
  56363. */
  56364. Action.prototype.then = function (action) {
  56365. this._child = action;
  56366. action._actionManager = this._actionManager;
  56367. action._prepare();
  56368. return action;
  56369. };
  56370. /**
  56371. * Internal only
  56372. * @hidden
  56373. */
  56374. Action.prototype._getProperty = function (propertyPath) {
  56375. return this._actionManager._getProperty(propertyPath);
  56376. };
  56377. /**
  56378. * Internal only
  56379. * @hidden
  56380. */
  56381. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  56382. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56383. };
  56384. /**
  56385. * Serialize placeholder for child classes
  56386. * @param parent of child
  56387. * @returns the serialized object
  56388. */
  56389. Action.prototype.serialize = function (parent) {
  56390. };
  56391. /**
  56392. * Internal only called by serialize
  56393. * @hidden
  56394. */
  56395. Action.prototype._serialize = function (serializedAction, parent) {
  56396. var serializationObject = {
  56397. type: 1,
  56398. children: [],
  56399. name: serializedAction.name,
  56400. properties: serializedAction.properties || []
  56401. };
  56402. // Serialize child
  56403. if (this._child) {
  56404. this._child.serialize(serializationObject);
  56405. }
  56406. // Check if "this" has a condition
  56407. if (this._condition) {
  56408. var serializedCondition = this._condition.serialize();
  56409. serializedCondition.children.push(serializationObject);
  56410. if (parent) {
  56411. parent.children.push(serializedCondition);
  56412. }
  56413. return serializedCondition;
  56414. }
  56415. if (parent) {
  56416. parent.children.push(serializationObject);
  56417. }
  56418. return serializationObject;
  56419. };
  56420. /**
  56421. * Internal only
  56422. * @hidden
  56423. */
  56424. Action._SerializeValueAsString = function (value) {
  56425. if (typeof value === "number") {
  56426. return value.toString();
  56427. }
  56428. if (typeof value === "boolean") {
  56429. return value ? "true" : "false";
  56430. }
  56431. if (value instanceof BABYLON.Vector2) {
  56432. return value.x + ", " + value.y;
  56433. }
  56434. if (value instanceof BABYLON.Vector3) {
  56435. return value.x + ", " + value.y + ", " + value.z;
  56436. }
  56437. if (value instanceof BABYLON.Color3) {
  56438. return value.r + ", " + value.g + ", " + value.b;
  56439. }
  56440. if (value instanceof BABYLON.Color4) {
  56441. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  56442. }
  56443. return value; // string
  56444. };
  56445. /**
  56446. * Internal only
  56447. * @hidden
  56448. */
  56449. Action._GetTargetProperty = function (target) {
  56450. return {
  56451. name: "target",
  56452. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  56453. : target instanceof BABYLON.Light ? "LightProperties"
  56454. : target instanceof BABYLON.Camera ? "CameraProperties"
  56455. : "SceneProperties",
  56456. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  56457. };
  56458. };
  56459. return Action;
  56460. }());
  56461. BABYLON.Action = Action;
  56462. })(BABYLON || (BABYLON = {}));
  56463. //# sourceMappingURL=babylon.action.js.map
  56464. var BABYLON;
  56465. (function (BABYLON) {
  56466. /**
  56467. * ActionEvent is the event being sent when an action is triggered.
  56468. */
  56469. var ActionEvent = /** @class */ (function () {
  56470. /**
  56471. * Creates a new ActionEvent
  56472. * @param source The mesh or sprite that triggered the action
  56473. * @param pointerX The X mouse cursor position at the time of the event
  56474. * @param pointerY The Y mouse cursor position at the time of the event
  56475. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  56476. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  56477. * @param additionalData additional data for the event
  56478. */
  56479. function ActionEvent(
  56480. /** The mesh or sprite that triggered the action */
  56481. source,
  56482. /** The X mouse cursor position at the time of the event */
  56483. pointerX,
  56484. /** The Y mouse cursor position at the time of the event */
  56485. pointerY,
  56486. /** The mesh that is currently pointed at (can be null) */
  56487. meshUnderPointer,
  56488. /** the original (browser) event that triggered the ActionEvent */
  56489. sourceEvent,
  56490. /** additional data for the event */
  56491. additionalData) {
  56492. this.source = source;
  56493. this.pointerX = pointerX;
  56494. this.pointerY = pointerY;
  56495. this.meshUnderPointer = meshUnderPointer;
  56496. this.sourceEvent = sourceEvent;
  56497. this.additionalData = additionalData;
  56498. }
  56499. /**
  56500. * Helper function to auto-create an ActionEvent from a source mesh.
  56501. * @param source The source mesh that triggered the event
  56502. * @param evt The original (browser) event
  56503. * @param additionalData additional data for the event
  56504. * @returns the new ActionEvent
  56505. */
  56506. ActionEvent.CreateNew = function (source, evt, additionalData) {
  56507. var scene = source.getScene();
  56508. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56509. };
  56510. /**
  56511. * Helper function to auto-create an ActionEvent from a source sprite
  56512. * @param source The source sprite that triggered the event
  56513. * @param scene Scene associated with the sprite
  56514. * @param evt The original (browser) event
  56515. * @param additionalData additional data for the event
  56516. * @returns the new ActionEvent
  56517. */
  56518. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  56519. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56520. };
  56521. /**
  56522. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  56523. * @param scene the scene where the event occurred
  56524. * @param evt The original (browser) event
  56525. * @returns the new ActionEvent
  56526. */
  56527. ActionEvent.CreateNewFromScene = function (scene, evt) {
  56528. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  56529. };
  56530. /**
  56531. * Helper function to auto-create an ActionEvent from a primitive
  56532. * @param prim defines the target primitive
  56533. * @param pointerPos defines the pointer position
  56534. * @param evt The original (browser) event
  56535. * @param additionalData additional data for the event
  56536. * @returns the new ActionEvent
  56537. */
  56538. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  56539. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  56540. };
  56541. return ActionEvent;
  56542. }());
  56543. BABYLON.ActionEvent = ActionEvent;
  56544. /**
  56545. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  56546. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  56547. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56548. */
  56549. var ActionManager = /** @class */ (function () {
  56550. /**
  56551. * Creates a new action manager
  56552. * @param scene defines the hosting scene
  56553. */
  56554. function ActionManager(scene) {
  56555. // Members
  56556. /** Gets the list of actions */
  56557. this.actions = new Array();
  56558. /** Gets the cursor to use when hovering items */
  56559. this.hoverCursor = '';
  56560. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56561. scene.actionManagers.push(this);
  56562. }
  56563. // Methods
  56564. /**
  56565. * Releases all associated resources
  56566. */
  56567. ActionManager.prototype.dispose = function () {
  56568. var index = this._scene.actionManagers.indexOf(this);
  56569. for (var i = 0; i < this.actions.length; i++) {
  56570. var action = this.actions[i];
  56571. ActionManager.Triggers[action.trigger]--;
  56572. if (ActionManager.Triggers[action.trigger] === 0) {
  56573. delete ActionManager.Triggers[action.trigger];
  56574. }
  56575. }
  56576. if (index > -1) {
  56577. this._scene.actionManagers.splice(index, 1);
  56578. }
  56579. };
  56580. /**
  56581. * Gets hosting scene
  56582. * @returns the hosting scene
  56583. */
  56584. ActionManager.prototype.getScene = function () {
  56585. return this._scene;
  56586. };
  56587. /**
  56588. * Does this action manager handles actions of any of the given triggers
  56589. * @param triggers defines the triggers to be tested
  56590. * @return a boolean indicating whether one (or more) of the triggers is handled
  56591. */
  56592. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  56593. for (var index = 0; index < this.actions.length; index++) {
  56594. var action = this.actions[index];
  56595. if (triggers.indexOf(action.trigger) > -1) {
  56596. return true;
  56597. }
  56598. }
  56599. return false;
  56600. };
  56601. /**
  56602. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  56603. * speed.
  56604. * @param triggerA defines the trigger to be tested
  56605. * @param triggerB defines the trigger to be tested
  56606. * @return a boolean indicating whether one (or more) of the triggers is handled
  56607. */
  56608. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  56609. for (var index = 0; index < this.actions.length; index++) {
  56610. var action = this.actions[index];
  56611. if (triggerA == action.trigger || triggerB == action.trigger) {
  56612. return true;
  56613. }
  56614. }
  56615. return false;
  56616. };
  56617. /**
  56618. * Does this action manager handles actions of a given trigger
  56619. * @param trigger defines the trigger to be tested
  56620. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  56621. * @return whether the trigger is handled
  56622. */
  56623. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  56624. for (var index = 0; index < this.actions.length; index++) {
  56625. var action = this.actions[index];
  56626. if (action.trigger === trigger) {
  56627. if (parameterPredicate) {
  56628. if (parameterPredicate(action.getTriggerParameter())) {
  56629. return true;
  56630. }
  56631. }
  56632. else {
  56633. return true;
  56634. }
  56635. }
  56636. }
  56637. return false;
  56638. };
  56639. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  56640. /**
  56641. * Does this action manager has pointer triggers
  56642. */
  56643. get: function () {
  56644. for (var index = 0; index < this.actions.length; index++) {
  56645. var action = this.actions[index];
  56646. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  56647. return true;
  56648. }
  56649. }
  56650. return false;
  56651. },
  56652. enumerable: true,
  56653. configurable: true
  56654. });
  56655. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  56656. /**
  56657. * Does this action manager has pick triggers
  56658. */
  56659. get: function () {
  56660. for (var index = 0; index < this.actions.length; index++) {
  56661. var action = this.actions[index];
  56662. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  56663. return true;
  56664. }
  56665. }
  56666. return false;
  56667. },
  56668. enumerable: true,
  56669. configurable: true
  56670. });
  56671. Object.defineProperty(ActionManager, "HasTriggers", {
  56672. /**
  56673. * Does exist one action manager with at least one trigger
  56674. **/
  56675. get: function () {
  56676. for (var t in ActionManager.Triggers) {
  56677. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56678. return true;
  56679. }
  56680. }
  56681. return false;
  56682. },
  56683. enumerable: true,
  56684. configurable: true
  56685. });
  56686. Object.defineProperty(ActionManager, "HasPickTriggers", {
  56687. /**
  56688. * Does exist one action manager with at least one pick trigger
  56689. **/
  56690. get: function () {
  56691. for (var t in ActionManager.Triggers) {
  56692. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56693. var t_int = parseInt(t);
  56694. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  56695. return true;
  56696. }
  56697. }
  56698. }
  56699. return false;
  56700. },
  56701. enumerable: true,
  56702. configurable: true
  56703. });
  56704. /**
  56705. * Does exist one action manager that handles actions of a given trigger
  56706. * @param trigger defines the trigger to be tested
  56707. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  56708. **/
  56709. ActionManager.HasSpecificTrigger = function (trigger) {
  56710. for (var t in ActionManager.Triggers) {
  56711. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56712. var t_int = parseInt(t);
  56713. if (t_int === trigger) {
  56714. return true;
  56715. }
  56716. }
  56717. }
  56718. return false;
  56719. };
  56720. /**
  56721. * Registers an action to this action manager
  56722. * @param action defines the action to be registered
  56723. * @return the action amended (prepared) after registration
  56724. */
  56725. ActionManager.prototype.registerAction = function (action) {
  56726. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  56727. if (this.getScene().actionManager !== this) {
  56728. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  56729. return null;
  56730. }
  56731. }
  56732. this.actions.push(action);
  56733. if (ActionManager.Triggers[action.trigger]) {
  56734. ActionManager.Triggers[action.trigger]++;
  56735. }
  56736. else {
  56737. ActionManager.Triggers[action.trigger] = 1;
  56738. }
  56739. action._actionManager = this;
  56740. action._prepare();
  56741. return action;
  56742. };
  56743. /**
  56744. * Unregisters an action to this action manager
  56745. * @param action defines the action to be unregistered
  56746. * @return a boolean indicating whether the action has been unregistered
  56747. */
  56748. ActionManager.prototype.unregisterAction = function (action) {
  56749. var index = this.actions.indexOf(action);
  56750. if (index !== -1) {
  56751. this.actions.splice(index, 1);
  56752. ActionManager.Triggers[action.trigger] -= 1;
  56753. if (ActionManager.Triggers[action.trigger] === 0) {
  56754. delete ActionManager.Triggers[action.trigger];
  56755. }
  56756. delete action._actionManager;
  56757. return true;
  56758. }
  56759. return false;
  56760. };
  56761. /**
  56762. * Process a specific trigger
  56763. * @param trigger defines the trigger to process
  56764. * @param evt defines the event details to be processed
  56765. */
  56766. ActionManager.prototype.processTrigger = function (trigger, evt) {
  56767. for (var index = 0; index < this.actions.length; index++) {
  56768. var action = this.actions[index];
  56769. if (action.trigger === trigger) {
  56770. if (evt) {
  56771. if (trigger === ActionManager.OnKeyUpTrigger
  56772. || trigger === ActionManager.OnKeyDownTrigger) {
  56773. var parameter = action.getTriggerParameter();
  56774. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  56775. if (!parameter.toLowerCase) {
  56776. continue;
  56777. }
  56778. var lowerCase = parameter.toLowerCase();
  56779. if (lowerCase !== evt.sourceEvent.key) {
  56780. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  56781. var actualkey = String.fromCharCode(unicode).toLowerCase();
  56782. if (actualkey !== lowerCase) {
  56783. continue;
  56784. }
  56785. }
  56786. }
  56787. }
  56788. }
  56789. action._executeCurrent(evt);
  56790. }
  56791. }
  56792. };
  56793. /** @hidden */
  56794. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  56795. var properties = propertyPath.split(".");
  56796. for (var index = 0; index < properties.length - 1; index++) {
  56797. target = target[properties[index]];
  56798. }
  56799. return target;
  56800. };
  56801. /** @hidden */
  56802. ActionManager.prototype._getProperty = function (propertyPath) {
  56803. var properties = propertyPath.split(".");
  56804. return properties[properties.length - 1];
  56805. };
  56806. /**
  56807. * Serialize this manager to a JSON object
  56808. * @param name defines the property name to store this manager
  56809. * @returns a JSON representation of this manager
  56810. */
  56811. ActionManager.prototype.serialize = function (name) {
  56812. var root = {
  56813. children: new Array(),
  56814. name: name,
  56815. type: 3,
  56816. properties: new Array() // Empty for root but required
  56817. };
  56818. for (var i = 0; i < this.actions.length; i++) {
  56819. var triggerObject = {
  56820. type: 0,
  56821. children: new Array(),
  56822. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  56823. properties: new Array()
  56824. };
  56825. var triggerOptions = this.actions[i].triggerOptions;
  56826. if (triggerOptions && typeof triggerOptions !== "number") {
  56827. if (triggerOptions.parameter instanceof BABYLON.Node) {
  56828. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  56829. }
  56830. else {
  56831. var parameter = {};
  56832. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  56833. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  56834. parameter._meshId = triggerOptions.parameter.mesh.id;
  56835. }
  56836. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  56837. }
  56838. }
  56839. // Serialize child action, recursively
  56840. this.actions[i].serialize(triggerObject);
  56841. // Add serialized trigger
  56842. root.children.push(triggerObject);
  56843. }
  56844. return root;
  56845. };
  56846. /**
  56847. * Creates a new ActionManager from a JSON data
  56848. * @param parsedActions defines the JSON data to read from
  56849. * @param object defines the hosting mesh
  56850. * @param scene defines the hosting scene
  56851. */
  56852. ActionManager.Parse = function (parsedActions, object, scene) {
  56853. var actionManager = new ActionManager(scene);
  56854. if (object === null) {
  56855. scene.actionManager = actionManager;
  56856. }
  56857. else {
  56858. object.actionManager = actionManager;
  56859. }
  56860. // instanciate a new object
  56861. var instanciate = function (name, params) {
  56862. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  56863. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  56864. newInstance.constructor.apply(newInstance, params);
  56865. return newInstance;
  56866. };
  56867. var parseParameter = function (name, value, target, propertyPath) {
  56868. if (propertyPath === null) {
  56869. // String, boolean or float
  56870. var floatValue = parseFloat(value);
  56871. if (value === "true" || value === "false") {
  56872. return value === "true";
  56873. }
  56874. else {
  56875. return isNaN(floatValue) ? value : floatValue;
  56876. }
  56877. }
  56878. var effectiveTarget = propertyPath.split(".");
  56879. var values = value.split(",");
  56880. // Get effective Target
  56881. for (var i = 0; i < effectiveTarget.length; i++) {
  56882. target = target[effectiveTarget[i]];
  56883. }
  56884. // Return appropriate value with its type
  56885. if (typeof (target) === "boolean") {
  56886. return values[0] === "true";
  56887. }
  56888. if (typeof (target) === "string") {
  56889. return values[0];
  56890. }
  56891. // Parameters with multiple values such as Vector3 etc.
  56892. var split = new Array();
  56893. for (var i = 0; i < values.length; i++) {
  56894. split.push(parseFloat(values[i]));
  56895. }
  56896. if (target instanceof BABYLON.Vector3) {
  56897. return BABYLON.Vector3.FromArray(split);
  56898. }
  56899. if (target instanceof BABYLON.Vector4) {
  56900. return BABYLON.Vector4.FromArray(split);
  56901. }
  56902. if (target instanceof BABYLON.Color3) {
  56903. return BABYLON.Color3.FromArray(split);
  56904. }
  56905. if (target instanceof BABYLON.Color4) {
  56906. return BABYLON.Color4.FromArray(split);
  56907. }
  56908. return parseFloat(values[0]);
  56909. };
  56910. // traverse graph per trigger
  56911. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  56912. if (combineArray === void 0) { combineArray = null; }
  56913. if (parsedAction.detached) {
  56914. return;
  56915. }
  56916. var parameters = new Array();
  56917. var target = null;
  56918. var propertyPath = null;
  56919. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  56920. // Parameters
  56921. if (parsedAction.type === 2) {
  56922. parameters.push(actionManager);
  56923. }
  56924. else {
  56925. parameters.push(trigger);
  56926. }
  56927. if (combine) {
  56928. var actions = new Array();
  56929. for (var j = 0; j < parsedAction.combine.length; j++) {
  56930. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  56931. }
  56932. parameters.push(actions);
  56933. }
  56934. else {
  56935. for (var i = 0; i < parsedAction.properties.length; i++) {
  56936. var value = parsedAction.properties[i].value;
  56937. var name = parsedAction.properties[i].name;
  56938. var targetType = parsedAction.properties[i].targetType;
  56939. if (name === "target") {
  56940. if (targetType !== null && targetType === "SceneProperties") {
  56941. value = target = scene;
  56942. }
  56943. else {
  56944. value = target = scene.getNodeByName(value);
  56945. }
  56946. }
  56947. else if (name === "parent") {
  56948. value = scene.getNodeByName(value);
  56949. }
  56950. else if (name === "sound") {
  56951. // Can not externalize to component, so only checks for the presence off the API.
  56952. if (scene.getSoundByName) {
  56953. value = scene.getSoundByName(value);
  56954. }
  56955. }
  56956. else if (name !== "propertyPath") {
  56957. if (parsedAction.type === 2 && name === "operator") {
  56958. value = BABYLON.ValueCondition[value];
  56959. }
  56960. else {
  56961. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  56962. }
  56963. }
  56964. else {
  56965. propertyPath = value;
  56966. }
  56967. parameters.push(value);
  56968. }
  56969. }
  56970. if (combineArray === null) {
  56971. parameters.push(condition);
  56972. }
  56973. else {
  56974. parameters.push(null);
  56975. }
  56976. // If interpolate value action
  56977. if (parsedAction.name === "InterpolateValueAction") {
  56978. var param = parameters[parameters.length - 2];
  56979. parameters[parameters.length - 1] = param;
  56980. parameters[parameters.length - 2] = condition;
  56981. }
  56982. // Action or condition(s) and not CombineAction
  56983. var newAction = instanciate(parsedAction.name, parameters);
  56984. if (newAction instanceof BABYLON.Condition && condition !== null) {
  56985. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  56986. if (action) {
  56987. action.then(nothing);
  56988. }
  56989. else {
  56990. actionManager.registerAction(nothing);
  56991. }
  56992. action = nothing;
  56993. }
  56994. if (combineArray === null) {
  56995. if (newAction instanceof BABYLON.Condition) {
  56996. condition = newAction;
  56997. newAction = action;
  56998. }
  56999. else {
  57000. condition = null;
  57001. if (action) {
  57002. action.then(newAction);
  57003. }
  57004. else {
  57005. actionManager.registerAction(newAction);
  57006. }
  57007. }
  57008. }
  57009. else {
  57010. combineArray.push(newAction);
  57011. }
  57012. for (var i = 0; i < parsedAction.children.length; i++) {
  57013. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  57014. }
  57015. };
  57016. // triggers
  57017. for (var i = 0; i < parsedActions.children.length; i++) {
  57018. var triggerParams;
  57019. var trigger = parsedActions.children[i];
  57020. if (trigger.properties.length > 0) {
  57021. var param = trigger.properties[0].value;
  57022. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  57023. if (value._meshId) {
  57024. value.mesh = scene.getMeshByID(value._meshId);
  57025. }
  57026. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  57027. }
  57028. else {
  57029. triggerParams = ActionManager[trigger.name];
  57030. }
  57031. for (var j = 0; j < trigger.children.length; j++) {
  57032. if (!trigger.detached) {
  57033. traverse(trigger.children[j], triggerParams, null, null);
  57034. }
  57035. }
  57036. }
  57037. };
  57038. /**
  57039. * Get a trigger name by index
  57040. * @param trigger defines the trigger index
  57041. * @returns a trigger name
  57042. */
  57043. ActionManager.GetTriggerName = function (trigger) {
  57044. switch (trigger) {
  57045. case 0: return "NothingTrigger";
  57046. case 1: return "OnPickTrigger";
  57047. case 2: return "OnLeftPickTrigger";
  57048. case 3: return "OnRightPickTrigger";
  57049. case 4: return "OnCenterPickTrigger";
  57050. case 5: return "OnPickDownTrigger";
  57051. case 6: return "OnPickUpTrigger";
  57052. case 7: return "OnLongPressTrigger";
  57053. case 8: return "OnPointerOverTrigger";
  57054. case 9: return "OnPointerOutTrigger";
  57055. case 10: return "OnEveryFrameTrigger";
  57056. case 11: return "OnIntersectionEnterTrigger";
  57057. case 12: return "OnIntersectionExitTrigger";
  57058. case 13: return "OnKeyDownTrigger";
  57059. case 14: return "OnKeyUpTrigger";
  57060. case 15: return "OnPickOutTrigger";
  57061. default: return "";
  57062. }
  57063. };
  57064. /**
  57065. * Nothing
  57066. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57067. */
  57068. ActionManager.NothingTrigger = 0;
  57069. /**
  57070. * On pick
  57071. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57072. */
  57073. ActionManager.OnPickTrigger = 1;
  57074. /**
  57075. * On left pick
  57076. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57077. */
  57078. ActionManager.OnLeftPickTrigger = 2;
  57079. /**
  57080. * On right pick
  57081. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57082. */
  57083. ActionManager.OnRightPickTrigger = 3;
  57084. /**
  57085. * On center pick
  57086. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57087. */
  57088. ActionManager.OnCenterPickTrigger = 4;
  57089. /**
  57090. * On pick down
  57091. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57092. */
  57093. ActionManager.OnPickDownTrigger = 5;
  57094. /**
  57095. * On double pick
  57096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57097. */
  57098. ActionManager.OnDoublePickTrigger = 6;
  57099. /**
  57100. * On pick up
  57101. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57102. */
  57103. ActionManager.OnPickUpTrigger = 7;
  57104. /**
  57105. * On pick out.
  57106. * This trigger will only be raised if you also declared a OnPickDown
  57107. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57108. */
  57109. ActionManager.OnPickOutTrigger = 16;
  57110. /**
  57111. * On long press
  57112. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57113. */
  57114. ActionManager.OnLongPressTrigger = 8;
  57115. /**
  57116. * On pointer over
  57117. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57118. */
  57119. ActionManager.OnPointerOverTrigger = 9;
  57120. /**
  57121. * On pointer out
  57122. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57123. */
  57124. ActionManager.OnPointerOutTrigger = 10;
  57125. /**
  57126. * On every frame
  57127. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57128. */
  57129. ActionManager.OnEveryFrameTrigger = 11;
  57130. /**
  57131. * On intersection enter
  57132. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57133. */
  57134. ActionManager.OnIntersectionEnterTrigger = 12;
  57135. /**
  57136. * On intersection exit
  57137. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57138. */
  57139. ActionManager.OnIntersectionExitTrigger = 13;
  57140. /**
  57141. * On key down
  57142. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57143. */
  57144. ActionManager.OnKeyDownTrigger = 14;
  57145. /**
  57146. * On key up
  57147. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57148. */
  57149. ActionManager.OnKeyUpTrigger = 15;
  57150. /** Gets the list of active triggers */
  57151. ActionManager.Triggers = {};
  57152. return ActionManager;
  57153. }());
  57154. BABYLON.ActionManager = ActionManager;
  57155. })(BABYLON || (BABYLON = {}));
  57156. //# sourceMappingURL=babylon.actionManager.js.map
  57157. var BABYLON;
  57158. (function (BABYLON) {
  57159. /**
  57160. * This defines an action responsible to change the value of a property
  57161. * by interpolating between its current value and the newly set one once triggered.
  57162. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57163. */
  57164. var InterpolateValueAction = /** @class */ (function (_super) {
  57165. __extends(InterpolateValueAction, _super);
  57166. /**
  57167. * Instantiate the action
  57168. * @param triggerOptions defines the trigger options
  57169. * @param target defines the object containing the value to interpolate
  57170. * @param propertyPath defines the path to the property in the target object
  57171. * @param value defines the target value at the end of the interpolation
  57172. * @param duration deines the time it will take for the property to interpolate to the value.
  57173. * @param condition defines the trigger related conditions
  57174. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  57175. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  57176. */
  57177. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  57178. if (duration === void 0) { duration = 1000; }
  57179. var _this = _super.call(this, triggerOptions, condition) || this;
  57180. /**
  57181. * Defines the time it will take for the property to interpolate to the value.
  57182. */
  57183. _this.duration = 1000;
  57184. /**
  57185. * Observable triggered once the interpolation animation has been done.
  57186. */
  57187. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  57188. _this.propertyPath = propertyPath;
  57189. _this.value = value;
  57190. _this.duration = duration;
  57191. _this.stopOtherAnimations = stopOtherAnimations;
  57192. _this.onInterpolationDone = onInterpolationDone;
  57193. _this._target = _this._effectiveTarget = target;
  57194. return _this;
  57195. }
  57196. /** @hidden */
  57197. InterpolateValueAction.prototype._prepare = function () {
  57198. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57199. this._property = this._getProperty(this.propertyPath);
  57200. };
  57201. /**
  57202. * Execute the action starts the value interpolation.
  57203. */
  57204. InterpolateValueAction.prototype.execute = function () {
  57205. var _this = this;
  57206. var scene = this._actionManager.getScene();
  57207. var keys = [
  57208. {
  57209. frame: 0,
  57210. value: this._effectiveTarget[this._property]
  57211. }, {
  57212. frame: 100,
  57213. value: this.value
  57214. }
  57215. ];
  57216. var dataType;
  57217. if (typeof this.value === "number") {
  57218. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  57219. }
  57220. else if (this.value instanceof BABYLON.Color3) {
  57221. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  57222. }
  57223. else if (this.value instanceof BABYLON.Vector3) {
  57224. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  57225. }
  57226. else if (this.value instanceof BABYLON.Matrix) {
  57227. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  57228. }
  57229. else if (this.value instanceof BABYLON.Quaternion) {
  57230. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  57231. }
  57232. else {
  57233. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  57234. return;
  57235. }
  57236. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  57237. animation.setKeys(keys);
  57238. if (this.stopOtherAnimations) {
  57239. scene.stopAnimation(this._effectiveTarget);
  57240. }
  57241. var wrapper = function () {
  57242. _this.onInterpolationDoneObservable.notifyObservers(_this);
  57243. if (_this.onInterpolationDone) {
  57244. _this.onInterpolationDone();
  57245. }
  57246. };
  57247. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  57248. };
  57249. /**
  57250. * Serializes the actions and its related information.
  57251. * @param parent defines the object to serialize in
  57252. * @returns the serialized object
  57253. */
  57254. InterpolateValueAction.prototype.serialize = function (parent) {
  57255. return _super.prototype._serialize.call(this, {
  57256. name: "InterpolateValueAction",
  57257. properties: [
  57258. BABYLON.Action._GetTargetProperty(this._target),
  57259. { name: "propertyPath", value: this.propertyPath },
  57260. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  57261. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  57262. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  57263. ]
  57264. }, parent);
  57265. };
  57266. return InterpolateValueAction;
  57267. }(BABYLON.Action));
  57268. BABYLON.InterpolateValueAction = InterpolateValueAction;
  57269. })(BABYLON || (BABYLON = {}));
  57270. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  57271. var BABYLON;
  57272. (function (BABYLON) {
  57273. /**
  57274. * This defines an action responsible to toggle a boolean once triggered.
  57275. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57276. */
  57277. var SwitchBooleanAction = /** @class */ (function (_super) {
  57278. __extends(SwitchBooleanAction, _super);
  57279. /**
  57280. * Instantiate the action
  57281. * @param triggerOptions defines the trigger options
  57282. * @param target defines the object containing the boolean
  57283. * @param propertyPath defines the path to the boolean property in the target object
  57284. * @param condition defines the trigger related conditions
  57285. */
  57286. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  57287. var _this = _super.call(this, triggerOptions, condition) || this;
  57288. _this.propertyPath = propertyPath;
  57289. _this._target = _this._effectiveTarget = target;
  57290. return _this;
  57291. }
  57292. /** @hidden */
  57293. SwitchBooleanAction.prototype._prepare = function () {
  57294. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57295. this._property = this._getProperty(this.propertyPath);
  57296. };
  57297. /**
  57298. * Execute the action toggle the boolean value.
  57299. */
  57300. SwitchBooleanAction.prototype.execute = function () {
  57301. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  57302. };
  57303. /**
  57304. * Serializes the actions and its related information.
  57305. * @param parent defines the object to serialize in
  57306. * @returns the serialized object
  57307. */
  57308. SwitchBooleanAction.prototype.serialize = function (parent) {
  57309. return _super.prototype._serialize.call(this, {
  57310. name: "SwitchBooleanAction",
  57311. properties: [
  57312. BABYLON.Action._GetTargetProperty(this._target),
  57313. { name: "propertyPath", value: this.propertyPath }
  57314. ]
  57315. }, parent);
  57316. };
  57317. return SwitchBooleanAction;
  57318. }(BABYLON.Action));
  57319. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  57320. /**
  57321. * This defines an action responsible to set a the state field of the target
  57322. * to a desired value once triggered.
  57323. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57324. */
  57325. var SetStateAction = /** @class */ (function (_super) {
  57326. __extends(SetStateAction, _super);
  57327. /**
  57328. * Instantiate the action
  57329. * @param triggerOptions defines the trigger options
  57330. * @param target defines the object containing the state property
  57331. * @param value defines the value to store in the state field
  57332. * @param condition defines the trigger related conditions
  57333. */
  57334. function SetStateAction(triggerOptions, target, value, condition) {
  57335. var _this = _super.call(this, triggerOptions, condition) || this;
  57336. _this.value = value;
  57337. _this._target = target;
  57338. return _this;
  57339. }
  57340. /**
  57341. * Execute the action and store the value on the target state property.
  57342. */
  57343. SetStateAction.prototype.execute = function () {
  57344. this._target.state = this.value;
  57345. };
  57346. /**
  57347. * Serializes the actions and its related information.
  57348. * @param parent defines the object to serialize in
  57349. * @returns the serialized object
  57350. */
  57351. SetStateAction.prototype.serialize = function (parent) {
  57352. return _super.prototype._serialize.call(this, {
  57353. name: "SetStateAction",
  57354. properties: [
  57355. BABYLON.Action._GetTargetProperty(this._target),
  57356. { name: "value", value: this.value }
  57357. ]
  57358. }, parent);
  57359. };
  57360. return SetStateAction;
  57361. }(BABYLON.Action));
  57362. BABYLON.SetStateAction = SetStateAction;
  57363. /**
  57364. * This defines an action responsible to set a property of the target
  57365. * to a desired value once triggered.
  57366. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57367. */
  57368. var SetValueAction = /** @class */ (function (_super) {
  57369. __extends(SetValueAction, _super);
  57370. /**
  57371. * Instantiate the action
  57372. * @param triggerOptions defines the trigger options
  57373. * @param target defines the object containing the property
  57374. * @param propertyPath defines the path of the property to set in the target
  57375. * @param value defines the value to set in the property
  57376. * @param condition defines the trigger related conditions
  57377. */
  57378. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  57379. var _this = _super.call(this, triggerOptions, condition) || this;
  57380. _this.propertyPath = propertyPath;
  57381. _this.value = value;
  57382. _this._target = _this._effectiveTarget = target;
  57383. return _this;
  57384. }
  57385. /** @hidden */
  57386. SetValueAction.prototype._prepare = function () {
  57387. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57388. this._property = this._getProperty(this.propertyPath);
  57389. };
  57390. /**
  57391. * Execute the action and set the targetted property to the desired value.
  57392. */
  57393. SetValueAction.prototype.execute = function () {
  57394. this._effectiveTarget[this._property] = this.value;
  57395. if (this._target.markAsDirty) {
  57396. this._target.markAsDirty(this._property);
  57397. }
  57398. };
  57399. /**
  57400. * Serializes the actions and its related information.
  57401. * @param parent defines the object to serialize in
  57402. * @returns the serialized object
  57403. */
  57404. SetValueAction.prototype.serialize = function (parent) {
  57405. return _super.prototype._serialize.call(this, {
  57406. name: "SetValueAction",
  57407. properties: [
  57408. BABYLON.Action._GetTargetProperty(this._target),
  57409. { name: "propertyPath", value: this.propertyPath },
  57410. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57411. ]
  57412. }, parent);
  57413. };
  57414. return SetValueAction;
  57415. }(BABYLON.Action));
  57416. BABYLON.SetValueAction = SetValueAction;
  57417. /**
  57418. * This defines an action responsible to increment the target value
  57419. * to a desired value once triggered.
  57420. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57421. */
  57422. var IncrementValueAction = /** @class */ (function (_super) {
  57423. __extends(IncrementValueAction, _super);
  57424. /**
  57425. * Instantiate the action
  57426. * @param triggerOptions defines the trigger options
  57427. * @param target defines the object containing the property
  57428. * @param propertyPath defines the path of the property to increment in the target
  57429. * @param value defines the value value we should increment the property by
  57430. * @param condition defines the trigger related conditions
  57431. */
  57432. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  57433. var _this = _super.call(this, triggerOptions, condition) || this;
  57434. _this.propertyPath = propertyPath;
  57435. _this.value = value;
  57436. _this._target = _this._effectiveTarget = target;
  57437. return _this;
  57438. }
  57439. /** @hidden */
  57440. IncrementValueAction.prototype._prepare = function () {
  57441. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57442. this._property = this._getProperty(this.propertyPath);
  57443. if (typeof this._effectiveTarget[this._property] !== "number") {
  57444. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  57445. }
  57446. };
  57447. /**
  57448. * Execute the action and increment the target of the value amount.
  57449. */
  57450. IncrementValueAction.prototype.execute = function () {
  57451. this._effectiveTarget[this._property] += this.value;
  57452. if (this._target.markAsDirty) {
  57453. this._target.markAsDirty(this._property);
  57454. }
  57455. };
  57456. /**
  57457. * Serializes the actions and its related information.
  57458. * @param parent defines the object to serialize in
  57459. * @returns the serialized object
  57460. */
  57461. IncrementValueAction.prototype.serialize = function (parent) {
  57462. return _super.prototype._serialize.call(this, {
  57463. name: "IncrementValueAction",
  57464. properties: [
  57465. BABYLON.Action._GetTargetProperty(this._target),
  57466. { name: "propertyPath", value: this.propertyPath },
  57467. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57468. ]
  57469. }, parent);
  57470. };
  57471. return IncrementValueAction;
  57472. }(BABYLON.Action));
  57473. BABYLON.IncrementValueAction = IncrementValueAction;
  57474. /**
  57475. * This defines an action responsible to start an animation once triggered.
  57476. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57477. */
  57478. var PlayAnimationAction = /** @class */ (function (_super) {
  57479. __extends(PlayAnimationAction, _super);
  57480. /**
  57481. * Instantiate the action
  57482. * @param triggerOptions defines the trigger options
  57483. * @param target defines the target animation or animation name
  57484. * @param from defines from where the animation should start (animation frame)
  57485. * @param end defines where the animation should stop (animation frame)
  57486. * @param loop defines if the animation should loop or stop after the first play
  57487. * @param condition defines the trigger related conditions
  57488. */
  57489. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  57490. var _this = _super.call(this, triggerOptions, condition) || this;
  57491. _this.from = from;
  57492. _this.to = to;
  57493. _this.loop = loop;
  57494. _this._target = target;
  57495. return _this;
  57496. }
  57497. /** @hidden */
  57498. PlayAnimationAction.prototype._prepare = function () {
  57499. };
  57500. /**
  57501. * Execute the action and play the animation.
  57502. */
  57503. PlayAnimationAction.prototype.execute = function () {
  57504. var scene = this._actionManager.getScene();
  57505. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  57506. };
  57507. /**
  57508. * Serializes the actions and its related information.
  57509. * @param parent defines the object to serialize in
  57510. * @returns the serialized object
  57511. */
  57512. PlayAnimationAction.prototype.serialize = function (parent) {
  57513. return _super.prototype._serialize.call(this, {
  57514. name: "PlayAnimationAction",
  57515. properties: [
  57516. BABYLON.Action._GetTargetProperty(this._target),
  57517. { name: "from", value: String(this.from) },
  57518. { name: "to", value: String(this.to) },
  57519. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  57520. ]
  57521. }, parent);
  57522. };
  57523. return PlayAnimationAction;
  57524. }(BABYLON.Action));
  57525. BABYLON.PlayAnimationAction = PlayAnimationAction;
  57526. /**
  57527. * This defines an action responsible to stop an animation once triggered.
  57528. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57529. */
  57530. var StopAnimationAction = /** @class */ (function (_super) {
  57531. __extends(StopAnimationAction, _super);
  57532. /**
  57533. * Instantiate the action
  57534. * @param triggerOptions defines the trigger options
  57535. * @param target defines the target animation or animation name
  57536. * @param condition defines the trigger related conditions
  57537. */
  57538. function StopAnimationAction(triggerOptions, target, condition) {
  57539. var _this = _super.call(this, triggerOptions, condition) || this;
  57540. _this._target = target;
  57541. return _this;
  57542. }
  57543. /** @hidden */
  57544. StopAnimationAction.prototype._prepare = function () {
  57545. };
  57546. /**
  57547. * Execute the action and stop the animation.
  57548. */
  57549. StopAnimationAction.prototype.execute = function () {
  57550. var scene = this._actionManager.getScene();
  57551. scene.stopAnimation(this._target);
  57552. };
  57553. /**
  57554. * Serializes the actions and its related information.
  57555. * @param parent defines the object to serialize in
  57556. * @returns the serialized object
  57557. */
  57558. StopAnimationAction.prototype.serialize = function (parent) {
  57559. return _super.prototype._serialize.call(this, {
  57560. name: "StopAnimationAction",
  57561. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  57562. }, parent);
  57563. };
  57564. return StopAnimationAction;
  57565. }(BABYLON.Action));
  57566. BABYLON.StopAnimationAction = StopAnimationAction;
  57567. /**
  57568. * This defines an action responsible that does nothing once triggered.
  57569. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57570. */
  57571. var DoNothingAction = /** @class */ (function (_super) {
  57572. __extends(DoNothingAction, _super);
  57573. /**
  57574. * Instantiate the action
  57575. * @param triggerOptions defines the trigger options
  57576. * @param condition defines the trigger related conditions
  57577. */
  57578. function DoNothingAction(triggerOptions, condition) {
  57579. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  57580. return _super.call(this, triggerOptions, condition) || this;
  57581. }
  57582. /**
  57583. * Execute the action and do nothing.
  57584. */
  57585. DoNothingAction.prototype.execute = function () {
  57586. };
  57587. /**
  57588. * Serializes the actions and its related information.
  57589. * @param parent defines the object to serialize in
  57590. * @returns the serialized object
  57591. */
  57592. DoNothingAction.prototype.serialize = function (parent) {
  57593. return _super.prototype._serialize.call(this, {
  57594. name: "DoNothingAction",
  57595. properties: []
  57596. }, parent);
  57597. };
  57598. return DoNothingAction;
  57599. }(BABYLON.Action));
  57600. BABYLON.DoNothingAction = DoNothingAction;
  57601. /**
  57602. * This defines an action responsible to trigger several actions once triggered.
  57603. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57604. */
  57605. var CombineAction = /** @class */ (function (_super) {
  57606. __extends(CombineAction, _super);
  57607. /**
  57608. * Instantiate the action
  57609. * @param triggerOptions defines the trigger options
  57610. * @param children defines the list of aggregated animations to run
  57611. * @param condition defines the trigger related conditions
  57612. */
  57613. function CombineAction(triggerOptions, children, condition) {
  57614. var _this = _super.call(this, triggerOptions, condition) || this;
  57615. _this.children = children;
  57616. return _this;
  57617. }
  57618. /** @hidden */
  57619. CombineAction.prototype._prepare = function () {
  57620. for (var index = 0; index < this.children.length; index++) {
  57621. this.children[index]._actionManager = this._actionManager;
  57622. this.children[index]._prepare();
  57623. }
  57624. };
  57625. /**
  57626. * Execute the action and executes all the aggregated actions.
  57627. */
  57628. CombineAction.prototype.execute = function (evt) {
  57629. for (var index = 0; index < this.children.length; index++) {
  57630. this.children[index].execute(evt);
  57631. }
  57632. };
  57633. /**
  57634. * Serializes the actions and its related information.
  57635. * @param parent defines the object to serialize in
  57636. * @returns the serialized object
  57637. */
  57638. CombineAction.prototype.serialize = function (parent) {
  57639. var serializationObject = _super.prototype._serialize.call(this, {
  57640. name: "CombineAction",
  57641. properties: [],
  57642. combine: []
  57643. }, parent);
  57644. for (var i = 0; i < this.children.length; i++) {
  57645. serializationObject.combine.push(this.children[i].serialize(null));
  57646. }
  57647. return serializationObject;
  57648. };
  57649. return CombineAction;
  57650. }(BABYLON.Action));
  57651. BABYLON.CombineAction = CombineAction;
  57652. /**
  57653. * This defines an action responsible to run code (external event) once triggered.
  57654. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57655. */
  57656. var ExecuteCodeAction = /** @class */ (function (_super) {
  57657. __extends(ExecuteCodeAction, _super);
  57658. /**
  57659. * Instantiate the action
  57660. * @param triggerOptions defines the trigger options
  57661. * @param func defines the callback function to run
  57662. * @param condition defines the trigger related conditions
  57663. */
  57664. function ExecuteCodeAction(triggerOptions, func, condition) {
  57665. var _this = _super.call(this, triggerOptions, condition) || this;
  57666. _this.func = func;
  57667. return _this;
  57668. }
  57669. /**
  57670. * Execute the action and run the attached code.
  57671. */
  57672. ExecuteCodeAction.prototype.execute = function (evt) {
  57673. this.func(evt);
  57674. };
  57675. return ExecuteCodeAction;
  57676. }(BABYLON.Action));
  57677. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  57678. /**
  57679. * This defines an action responsible to set the parent property of the target once triggered.
  57680. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57681. */
  57682. var SetParentAction = /** @class */ (function (_super) {
  57683. __extends(SetParentAction, _super);
  57684. /**
  57685. * Instantiate the action
  57686. * @param triggerOptions defines the trigger options
  57687. * @param target defines the target containing the parent property
  57688. * @param parent defines from where the animation should start (animation frame)
  57689. * @param condition defines the trigger related conditions
  57690. */
  57691. function SetParentAction(triggerOptions, target, parent, condition) {
  57692. var _this = _super.call(this, triggerOptions, condition) || this;
  57693. _this._target = target;
  57694. _this._parent = parent;
  57695. return _this;
  57696. }
  57697. /** @hidden */
  57698. SetParentAction.prototype._prepare = function () {
  57699. };
  57700. /**
  57701. * Execute the action and set the parent property.
  57702. */
  57703. SetParentAction.prototype.execute = function () {
  57704. if (this._target.parent === this._parent) {
  57705. return;
  57706. }
  57707. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  57708. invertParentWorldMatrix.invert();
  57709. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  57710. this._target.parent = this._parent;
  57711. };
  57712. /**
  57713. * Serializes the actions and its related information.
  57714. * @param parent defines the object to serialize in
  57715. * @returns the serialized object
  57716. */
  57717. SetParentAction.prototype.serialize = function (parent) {
  57718. return _super.prototype._serialize.call(this, {
  57719. name: "SetParentAction",
  57720. properties: [
  57721. BABYLON.Action._GetTargetProperty(this._target),
  57722. BABYLON.Action._GetTargetProperty(this._parent),
  57723. ]
  57724. }, parent);
  57725. };
  57726. return SetParentAction;
  57727. }(BABYLON.Action));
  57728. BABYLON.SetParentAction = SetParentAction;
  57729. })(BABYLON || (BABYLON = {}));
  57730. //# sourceMappingURL=babylon.directActions.js.map
  57731. var BABYLON;
  57732. (function (BABYLON) {
  57733. /**
  57734. * Class used to manage multiple sprites on the same spritesheet
  57735. * @see http://doc.babylonjs.com/babylon101/sprites
  57736. */
  57737. var SpriteManager = /** @class */ (function () {
  57738. /**
  57739. * Creates a new sprite manager
  57740. * @param name defines the manager's name
  57741. * @param imgUrl defines the sprite sheet url
  57742. * @param capacity defines the maximum allowed number of sprites
  57743. * @param cellSize defines the size of a sprite cell
  57744. * @param scene defines the hosting scene
  57745. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  57746. * @param samplingMode defines the smapling mode to use with spritesheet
  57747. */
  57748. function SpriteManager(
  57749. /** defines the manager's name */
  57750. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  57751. if (epsilon === void 0) { epsilon = 0.01; }
  57752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57753. this.name = name;
  57754. /** Gets the list of sprites */
  57755. this.sprites = new Array();
  57756. /** Gets or sets the rendering group id (0 by default) */
  57757. this.renderingGroupId = 0;
  57758. /** Gets or sets camera layer mask */
  57759. this.layerMask = 0x0FFFFFFF;
  57760. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  57761. this.fogEnabled = true;
  57762. /** Gets or sets a boolean indicating if the sprites are pickable */
  57763. this.isPickable = false;
  57764. /**
  57765. * An event triggered when the manager is disposed.
  57766. */
  57767. this.onDisposeObservable = new BABYLON.Observable();
  57768. this._vertexBuffers = {};
  57769. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  57770. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  57771. }
  57772. this._capacity = capacity;
  57773. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  57774. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57775. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57776. if (cellSize.width && cellSize.height) {
  57777. this.cellWidth = cellSize.width;
  57778. this.cellHeight = cellSize.height;
  57779. }
  57780. else if (cellSize !== undefined) {
  57781. this.cellWidth = cellSize;
  57782. this.cellHeight = cellSize;
  57783. }
  57784. else {
  57785. return;
  57786. }
  57787. this._epsilon = epsilon;
  57788. this._scene = scene;
  57789. this._scene.spriteManagers.push(this);
  57790. var indices = [];
  57791. var index = 0;
  57792. for (var count = 0; count < capacity; count++) {
  57793. indices.push(index);
  57794. indices.push(index + 1);
  57795. indices.push(index + 2);
  57796. indices.push(index);
  57797. indices.push(index + 2);
  57798. indices.push(index + 3);
  57799. index += 4;
  57800. }
  57801. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  57802. // VBO
  57803. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  57804. this._vertexData = new Float32Array(capacity * 16 * 4);
  57805. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  57806. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  57807. var options = this._buffer.createVertexBuffer("options", 4, 4);
  57808. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  57809. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  57810. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57811. this._vertexBuffers["options"] = options;
  57812. this._vertexBuffers["cellInfo"] = cellInfo;
  57813. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57814. // Effects
  57815. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  57816. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  57817. }
  57818. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  57819. /**
  57820. * Callback called when the manager is disposed
  57821. */
  57822. set: function (callback) {
  57823. if (this._onDisposeObserver) {
  57824. this.onDisposeObservable.remove(this._onDisposeObserver);
  57825. }
  57826. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57827. },
  57828. enumerable: true,
  57829. configurable: true
  57830. });
  57831. Object.defineProperty(SpriteManager.prototype, "texture", {
  57832. /**
  57833. * Gets or sets the spritesheet texture
  57834. */
  57835. get: function () {
  57836. return this._spriteTexture;
  57837. },
  57838. set: function (value) {
  57839. this._spriteTexture = value;
  57840. },
  57841. enumerable: true,
  57842. configurable: true
  57843. });
  57844. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  57845. var arrayOffset = index * 16;
  57846. if (offsetX === 0) {
  57847. offsetX = this._epsilon;
  57848. }
  57849. else if (offsetX === 1) {
  57850. offsetX = 1 - this._epsilon;
  57851. }
  57852. if (offsetY === 0) {
  57853. offsetY = this._epsilon;
  57854. }
  57855. else if (offsetY === 1) {
  57856. offsetY = 1 - this._epsilon;
  57857. }
  57858. this._vertexData[arrayOffset] = sprite.position.x;
  57859. this._vertexData[arrayOffset + 1] = sprite.position.y;
  57860. this._vertexData[arrayOffset + 2] = sprite.position.z;
  57861. this._vertexData[arrayOffset + 3] = sprite.angle;
  57862. this._vertexData[arrayOffset + 4] = sprite.width;
  57863. this._vertexData[arrayOffset + 5] = sprite.height;
  57864. this._vertexData[arrayOffset + 6] = offsetX;
  57865. this._vertexData[arrayOffset + 7] = offsetY;
  57866. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  57867. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  57868. var offset = (sprite.cellIndex / rowSize) >> 0;
  57869. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  57870. this._vertexData[arrayOffset + 11] = offset;
  57871. // Color
  57872. this._vertexData[arrayOffset + 12] = sprite.color.r;
  57873. this._vertexData[arrayOffset + 13] = sprite.color.g;
  57874. this._vertexData[arrayOffset + 14] = sprite.color.b;
  57875. this._vertexData[arrayOffset + 15] = sprite.color.a;
  57876. };
  57877. /**
  57878. * Intersects the sprites with a ray
  57879. * @param ray defines the ray to intersect with
  57880. * @param camera defines the current active camera
  57881. * @param predicate defines a predicate used to select candidate sprites
  57882. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  57883. * @returns null if no hit or a PickingInfo
  57884. */
  57885. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  57886. var count = Math.min(this._capacity, this.sprites.length);
  57887. var min = BABYLON.Vector3.Zero();
  57888. var max = BABYLON.Vector3.Zero();
  57889. var distance = Number.MAX_VALUE;
  57890. var currentSprite = null;
  57891. var cameraSpacePosition = BABYLON.Vector3.Zero();
  57892. var cameraView = camera.getViewMatrix();
  57893. for (var index = 0; index < count; index++) {
  57894. var sprite = this.sprites[index];
  57895. if (!sprite) {
  57896. continue;
  57897. }
  57898. if (predicate) {
  57899. if (!predicate(sprite)) {
  57900. continue;
  57901. }
  57902. }
  57903. else if (!sprite.isPickable) {
  57904. continue;
  57905. }
  57906. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  57907. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  57908. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  57909. if (ray.intersectsBoxMinMax(min, max)) {
  57910. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  57911. if (distance > currentDistance) {
  57912. distance = currentDistance;
  57913. currentSprite = sprite;
  57914. if (fastCheck) {
  57915. break;
  57916. }
  57917. }
  57918. }
  57919. }
  57920. if (currentSprite) {
  57921. var result = new BABYLON.PickingInfo();
  57922. result.hit = true;
  57923. result.pickedSprite = currentSprite;
  57924. result.distance = distance;
  57925. return result;
  57926. }
  57927. return null;
  57928. };
  57929. /**
  57930. * Render all child sprites
  57931. */
  57932. SpriteManager.prototype.render = function () {
  57933. // Check
  57934. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  57935. return;
  57936. }
  57937. var engine = this._scene.getEngine();
  57938. var baseSize = this._spriteTexture.getBaseSize();
  57939. // Sprites
  57940. var deltaTime = engine.getDeltaTime();
  57941. var max = Math.min(this._capacity, this.sprites.length);
  57942. var rowSize = baseSize.width / this.cellWidth;
  57943. var offset = 0;
  57944. for (var index = 0; index < max; index++) {
  57945. var sprite = this.sprites[index];
  57946. if (!sprite || !sprite.isVisible) {
  57947. continue;
  57948. }
  57949. sprite._animate(deltaTime);
  57950. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  57951. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  57952. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  57953. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  57954. }
  57955. this._buffer.update(this._vertexData);
  57956. // Render
  57957. var effect = this._effectBase;
  57958. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57959. effect = this._effectFog;
  57960. }
  57961. engine.enableEffect(effect);
  57962. var viewMatrix = this._scene.getViewMatrix();
  57963. effect.setTexture("diffuseSampler", this._spriteTexture);
  57964. effect.setMatrix("view", viewMatrix);
  57965. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57966. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  57967. // Fog
  57968. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57969. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  57970. effect.setColor3("vFogColor", this._scene.fogColor);
  57971. }
  57972. // VBOs
  57973. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57974. // Draw order
  57975. engine.setDepthFunctionToLessOrEqual();
  57976. effect.setBool("alphaTest", true);
  57977. engine.setColorWrite(false);
  57978. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57979. engine.setColorWrite(true);
  57980. effect.setBool("alphaTest", false);
  57981. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57982. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  57983. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57984. };
  57985. /**
  57986. * Release associated resources
  57987. */
  57988. SpriteManager.prototype.dispose = function () {
  57989. if (this._buffer) {
  57990. this._buffer.dispose();
  57991. this._buffer = null;
  57992. }
  57993. if (this._indexBuffer) {
  57994. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57995. this._indexBuffer = null;
  57996. }
  57997. if (this._spriteTexture) {
  57998. this._spriteTexture.dispose();
  57999. this._spriteTexture = null;
  58000. }
  58001. // Remove from scene
  58002. var index = this._scene.spriteManagers.indexOf(this);
  58003. this._scene.spriteManagers.splice(index, 1);
  58004. // Callback
  58005. this.onDisposeObservable.notifyObservers(this);
  58006. this.onDisposeObservable.clear();
  58007. };
  58008. return SpriteManager;
  58009. }());
  58010. BABYLON.SpriteManager = SpriteManager;
  58011. })(BABYLON || (BABYLON = {}));
  58012. //# sourceMappingURL=babylon.spriteManager.js.map
  58013. var BABYLON;
  58014. (function (BABYLON) {
  58015. /**
  58016. * Class used to represent a sprite
  58017. * @see http://doc.babylonjs.com/babylon101/sprites
  58018. */
  58019. var Sprite = /** @class */ (function () {
  58020. /**
  58021. * Creates a new Sprite
  58022. * @param name defines the name
  58023. * @param manager defines the manager
  58024. */
  58025. function Sprite(
  58026. /** defines the name */
  58027. name, manager) {
  58028. this.name = name;
  58029. /** Gets or sets the main color */
  58030. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58031. /** Gets or sets the width */
  58032. this.width = 1.0;
  58033. /** Gets or sets the height */
  58034. this.height = 1.0;
  58035. /** Gets or sets rotation angle */
  58036. this.angle = 0;
  58037. /** Gets or sets the cell index in the sprite sheet */
  58038. this.cellIndex = 0;
  58039. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  58040. this.invertU = 0;
  58041. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  58042. this.invertV = 0;
  58043. /** Gets the list of attached animations */
  58044. this.animations = new Array();
  58045. /** Gets or sets a boolean indicating if the sprite can be picked */
  58046. this.isPickable = false;
  58047. this._animationStarted = false;
  58048. this._loopAnimation = false;
  58049. this._fromIndex = 0;
  58050. this._toIndex = 0;
  58051. this._delay = 0;
  58052. this._direction = 1;
  58053. this._time = 0;
  58054. /**
  58055. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  58056. */
  58057. this.isVisible = true;
  58058. this._manager = manager;
  58059. this._manager.sprites.push(this);
  58060. this.position = BABYLON.Vector3.Zero();
  58061. }
  58062. Object.defineProperty(Sprite.prototype, "size", {
  58063. /**
  58064. * Gets or sets the sprite size
  58065. */
  58066. get: function () {
  58067. return this.width;
  58068. },
  58069. set: function (value) {
  58070. this.width = value;
  58071. this.height = value;
  58072. },
  58073. enumerable: true,
  58074. configurable: true
  58075. });
  58076. /**
  58077. * Starts an animation
  58078. * @param from defines the initial key
  58079. * @param to defines the end key
  58080. * @param loop defines if the animation must loop
  58081. * @param delay defines the start delay (in ms)
  58082. * @param onAnimationEnd defines a callback to call when animation ends
  58083. */
  58084. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  58085. this._fromIndex = from;
  58086. this._toIndex = to;
  58087. this._loopAnimation = loop;
  58088. this._delay = delay;
  58089. this._animationStarted = true;
  58090. this._direction = from < to ? 1 : -1;
  58091. this.cellIndex = from;
  58092. this._time = 0;
  58093. this._onAnimationEnd = onAnimationEnd;
  58094. };
  58095. /** Stops current animation (if any) */
  58096. Sprite.prototype.stopAnimation = function () {
  58097. this._animationStarted = false;
  58098. };
  58099. /** @hidden */
  58100. Sprite.prototype._animate = function (deltaTime) {
  58101. if (!this._animationStarted) {
  58102. return;
  58103. }
  58104. this._time += deltaTime;
  58105. if (this._time > this._delay) {
  58106. this._time = this._time % this._delay;
  58107. this.cellIndex += this._direction;
  58108. if (this.cellIndex > this._toIndex) {
  58109. if (this._loopAnimation) {
  58110. this.cellIndex = this._fromIndex;
  58111. }
  58112. else {
  58113. this.cellIndex = this._toIndex;
  58114. this._animationStarted = false;
  58115. if (this._onAnimationEnd) {
  58116. this._onAnimationEnd();
  58117. }
  58118. if (this.disposeWhenFinishedAnimating) {
  58119. this.dispose();
  58120. }
  58121. }
  58122. }
  58123. }
  58124. };
  58125. /** Release associated resources */
  58126. Sprite.prototype.dispose = function () {
  58127. for (var i = 0; i < this._manager.sprites.length; i++) {
  58128. if (this._manager.sprites[i] == this) {
  58129. this._manager.sprites.splice(i, 1);
  58130. }
  58131. }
  58132. };
  58133. return Sprite;
  58134. }());
  58135. BABYLON.Sprite = Sprite;
  58136. })(BABYLON || (BABYLON = {}));
  58137. //# sourceMappingURL=babylon.sprite.js.map
  58138. var BABYLON;
  58139. (function (BABYLON) {
  58140. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  58141. if (!BABYLON.PickingInfo) {
  58142. return null;
  58143. }
  58144. var pickingInfo = null;
  58145. if (!camera) {
  58146. if (!this.activeCamera) {
  58147. return null;
  58148. }
  58149. camera = this.activeCamera;
  58150. }
  58151. if (this.spriteManagers.length > 0) {
  58152. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  58153. var spriteManager = this.spriteManagers[spriteIndex];
  58154. if (!spriteManager.isPickable) {
  58155. continue;
  58156. }
  58157. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  58158. if (!result || !result.hit) {
  58159. continue;
  58160. }
  58161. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  58162. continue;
  58163. }
  58164. pickingInfo = result;
  58165. if (fastCheck) {
  58166. break;
  58167. }
  58168. }
  58169. }
  58170. return pickingInfo || new BABYLON.PickingInfo();
  58171. };
  58172. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  58173. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  58174. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58175. };
  58176. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  58177. if (!this._tempSpritePickingRay) {
  58178. return null;
  58179. }
  58180. if (!camera) {
  58181. if (!this.activeCamera) {
  58182. return null;
  58183. }
  58184. camera = this.activeCamera;
  58185. }
  58186. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  58187. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58188. };
  58189. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  58190. if (this._pointerOverSprite === sprite) {
  58191. return;
  58192. }
  58193. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58194. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58195. }
  58196. this._pointerOverSprite = sprite;
  58197. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58198. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58199. }
  58200. };
  58201. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  58202. return this._pointerOverSprite;
  58203. };
  58204. /**
  58205. * Defines the sprite scene component responsible to manage sprites
  58206. * in a given scene.
  58207. */
  58208. var SpriteSceneComponent = /** @class */ (function () {
  58209. /**
  58210. * Creates a new instance of the component for the given scene
  58211. * @param scene Defines the scene to register the component in
  58212. */
  58213. function SpriteSceneComponent(scene) {
  58214. /**
  58215. * The component name helpfull to identify the component in the list of scene components.
  58216. */
  58217. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  58218. this.scene = scene;
  58219. this.scene.spriteManagers = new Array();
  58220. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  58221. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  58222. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  58223. this._spritePredicate = function (sprite) {
  58224. if (!sprite.actionManager) {
  58225. return false;
  58226. }
  58227. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  58228. };
  58229. }
  58230. /**
  58231. * Registers the component in a given scene
  58232. */
  58233. SpriteSceneComponent.prototype.register = function () {
  58234. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  58235. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  58236. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  58237. };
  58238. /**
  58239. * Rebuilds the elements related to this component in case of
  58240. * context lost for instance.
  58241. */
  58242. SpriteSceneComponent.prototype.rebuild = function () {
  58243. /** Nothing to do for sprites */
  58244. };
  58245. /**
  58246. * Disposes the component and the associated ressources.
  58247. */
  58248. SpriteSceneComponent.prototype.dispose = function () {
  58249. this.scene.onBeforeSpritesRenderingObservable.clear();
  58250. this.scene.onAfterSpritesRenderingObservable.clear();
  58251. var spriteManagers = this.scene.spriteManagers;
  58252. while (spriteManagers.length) {
  58253. spriteManagers[0].dispose();
  58254. }
  58255. };
  58256. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  58257. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  58258. if (result) {
  58259. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  58260. }
  58261. return result;
  58262. };
  58263. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  58264. var scene = this.scene;
  58265. if (isMeshPicked) {
  58266. scene.setPointerOverSprite(null);
  58267. }
  58268. else {
  58269. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  58270. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58271. scene.setPointerOverSprite(pickResult.pickedSprite);
  58272. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  58273. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  58274. }
  58275. else {
  58276. canvas.style.cursor = scene.hoverCursor;
  58277. }
  58278. }
  58279. else {
  58280. scene.setPointerOverSprite(null);
  58281. }
  58282. }
  58283. return pickResult;
  58284. };
  58285. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58286. var scene = this.scene;
  58287. scene._pickedDownSprite = null;
  58288. if (scene.spriteManagers.length > 0) {
  58289. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58290. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58291. if (pickResult.pickedSprite.actionManager) {
  58292. scene._pickedDownSprite = pickResult.pickedSprite;
  58293. switch (evt.button) {
  58294. case 0:
  58295. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58296. break;
  58297. case 1:
  58298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58299. break;
  58300. case 2:
  58301. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58302. break;
  58303. }
  58304. if (pickResult.pickedSprite.actionManager) {
  58305. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58306. }
  58307. }
  58308. }
  58309. }
  58310. return pickResult;
  58311. };
  58312. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58313. var scene = this.scene;
  58314. if (scene.spriteManagers.length > 0) {
  58315. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58316. if (spritePickResult) {
  58317. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  58318. if (spritePickResult.pickedSprite.actionManager) {
  58319. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58320. if (spritePickResult.pickedSprite.actionManager) {
  58321. if (!this.scene._isPointerSwiping()) {
  58322. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58323. }
  58324. }
  58325. }
  58326. }
  58327. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  58328. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  58329. }
  58330. }
  58331. }
  58332. return pickResult;
  58333. };
  58334. return SpriteSceneComponent;
  58335. }());
  58336. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  58337. })(BABYLON || (BABYLON = {}));
  58338. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  58339. var BABYLON;
  58340. (function (BABYLON) {
  58341. /**
  58342. * @hidden
  58343. */
  58344. var IntersectionInfo = /** @class */ (function () {
  58345. function IntersectionInfo(bu, bv, distance) {
  58346. this.bu = bu;
  58347. this.bv = bv;
  58348. this.distance = distance;
  58349. this.faceId = 0;
  58350. this.subMeshId = 0;
  58351. }
  58352. return IntersectionInfo;
  58353. }());
  58354. BABYLON.IntersectionInfo = IntersectionInfo;
  58355. /**
  58356. * Information about the result of picking within a scene
  58357. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  58358. */
  58359. var PickingInfo = /** @class */ (function () {
  58360. function PickingInfo() {
  58361. /**
  58362. * If the pick collided with an object
  58363. */
  58364. this.hit = false;
  58365. /**
  58366. * Distance away where the pick collided
  58367. */
  58368. this.distance = 0;
  58369. /**
  58370. * The location of pick collision
  58371. */
  58372. this.pickedPoint = null;
  58373. /**
  58374. * The mesh corresponding the the pick collision
  58375. */
  58376. this.pickedMesh = null;
  58377. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  58378. this.bu = 0;
  58379. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  58380. this.bv = 0;
  58381. /** The id of the face on the mesh that was picked */
  58382. this.faceId = -1;
  58383. /** Id of the the submesh that was picked */
  58384. this.subMeshId = 0;
  58385. /** If a sprite was picked, this will be the sprite the pick collided with */
  58386. this.pickedSprite = null;
  58387. /**
  58388. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  58389. */
  58390. this.originMesh = null;
  58391. /**
  58392. * The ray that was used to perform the picking.
  58393. */
  58394. this.ray = null;
  58395. }
  58396. /**
  58397. * Gets the normal correspodning to the face the pick collided with
  58398. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  58399. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  58400. * @returns The normal correspodning to the face the pick collided with
  58401. */
  58402. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  58403. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  58404. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  58405. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58406. return null;
  58407. }
  58408. var indices = this.pickedMesh.getIndices();
  58409. if (!indices) {
  58410. return null;
  58411. }
  58412. var result;
  58413. if (useVerticesNormals) {
  58414. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58415. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  58416. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  58417. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  58418. normal0 = normal0.scale(this.bu);
  58419. normal1 = normal1.scale(this.bv);
  58420. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  58421. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  58422. }
  58423. else {
  58424. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58425. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  58426. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  58427. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  58428. var p1p2 = vertex1.subtract(vertex2);
  58429. var p3p2 = vertex3.subtract(vertex2);
  58430. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  58431. }
  58432. if (useWorldCoordinates) {
  58433. var wm = this.pickedMesh.getWorldMatrix();
  58434. if (this.pickedMesh.nonUniformScaling) {
  58435. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  58436. wm = BABYLON.Tmp.Matrix[0];
  58437. wm.setTranslationFromFloats(0, 0, 0);
  58438. wm.invert();
  58439. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  58440. wm = BABYLON.Tmp.Matrix[1];
  58441. }
  58442. result = BABYLON.Vector3.TransformNormal(result, wm);
  58443. }
  58444. result.normalize();
  58445. return result;
  58446. };
  58447. /**
  58448. * Gets the texture coordinates of where the pick occured
  58449. * @returns the vector containing the coordnates of the texture
  58450. */
  58451. PickingInfo.prototype.getTextureCoordinates = function () {
  58452. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58453. return null;
  58454. }
  58455. var indices = this.pickedMesh.getIndices();
  58456. if (!indices) {
  58457. return null;
  58458. }
  58459. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58460. if (!uvs) {
  58461. return null;
  58462. }
  58463. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  58464. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  58465. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  58466. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  58467. uv1 = uv1.scale(this.bu);
  58468. uv2 = uv2.scale(this.bv);
  58469. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  58470. };
  58471. return PickingInfo;
  58472. }());
  58473. BABYLON.PickingInfo = PickingInfo;
  58474. })(BABYLON || (BABYLON = {}));
  58475. //# sourceMappingURL=babylon.pickingInfo.js.map
  58476. var BABYLON;
  58477. (function (BABYLON) {
  58478. /**
  58479. * Class representing a ray with position and direction
  58480. */
  58481. var Ray = /** @class */ (function () {
  58482. /**
  58483. * Creates a new ray
  58484. * @param origin origin point
  58485. * @param direction direction
  58486. * @param length length of the ray
  58487. */
  58488. function Ray(
  58489. /** origin point */
  58490. origin,
  58491. /** direction */
  58492. direction,
  58493. /** length of the ray */
  58494. length) {
  58495. if (length === void 0) { length = Number.MAX_VALUE; }
  58496. this.origin = origin;
  58497. this.direction = direction;
  58498. this.length = length;
  58499. }
  58500. // Methods
  58501. /**
  58502. * Checks if the ray intersects a box
  58503. * @param minimum bound of the box
  58504. * @param maximum bound of the box
  58505. * @returns if the box was hit
  58506. */
  58507. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  58508. var d = 0.0;
  58509. var maxValue = Number.MAX_VALUE;
  58510. var inv;
  58511. var min;
  58512. var max;
  58513. var temp;
  58514. if (Math.abs(this.direction.x) < 0.0000001) {
  58515. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  58516. return false;
  58517. }
  58518. }
  58519. else {
  58520. inv = 1.0 / this.direction.x;
  58521. min = (minimum.x - this.origin.x) * inv;
  58522. max = (maximum.x - this.origin.x) * inv;
  58523. if (max === -Infinity) {
  58524. max = Infinity;
  58525. }
  58526. if (min > max) {
  58527. temp = min;
  58528. min = max;
  58529. max = temp;
  58530. }
  58531. d = Math.max(min, d);
  58532. maxValue = Math.min(max, maxValue);
  58533. if (d > maxValue) {
  58534. return false;
  58535. }
  58536. }
  58537. if (Math.abs(this.direction.y) < 0.0000001) {
  58538. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  58539. return false;
  58540. }
  58541. }
  58542. else {
  58543. inv = 1.0 / this.direction.y;
  58544. min = (minimum.y - this.origin.y) * inv;
  58545. max = (maximum.y - this.origin.y) * inv;
  58546. if (max === -Infinity) {
  58547. max = Infinity;
  58548. }
  58549. if (min > max) {
  58550. temp = min;
  58551. min = max;
  58552. max = temp;
  58553. }
  58554. d = Math.max(min, d);
  58555. maxValue = Math.min(max, maxValue);
  58556. if (d > maxValue) {
  58557. return false;
  58558. }
  58559. }
  58560. if (Math.abs(this.direction.z) < 0.0000001) {
  58561. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  58562. return false;
  58563. }
  58564. }
  58565. else {
  58566. inv = 1.0 / this.direction.z;
  58567. min = (minimum.z - this.origin.z) * inv;
  58568. max = (maximum.z - this.origin.z) * inv;
  58569. if (max === -Infinity) {
  58570. max = Infinity;
  58571. }
  58572. if (min > max) {
  58573. temp = min;
  58574. min = max;
  58575. max = temp;
  58576. }
  58577. d = Math.max(min, d);
  58578. maxValue = Math.min(max, maxValue);
  58579. if (d > maxValue) {
  58580. return false;
  58581. }
  58582. }
  58583. return true;
  58584. };
  58585. /**
  58586. * Checks if the ray intersects a box
  58587. * @param box the bounding box to check
  58588. * @returns if the box was hit
  58589. */
  58590. Ray.prototype.intersectsBox = function (box) {
  58591. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  58592. };
  58593. /**
  58594. * If the ray hits a sphere
  58595. * @param sphere the bounding sphere to check
  58596. * @returns true if it hits the sphere
  58597. */
  58598. Ray.prototype.intersectsSphere = function (sphere) {
  58599. var x = sphere.center.x - this.origin.x;
  58600. var y = sphere.center.y - this.origin.y;
  58601. var z = sphere.center.z - this.origin.z;
  58602. var pyth = (x * x) + (y * y) + (z * z);
  58603. var rr = sphere.radius * sphere.radius;
  58604. if (pyth <= rr) {
  58605. return true;
  58606. }
  58607. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  58608. if (dot < 0.0) {
  58609. return false;
  58610. }
  58611. var temp = pyth - (dot * dot);
  58612. return temp <= rr;
  58613. };
  58614. /**
  58615. * If the ray hits a triange
  58616. * @param vertex0 triangle vertex
  58617. * @param vertex1 triangle vertex
  58618. * @param vertex2 triangle vertex
  58619. * @returns intersection information if hit
  58620. */
  58621. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  58622. if (!this._edge1) {
  58623. this._edge1 = BABYLON.Vector3.Zero();
  58624. this._edge2 = BABYLON.Vector3.Zero();
  58625. this._pvec = BABYLON.Vector3.Zero();
  58626. this._tvec = BABYLON.Vector3.Zero();
  58627. this._qvec = BABYLON.Vector3.Zero();
  58628. }
  58629. vertex1.subtractToRef(vertex0, this._edge1);
  58630. vertex2.subtractToRef(vertex0, this._edge2);
  58631. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  58632. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  58633. if (det === 0) {
  58634. return null;
  58635. }
  58636. var invdet = 1 / det;
  58637. this.origin.subtractToRef(vertex0, this._tvec);
  58638. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  58639. if (bu < 0 || bu > 1.0) {
  58640. return null;
  58641. }
  58642. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  58643. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  58644. if (bv < 0 || bu + bv > 1.0) {
  58645. return null;
  58646. }
  58647. //check if the distance is longer than the predefined length.
  58648. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  58649. if (distance > this.length) {
  58650. return null;
  58651. }
  58652. return new BABYLON.IntersectionInfo(bu, bv, distance);
  58653. };
  58654. /**
  58655. * Checks if ray intersects a plane
  58656. * @param plane the plane to check
  58657. * @returns the distance away it was hit
  58658. */
  58659. Ray.prototype.intersectsPlane = function (plane) {
  58660. var distance;
  58661. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  58662. if (Math.abs(result1) < 9.99999997475243E-07) {
  58663. return null;
  58664. }
  58665. else {
  58666. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  58667. distance = (-plane.d - result2) / result1;
  58668. if (distance < 0.0) {
  58669. if (distance < -9.99999997475243E-07) {
  58670. return null;
  58671. }
  58672. else {
  58673. return 0;
  58674. }
  58675. }
  58676. return distance;
  58677. }
  58678. };
  58679. /**
  58680. * Checks if ray intersects a mesh
  58681. * @param mesh the mesh to check
  58682. * @param fastCheck if only the bounding box should checked
  58683. * @returns picking info of the intersecton
  58684. */
  58685. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  58686. var tm = BABYLON.Tmp.Matrix[0];
  58687. mesh.getWorldMatrix().invertToRef(tm);
  58688. if (this._tmpRay) {
  58689. Ray.TransformToRef(this, tm, this._tmpRay);
  58690. }
  58691. else {
  58692. this._tmpRay = Ray.Transform(this, tm);
  58693. }
  58694. return mesh.intersects(this._tmpRay, fastCheck);
  58695. };
  58696. /**
  58697. * Checks if ray intersects a mesh
  58698. * @param meshes the meshes to check
  58699. * @param fastCheck if only the bounding box should checked
  58700. * @param results array to store result in
  58701. * @returns Array of picking infos
  58702. */
  58703. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  58704. if (results) {
  58705. results.length = 0;
  58706. }
  58707. else {
  58708. results = [];
  58709. }
  58710. for (var i = 0; i < meshes.length; i++) {
  58711. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  58712. if (pickInfo.hit) {
  58713. results.push(pickInfo);
  58714. }
  58715. }
  58716. results.sort(this._comparePickingInfo);
  58717. return results;
  58718. };
  58719. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  58720. if (pickingInfoA.distance < pickingInfoB.distance) {
  58721. return -1;
  58722. }
  58723. else if (pickingInfoA.distance > pickingInfoB.distance) {
  58724. return 1;
  58725. }
  58726. else {
  58727. return 0;
  58728. }
  58729. };
  58730. /**
  58731. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  58732. * @param sega the first point of the segment to test the intersection against
  58733. * @param segb the second point of the segment to test the intersection against
  58734. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  58735. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  58736. */
  58737. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  58738. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  58739. var u = segb.subtract(sega);
  58740. var v = rsegb.subtract(this.origin);
  58741. var w = sega.subtract(this.origin);
  58742. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  58743. var b = BABYLON.Vector3.Dot(u, v);
  58744. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  58745. var d = BABYLON.Vector3.Dot(u, w);
  58746. var e = BABYLON.Vector3.Dot(v, w);
  58747. var D = a * c - b * b; // always >= 0
  58748. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  58749. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  58750. // compute the line parameters of the two closest points
  58751. if (D < Ray.smallnum) { // the lines are almost parallel
  58752. sN = 0.0; // force using point P0 on segment S1
  58753. sD = 1.0; // to prevent possible division by 0.0 later
  58754. tN = e;
  58755. tD = c;
  58756. }
  58757. else { // get the closest points on the infinite lines
  58758. sN = (b * e - c * d);
  58759. tN = (a * e - b * d);
  58760. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  58761. sN = 0.0;
  58762. tN = e;
  58763. tD = c;
  58764. }
  58765. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  58766. sN = sD;
  58767. tN = e + b;
  58768. tD = c;
  58769. }
  58770. }
  58771. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  58772. tN = 0.0;
  58773. // recompute sc for this edge
  58774. if (-d < 0.0) {
  58775. sN = 0.0;
  58776. }
  58777. else if (-d > a) {
  58778. sN = sD;
  58779. }
  58780. else {
  58781. sN = -d;
  58782. sD = a;
  58783. }
  58784. }
  58785. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  58786. tN = tD;
  58787. // recompute sc for this edge
  58788. if ((-d + b) < 0.0) {
  58789. sN = 0;
  58790. }
  58791. else if ((-d + b) > a) {
  58792. sN = sD;
  58793. }
  58794. else {
  58795. sN = (-d + b);
  58796. sD = a;
  58797. }
  58798. }
  58799. // finally do the division to get sc and tc
  58800. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  58801. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  58802. // get the difference of the two closest points
  58803. var qtc = v.multiplyByFloats(tc, tc, tc);
  58804. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  58805. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  58806. if (isIntersected) {
  58807. return qtc.length();
  58808. }
  58809. return -1;
  58810. };
  58811. /**
  58812. * Update the ray from viewport position
  58813. * @param x position
  58814. * @param y y position
  58815. * @param viewportWidth viewport width
  58816. * @param viewportHeight viewport height
  58817. * @param world world matrix
  58818. * @param view view matrix
  58819. * @param projection projection matrix
  58820. * @returns this ray updated
  58821. */
  58822. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58823. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  58824. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  58825. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  58826. this.direction.normalize();
  58827. return this;
  58828. };
  58829. // Statics
  58830. /**
  58831. * Creates a ray with origin and direction of 0,0,0
  58832. * @returns the new ray
  58833. */
  58834. Ray.Zero = function () {
  58835. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  58836. };
  58837. /**
  58838. * Creates a new ray from screen space and viewport
  58839. * @param x position
  58840. * @param y y position
  58841. * @param viewportWidth viewport width
  58842. * @param viewportHeight viewport height
  58843. * @param world world matrix
  58844. * @param view view matrix
  58845. * @param projection projection matrix
  58846. * @returns new ray
  58847. */
  58848. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58849. var result = Ray.Zero();
  58850. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  58851. };
  58852. /**
  58853. * 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
  58854. * transformed to the given world matrix.
  58855. * @param origin The origin point
  58856. * @param end The end point
  58857. * @param world a matrix to transform the ray to. Default is the identity matrix.
  58858. * @returns the new ray
  58859. */
  58860. Ray.CreateNewFromTo = function (origin, end, world) {
  58861. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  58862. var direction = end.subtract(origin);
  58863. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  58864. direction.normalize();
  58865. return Ray.Transform(new Ray(origin, direction, length), world);
  58866. };
  58867. /**
  58868. * Transforms a ray by a matrix
  58869. * @param ray ray to transform
  58870. * @param matrix matrix to apply
  58871. * @returns the resulting new ray
  58872. */
  58873. Ray.Transform = function (ray, matrix) {
  58874. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  58875. Ray.TransformToRef(ray, matrix, result);
  58876. return result;
  58877. };
  58878. /**
  58879. * Transforms a ray by a matrix
  58880. * @param ray ray to transform
  58881. * @param matrix matrix to apply
  58882. * @param result ray to store result in
  58883. */
  58884. Ray.TransformToRef = function (ray, matrix, result) {
  58885. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  58886. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  58887. result.length = ray.length;
  58888. var dir = result.direction;
  58889. var len = dir.length();
  58890. if (!(len === 0 || len === 1)) {
  58891. var num = 1.0 / len;
  58892. dir.x *= num;
  58893. dir.y *= num;
  58894. dir.z *= num;
  58895. result.length *= len;
  58896. }
  58897. };
  58898. Ray.smallnum = 0.00000001;
  58899. Ray.rayl = 10e8;
  58900. return Ray;
  58901. }());
  58902. BABYLON.Ray = Ray;
  58903. })(BABYLON || (BABYLON = {}));
  58904. //# sourceMappingURL=babylon.ray.js.map
  58905. var BABYLON;
  58906. (function (BABYLON) {
  58907. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  58908. if (boxMin.x > sphereCenter.x + sphereRadius) {
  58909. return false;
  58910. }
  58911. if (sphereCenter.x - sphereRadius > boxMax.x) {
  58912. return false;
  58913. }
  58914. if (boxMin.y > sphereCenter.y + sphereRadius) {
  58915. return false;
  58916. }
  58917. if (sphereCenter.y - sphereRadius > boxMax.y) {
  58918. return false;
  58919. }
  58920. if (boxMin.z > sphereCenter.z + sphereRadius) {
  58921. return false;
  58922. }
  58923. if (sphereCenter.z - sphereRadius > boxMax.z) {
  58924. return false;
  58925. }
  58926. return true;
  58927. };
  58928. var getLowestRoot = (function () {
  58929. var result = { root: 0, found: false };
  58930. return function (a, b, c, maxR) {
  58931. result.root = 0;
  58932. result.found = false;
  58933. var determinant = b * b - 4.0 * a * c;
  58934. if (determinant < 0) {
  58935. return result;
  58936. }
  58937. var sqrtD = Math.sqrt(determinant);
  58938. var r1 = (-b - sqrtD) / (2.0 * a);
  58939. var r2 = (-b + sqrtD) / (2.0 * a);
  58940. if (r1 > r2) {
  58941. var temp = r2;
  58942. r2 = r1;
  58943. r1 = temp;
  58944. }
  58945. if (r1 > 0 && r1 < maxR) {
  58946. result.root = r1;
  58947. result.found = true;
  58948. return result;
  58949. }
  58950. if (r2 > 0 && r2 < maxR) {
  58951. result.root = r2;
  58952. result.found = true;
  58953. return result;
  58954. }
  58955. return result;
  58956. };
  58957. })();
  58958. /** @hidden */
  58959. var Collider = /** @class */ (function () {
  58960. function Collider() {
  58961. this._collisionPoint = BABYLON.Vector3.Zero();
  58962. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  58963. this._tempVector = BABYLON.Vector3.Zero();
  58964. this._tempVector2 = BABYLON.Vector3.Zero();
  58965. this._tempVector3 = BABYLON.Vector3.Zero();
  58966. this._tempVector4 = BABYLON.Vector3.Zero();
  58967. this._edge = BABYLON.Vector3.Zero();
  58968. this._baseToVertex = BABYLON.Vector3.Zero();
  58969. this._destinationPoint = BABYLON.Vector3.Zero();
  58970. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  58971. this._displacementVector = BABYLON.Vector3.Zero();
  58972. /** @hidden */
  58973. this._radius = BABYLON.Vector3.One();
  58974. /** @hidden */
  58975. this._retry = 0;
  58976. /** @hidden */
  58977. this._basePointWorld = BABYLON.Vector3.Zero();
  58978. this._velocityWorld = BABYLON.Vector3.Zero();
  58979. this._normalizedVelocity = BABYLON.Vector3.Zero();
  58980. this._collisionMask = -1;
  58981. }
  58982. Object.defineProperty(Collider.prototype, "collisionMask", {
  58983. get: function () {
  58984. return this._collisionMask;
  58985. },
  58986. set: function (mask) {
  58987. this._collisionMask = !isNaN(mask) ? mask : -1;
  58988. },
  58989. enumerable: true,
  58990. configurable: true
  58991. });
  58992. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  58993. /**
  58994. * Gets the plane normal used to compute the sliding response (in local space)
  58995. */
  58996. get: function () {
  58997. return this._slidePlaneNormal;
  58998. },
  58999. enumerable: true,
  59000. configurable: true
  59001. });
  59002. // Methods
  59003. /** @hidden */
  59004. Collider.prototype._initialize = function (source, dir, e) {
  59005. this._velocity = dir;
  59006. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  59007. this._basePoint = source;
  59008. source.multiplyToRef(this._radius, this._basePointWorld);
  59009. dir.multiplyToRef(this._radius, this._velocityWorld);
  59010. this._velocityWorldLength = this._velocityWorld.length();
  59011. this._epsilon = e;
  59012. this.collisionFound = false;
  59013. };
  59014. /** @hidden */
  59015. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  59016. pa.subtractToRef(point, this._tempVector);
  59017. pb.subtractToRef(point, this._tempVector2);
  59018. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  59019. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59020. if (d < 0) {
  59021. return false;
  59022. }
  59023. pc.subtractToRef(point, this._tempVector3);
  59024. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  59025. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59026. if (d < 0) {
  59027. return false;
  59028. }
  59029. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  59030. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59031. return d >= 0;
  59032. };
  59033. /** @hidden */
  59034. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  59035. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  59036. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  59037. if (distance > this._velocityWorldLength + max + sphereRadius) {
  59038. return false;
  59039. }
  59040. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  59041. return false;
  59042. }
  59043. return true;
  59044. };
  59045. /** @hidden */
  59046. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  59047. var t0;
  59048. var embeddedInPlane = false;
  59049. //defensive programming, actually not needed.
  59050. if (!trianglePlaneArray) {
  59051. trianglePlaneArray = [];
  59052. }
  59053. if (!trianglePlaneArray[faceIndex]) {
  59054. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  59055. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  59056. }
  59057. var trianglePlane = trianglePlaneArray[faceIndex];
  59058. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  59059. return;
  59060. }
  59061. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  59062. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  59063. if (normalDotVelocity == 0) {
  59064. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  59065. return;
  59066. }
  59067. embeddedInPlane = true;
  59068. t0 = 0;
  59069. }
  59070. else {
  59071. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59072. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59073. if (t0 > t1) {
  59074. var temp = t1;
  59075. t1 = t0;
  59076. t0 = temp;
  59077. }
  59078. if (t0 > 1.0 || t1 < 0.0) {
  59079. return;
  59080. }
  59081. if (t0 < 0) {
  59082. t0 = 0;
  59083. }
  59084. if (t0 > 1.0) {
  59085. t0 = 1.0;
  59086. }
  59087. }
  59088. this._collisionPoint.copyFromFloats(0, 0, 0);
  59089. var found = false;
  59090. var t = 1.0;
  59091. if (!embeddedInPlane) {
  59092. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  59093. this._velocity.scaleToRef(t0, this._tempVector);
  59094. this._planeIntersectionPoint.addInPlace(this._tempVector);
  59095. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  59096. found = true;
  59097. t = t0;
  59098. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  59099. }
  59100. }
  59101. if (!found) {
  59102. var velocitySquaredLength = this._velocity.lengthSquared();
  59103. var a = velocitySquaredLength;
  59104. this._basePoint.subtractToRef(p1, this._tempVector);
  59105. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59106. var c = this._tempVector.lengthSquared() - 1.0;
  59107. var lowestRoot = getLowestRoot(a, b, c, t);
  59108. if (lowestRoot.found) {
  59109. t = lowestRoot.root;
  59110. found = true;
  59111. this._collisionPoint.copyFrom(p1);
  59112. }
  59113. this._basePoint.subtractToRef(p2, this._tempVector);
  59114. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59115. c = this._tempVector.lengthSquared() - 1.0;
  59116. lowestRoot = getLowestRoot(a, b, c, t);
  59117. if (lowestRoot.found) {
  59118. t = lowestRoot.root;
  59119. found = true;
  59120. this._collisionPoint.copyFrom(p2);
  59121. }
  59122. this._basePoint.subtractToRef(p3, this._tempVector);
  59123. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59124. c = this._tempVector.lengthSquared() - 1.0;
  59125. lowestRoot = getLowestRoot(a, b, c, t);
  59126. if (lowestRoot.found) {
  59127. t = lowestRoot.root;
  59128. found = true;
  59129. this._collisionPoint.copyFrom(p3);
  59130. }
  59131. p2.subtractToRef(p1, this._edge);
  59132. p1.subtractToRef(this._basePoint, this._baseToVertex);
  59133. var edgeSquaredLength = this._edge.lengthSquared();
  59134. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59135. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59136. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59137. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59138. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59139. lowestRoot = getLowestRoot(a, b, c, t);
  59140. if (lowestRoot.found) {
  59141. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59142. if (f >= 0.0 && f <= 1.0) {
  59143. t = lowestRoot.root;
  59144. found = true;
  59145. this._edge.scaleInPlace(f);
  59146. p1.addToRef(this._edge, this._collisionPoint);
  59147. }
  59148. }
  59149. p3.subtractToRef(p2, this._edge);
  59150. p2.subtractToRef(this._basePoint, this._baseToVertex);
  59151. edgeSquaredLength = this._edge.lengthSquared();
  59152. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59153. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59154. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59155. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59156. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59157. lowestRoot = getLowestRoot(a, b, c, t);
  59158. if (lowestRoot.found) {
  59159. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59160. if (f >= 0.0 && f <= 1.0) {
  59161. t = lowestRoot.root;
  59162. found = true;
  59163. this._edge.scaleInPlace(f);
  59164. p2.addToRef(this._edge, this._collisionPoint);
  59165. }
  59166. }
  59167. p1.subtractToRef(p3, this._edge);
  59168. p3.subtractToRef(this._basePoint, this._baseToVertex);
  59169. edgeSquaredLength = this._edge.lengthSquared();
  59170. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59171. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59172. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59173. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59174. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59175. lowestRoot = getLowestRoot(a, b, c, t);
  59176. if (lowestRoot.found) {
  59177. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59178. if (f >= 0.0 && f <= 1.0) {
  59179. t = lowestRoot.root;
  59180. found = true;
  59181. this._edge.scaleInPlace(f);
  59182. p3.addToRef(this._edge, this._collisionPoint);
  59183. }
  59184. }
  59185. }
  59186. if (found) {
  59187. var distToCollision = t * this._velocity.length();
  59188. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  59189. if (!this.intersectionPoint) {
  59190. this.intersectionPoint = this._collisionPoint.clone();
  59191. }
  59192. else {
  59193. this.intersectionPoint.copyFrom(this._collisionPoint);
  59194. }
  59195. this._nearestDistance = distToCollision;
  59196. this.collisionFound = true;
  59197. }
  59198. }
  59199. };
  59200. /** @hidden */
  59201. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  59202. for (var i = indexStart; i < indexEnd; i += 3) {
  59203. var p1 = pts[indices[i] - decal];
  59204. var p2 = pts[indices[i + 1] - decal];
  59205. var p3 = pts[indices[i + 2] - decal];
  59206. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  59207. }
  59208. };
  59209. /** @hidden */
  59210. Collider.prototype._getResponse = function (pos, vel) {
  59211. pos.addToRef(vel, this._destinationPoint);
  59212. vel.scaleInPlace((this._nearestDistance / vel.length()));
  59213. this._basePoint.addToRef(vel, pos);
  59214. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  59215. this._slidePlaneNormal.normalize();
  59216. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  59217. pos.addInPlace(this._displacementVector);
  59218. this.intersectionPoint.addInPlace(this._displacementVector);
  59219. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  59220. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  59221. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  59222. };
  59223. return Collider;
  59224. }());
  59225. BABYLON.Collider = Collider;
  59226. })(BABYLON || (BABYLON = {}));
  59227. //# sourceMappingURL=babylon.collider.js.map
  59228. var BABYLON;
  59229. (function (BABYLON) {
  59230. //WebWorker code will be inserted to this variable.
  59231. /** @hidden */
  59232. BABYLON.CollisionWorker = "";
  59233. /** Defines supported task for worker process */
  59234. var WorkerTaskType;
  59235. (function (WorkerTaskType) {
  59236. /** Initialization */
  59237. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  59238. /** Update of geometry */
  59239. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  59240. /** Evaluate collision */
  59241. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  59242. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  59243. /** Defines kind of replies returned by worker */
  59244. var WorkerReplyType;
  59245. (function (WorkerReplyType) {
  59246. /** Success */
  59247. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  59248. /** Unkown error */
  59249. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  59250. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  59251. /** @hidden */
  59252. var CollisionCoordinatorWorker = /** @class */ (function () {
  59253. function CollisionCoordinatorWorker() {
  59254. var _this = this;
  59255. this._scaledPosition = BABYLON.Vector3.Zero();
  59256. this._scaledVelocity = BABYLON.Vector3.Zero();
  59257. this.onMeshUpdated = function (transformNode) {
  59258. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  59259. };
  59260. this.onGeometryUpdated = function (geometry) {
  59261. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  59262. };
  59263. this._afterRender = function () {
  59264. if (!_this._init) {
  59265. return;
  59266. }
  59267. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  59268. return;
  59269. }
  59270. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  59271. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  59272. if (_this._runningUpdated > 4) {
  59273. return;
  59274. }
  59275. ++_this._runningUpdated;
  59276. var payload = {
  59277. updatedMeshes: _this._addUpdateMeshesList,
  59278. updatedGeometries: _this._addUpdateGeometriesList,
  59279. removedGeometries: _this._toRemoveGeometryArray,
  59280. removedMeshes: _this._toRemoveMeshesArray
  59281. };
  59282. var message = {
  59283. payload: payload,
  59284. taskType: WorkerTaskType.UPDATE
  59285. };
  59286. var serializable = [];
  59287. for (var id in payload.updatedGeometries) {
  59288. if (payload.updatedGeometries.hasOwnProperty(id)) {
  59289. //prepare transferables
  59290. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  59291. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  59292. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  59293. }
  59294. }
  59295. _this._worker.postMessage(message, serializable);
  59296. _this._addUpdateMeshesList = {};
  59297. _this._addUpdateGeometriesList = {};
  59298. _this._toRemoveGeometryArray = [];
  59299. _this._toRemoveMeshesArray = [];
  59300. };
  59301. this._onMessageFromWorker = function (e) {
  59302. var returnData = e.data;
  59303. if (returnData.error != WorkerReplyType.SUCCESS) {
  59304. //TODO what errors can be returned from the worker?
  59305. BABYLON.Tools.Warn("error returned from worker!");
  59306. return;
  59307. }
  59308. switch (returnData.taskType) {
  59309. case WorkerTaskType.INIT:
  59310. _this._init = true;
  59311. //Update the worked with ALL of the scene's current state
  59312. _this._scene.meshes.forEach(function (mesh) {
  59313. _this.onMeshAdded(mesh);
  59314. });
  59315. _this._scene.getGeometries().forEach(function (geometry) {
  59316. _this.onGeometryAdded(geometry);
  59317. });
  59318. break;
  59319. case WorkerTaskType.UPDATE:
  59320. _this._runningUpdated--;
  59321. break;
  59322. case WorkerTaskType.COLLIDE:
  59323. var returnPayload = returnData.payload;
  59324. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  59325. return;
  59326. }
  59327. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  59328. if (callback) {
  59329. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  59330. if (mesh) {
  59331. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  59332. }
  59333. }
  59334. //cleanup
  59335. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  59336. break;
  59337. }
  59338. };
  59339. this._collisionsCallbackArray = [];
  59340. this._init = false;
  59341. this._runningUpdated = 0;
  59342. this._addUpdateMeshesList = {};
  59343. this._addUpdateGeometriesList = {};
  59344. this._toRemoveGeometryArray = [];
  59345. this._toRemoveMeshesArray = [];
  59346. }
  59347. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59348. if (!this._init) {
  59349. return;
  59350. }
  59351. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  59352. return;
  59353. }
  59354. position.divideToRef(collider._radius, this._scaledPosition);
  59355. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59356. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  59357. var payload = {
  59358. collider: {
  59359. position: this._scaledPosition.asArray(),
  59360. velocity: this._scaledVelocity.asArray(),
  59361. radius: collider._radius.asArray()
  59362. },
  59363. collisionId: collisionIndex,
  59364. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  59365. maximumRetry: maximumRetry
  59366. };
  59367. var message = {
  59368. payload: payload,
  59369. taskType: WorkerTaskType.COLLIDE
  59370. };
  59371. this._worker.postMessage(message);
  59372. };
  59373. CollisionCoordinatorWorker.prototype.init = function (scene) {
  59374. this._scene = scene;
  59375. this._scene.registerAfterRender(this._afterRender);
  59376. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  59377. this._worker = new Worker(workerUrl);
  59378. this._worker.onmessage = this._onMessageFromWorker;
  59379. var message = {
  59380. payload: {},
  59381. taskType: WorkerTaskType.INIT
  59382. };
  59383. this._worker.postMessage(message);
  59384. };
  59385. CollisionCoordinatorWorker.prototype.destroy = function () {
  59386. this._scene.unregisterAfterRender(this._afterRender);
  59387. this._worker.terminate();
  59388. };
  59389. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  59390. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  59391. this.onMeshUpdated(mesh);
  59392. };
  59393. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  59394. this._toRemoveMeshesArray.push(mesh.uniqueId);
  59395. };
  59396. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  59397. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  59398. geometry.onGeometryUpdated = this.onGeometryUpdated;
  59399. this.onGeometryUpdated(geometry);
  59400. };
  59401. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  59402. this._toRemoveGeometryArray.push(geometry.id);
  59403. };
  59404. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  59405. var submeshes = [];
  59406. if (mesh.subMeshes) {
  59407. submeshes = mesh.subMeshes.map(function (sm, idx) {
  59408. var boundingInfo = sm.getBoundingInfo();
  59409. return {
  59410. position: idx,
  59411. verticesStart: sm.verticesStart,
  59412. verticesCount: sm.verticesCount,
  59413. indexStart: sm.indexStart,
  59414. indexCount: sm.indexCount,
  59415. hasMaterial: !!sm.getMaterial(),
  59416. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59417. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59418. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59419. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  59420. };
  59421. });
  59422. }
  59423. var geometryId = null;
  59424. if (mesh instanceof BABYLON.Mesh) {
  59425. var geometry = mesh.geometry;
  59426. geometryId = geometry ? geometry.id : null;
  59427. }
  59428. else if (mesh instanceof BABYLON.InstancedMesh) {
  59429. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  59430. geometryId = geometry ? geometry.id : null;
  59431. }
  59432. var boundingInfo = mesh.getBoundingInfo();
  59433. return {
  59434. uniqueId: mesh.uniqueId,
  59435. id: mesh.id,
  59436. name: mesh.name,
  59437. geometryId: geometryId,
  59438. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59439. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59440. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59441. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  59442. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  59443. subMeshes: submeshes,
  59444. checkCollisions: mesh.checkCollisions
  59445. };
  59446. };
  59447. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  59448. return {
  59449. id: geometry.id,
  59450. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  59451. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  59452. indices: new Uint32Array(geometry.getIndices() || []),
  59453. };
  59454. };
  59455. return CollisionCoordinatorWorker;
  59456. }());
  59457. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  59458. /** @hidden */
  59459. var CollisionCoordinatorLegacy = /** @class */ (function () {
  59460. function CollisionCoordinatorLegacy() {
  59461. this._scaledPosition = BABYLON.Vector3.Zero();
  59462. this._scaledVelocity = BABYLON.Vector3.Zero();
  59463. this._finalPosition = BABYLON.Vector3.Zero();
  59464. }
  59465. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59466. position.divideToRef(collider._radius, this._scaledPosition);
  59467. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59468. collider.collidedMesh = null;
  59469. collider._retry = 0;
  59470. collider._initialVelocity = this._scaledVelocity;
  59471. collider._initialPosition = this._scaledPosition;
  59472. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  59473. this._finalPosition.multiplyInPlace(collider._radius);
  59474. //run the callback
  59475. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  59476. };
  59477. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  59478. this._scene = scene;
  59479. };
  59480. CollisionCoordinatorLegacy.prototype.destroy = function () {
  59481. //Legacy need no destruction method.
  59482. };
  59483. //No update in legacy mode
  59484. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  59485. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  59486. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  59487. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  59488. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  59489. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  59490. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  59491. if (excludedMesh === void 0) { excludedMesh = null; }
  59492. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  59493. if (collider._retry >= maximumRetry) {
  59494. finalPosition.copyFrom(position);
  59495. return;
  59496. }
  59497. // Check if this is a mesh else camera or -1
  59498. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  59499. collider._initialize(position, velocity, closeDistance);
  59500. // Check all meshes
  59501. for (var index = 0; index < this._scene.meshes.length; index++) {
  59502. var mesh = this._scene.meshes[index];
  59503. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  59504. mesh._checkCollision(collider);
  59505. }
  59506. }
  59507. if (!collider.collisionFound) {
  59508. position.addToRef(velocity, finalPosition);
  59509. return;
  59510. }
  59511. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  59512. collider._getResponse(position, velocity);
  59513. }
  59514. if (velocity.length() <= closeDistance) {
  59515. finalPosition.copyFrom(position);
  59516. return;
  59517. }
  59518. collider._retry++;
  59519. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  59520. };
  59521. return CollisionCoordinatorLegacy;
  59522. }());
  59523. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  59524. })(BABYLON || (BABYLON = {}));
  59525. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  59526. var BABYLON;
  59527. (function (BABYLON) {
  59528. /**
  59529. * A particle represents one of the element emitted by a particle system.
  59530. * This is mainly define by its coordinates, direction, velocity and age.
  59531. */
  59532. var Particle = /** @class */ (function () {
  59533. /**
  59534. * Creates a new instance Particle
  59535. * @param particleSystem the particle system the particle belongs to
  59536. */
  59537. function Particle(
  59538. /**
  59539. * The particle system the particle belongs to.
  59540. */
  59541. particleSystem) {
  59542. this.particleSystem = particleSystem;
  59543. /**
  59544. * The world position of the particle in the scene.
  59545. */
  59546. this.position = BABYLON.Vector3.Zero();
  59547. /**
  59548. * The world direction of the particle in the scene.
  59549. */
  59550. this.direction = BABYLON.Vector3.Zero();
  59551. /**
  59552. * The color of the particle.
  59553. */
  59554. this.color = new BABYLON.Color4(0, 0, 0, 0);
  59555. /**
  59556. * The color change of the particle per step.
  59557. */
  59558. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  59559. /**
  59560. * Defines how long will the life of the particle be.
  59561. */
  59562. this.lifeTime = 1.0;
  59563. /**
  59564. * The current age of the particle.
  59565. */
  59566. this.age = 0;
  59567. /**
  59568. * The current size of the particle.
  59569. */
  59570. this.size = 0;
  59571. /**
  59572. * The current scale of the particle.
  59573. */
  59574. this.scale = new BABYLON.Vector2(1, 1);
  59575. /**
  59576. * The current angle of the particle.
  59577. */
  59578. this.angle = 0;
  59579. /**
  59580. * Defines how fast is the angle changing.
  59581. */
  59582. this.angularSpeed = 0;
  59583. /**
  59584. * Defines the cell index used by the particle to be rendered from a sprite.
  59585. */
  59586. this.cellIndex = 0;
  59587. /** @hidden */
  59588. this._attachedSubEmitters = null;
  59589. /** @hidden */
  59590. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  59591. /** @hidden */
  59592. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  59593. /** @hidden */
  59594. this._currentSize1 = 0;
  59595. /** @hidden */
  59596. this._currentSize2 = 0;
  59597. /** @hidden */
  59598. this._currentAngularSpeed1 = 0;
  59599. /** @hidden */
  59600. this._currentAngularSpeed2 = 0;
  59601. /** @hidden */
  59602. this._currentVelocity1 = 0;
  59603. /** @hidden */
  59604. this._currentVelocity2 = 0;
  59605. /** @hidden */
  59606. this._currentLimitVelocity1 = 0;
  59607. /** @hidden */
  59608. this._currentLimitVelocity2 = 0;
  59609. /** @hidden */
  59610. this._currentDrag1 = 0;
  59611. /** @hidden */
  59612. this._currentDrag2 = 0;
  59613. this.id = Particle._Count++;
  59614. if (!this.particleSystem.isAnimationSheetEnabled) {
  59615. return;
  59616. }
  59617. this.updateCellInfoFromSystem();
  59618. }
  59619. Particle.prototype.updateCellInfoFromSystem = function () {
  59620. this.cellIndex = this.particleSystem.startSpriteCellID;
  59621. };
  59622. /**
  59623. * Defines how the sprite cell index is updated for the particle
  59624. */
  59625. Particle.prototype.updateCellIndex = function () {
  59626. var offsetAge = this.age;
  59627. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  59628. if (this.particleSystem.spriteRandomStartCell) {
  59629. if (this._randomCellOffset === undefined) {
  59630. this._randomCellOffset = Math.random() * this.lifeTime;
  59631. }
  59632. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  59633. changeSpeed = 1;
  59634. offsetAge = this._randomCellOffset;
  59635. }
  59636. else {
  59637. offsetAge += this._randomCellOffset;
  59638. }
  59639. }
  59640. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  59641. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  59642. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  59643. };
  59644. /** @hidden */
  59645. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  59646. if (subEmitter.particleSystem.emitter.position) {
  59647. var emitterMesh = subEmitter.particleSystem.emitter;
  59648. emitterMesh.position.copyFrom(this.position);
  59649. if (subEmitter.inheritDirection) {
  59650. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  59651. // Look at using Y as forward
  59652. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  59653. }
  59654. }
  59655. else {
  59656. var emitterPosition = subEmitter.particleSystem.emitter;
  59657. emitterPosition.copyFrom(this.position);
  59658. }
  59659. // Set inheritedVelocityOffset to be used when new particles are created
  59660. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  59661. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  59662. };
  59663. /** @hidden */
  59664. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  59665. var _this = this;
  59666. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  59667. this._attachedSubEmitters.forEach(function (subEmitter) {
  59668. _this._inheritParticleInfoToSubEmitter(subEmitter);
  59669. });
  59670. }
  59671. };
  59672. /** @hidden */
  59673. Particle.prototype._reset = function () {
  59674. this.age = 0;
  59675. this._currentColorGradient = null;
  59676. this._currentSizeGradient = null;
  59677. this._currentAngularSpeedGradient = null;
  59678. this._currentVelocityGradient = null;
  59679. this._currentLimitVelocityGradient = null;
  59680. this._currentDragGradient = null;
  59681. this.cellIndex = this.particleSystem.startSpriteCellID;
  59682. this._randomCellOffset = undefined;
  59683. };
  59684. /**
  59685. * Copy the properties of particle to another one.
  59686. * @param other the particle to copy the information to.
  59687. */
  59688. Particle.prototype.copyTo = function (other) {
  59689. other.position.copyFrom(this.position);
  59690. if (this._initialDirection) {
  59691. if (other._initialDirection) {
  59692. other._initialDirection.copyFrom(this._initialDirection);
  59693. }
  59694. else {
  59695. other._initialDirection = this._initialDirection.clone();
  59696. }
  59697. }
  59698. else {
  59699. other._initialDirection = null;
  59700. }
  59701. other.direction.copyFrom(this.direction);
  59702. other.color.copyFrom(this.color);
  59703. other.colorStep.copyFrom(this.colorStep);
  59704. other.lifeTime = this.lifeTime;
  59705. other.age = this.age;
  59706. other._randomCellOffset = this._randomCellOffset;
  59707. other.size = this.size;
  59708. other.scale.copyFrom(this.scale);
  59709. other.angle = this.angle;
  59710. other.angularSpeed = this.angularSpeed;
  59711. other.particleSystem = this.particleSystem;
  59712. other.cellIndex = this.cellIndex;
  59713. other.id = this.id;
  59714. other._attachedSubEmitters = this._attachedSubEmitters;
  59715. if (this._currentColorGradient) {
  59716. other._currentColorGradient = this._currentColorGradient;
  59717. other._currentColor1.copyFrom(this._currentColor1);
  59718. other._currentColor2.copyFrom(this._currentColor2);
  59719. }
  59720. if (this._currentSizeGradient) {
  59721. other._currentSizeGradient = this._currentSizeGradient;
  59722. other._currentSize1 = this._currentSize1;
  59723. other._currentSize2 = this._currentSize2;
  59724. }
  59725. if (this._currentAngularSpeedGradient) {
  59726. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  59727. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  59728. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  59729. }
  59730. if (this._currentVelocityGradient) {
  59731. other._currentVelocityGradient = this._currentVelocityGradient;
  59732. other._currentVelocity1 = this._currentVelocity1;
  59733. other._currentVelocity2 = this._currentVelocity2;
  59734. }
  59735. if (this._currentLimitVelocityGradient) {
  59736. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  59737. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  59738. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  59739. }
  59740. if (this._currentDragGradient) {
  59741. other._currentDragGradient = this._currentDragGradient;
  59742. other._currentDrag1 = this._currentDrag1;
  59743. other._currentDrag2 = this._currentDrag2;
  59744. }
  59745. if (this.particleSystem.isAnimationSheetEnabled) {
  59746. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  59747. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  59748. }
  59749. if (this.particleSystem.useRampGradients) {
  59750. other.remapData.copyFrom(this.remapData);
  59751. }
  59752. if (this._randomNoiseCoordinates1) {
  59753. if (other._randomNoiseCoordinates1) {
  59754. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  59755. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  59756. }
  59757. else {
  59758. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  59759. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  59760. }
  59761. }
  59762. };
  59763. Particle._Count = 0;
  59764. return Particle;
  59765. }());
  59766. BABYLON.Particle = Particle;
  59767. })(BABYLON || (BABYLON = {}));
  59768. //# sourceMappingURL=babylon.particle.js.map
  59769. var BABYLON;
  59770. (function (BABYLON) {
  59771. /**
  59772. * This represents the base class for particle system in Babylon.
  59773. * 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.
  59774. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59775. * @example https://doc.babylonjs.com/babylon101/particles
  59776. */
  59777. var BaseParticleSystem = /** @class */ (function () {
  59778. /**
  59779. * Instantiates a particle system.
  59780. * 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.
  59781. * @param name The name of the particle system
  59782. */
  59783. function BaseParticleSystem(name) {
  59784. /**
  59785. * List of animations used by the particle system.
  59786. */
  59787. this.animations = [];
  59788. /**
  59789. * The rendering group used by the Particle system to chose when to render.
  59790. */
  59791. this.renderingGroupId = 0;
  59792. /**
  59793. * The emitter represents the Mesh or position we are attaching the particle system to.
  59794. */
  59795. this.emitter = null;
  59796. /**
  59797. * The maximum number of particles to emit per frame
  59798. */
  59799. this.emitRate = 10;
  59800. /**
  59801. * If you want to launch only a few particles at once, that can be done, as well.
  59802. */
  59803. this.manualEmitCount = -1;
  59804. /**
  59805. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59806. */
  59807. this.updateSpeed = 0.01;
  59808. /**
  59809. * The amount of time the particle system is running (depends of the overall update speed).
  59810. */
  59811. this.targetStopDuration = 0;
  59812. /**
  59813. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  59814. */
  59815. this.disposeOnStop = false;
  59816. /**
  59817. * Minimum power of emitting particles.
  59818. */
  59819. this.minEmitPower = 1;
  59820. /**
  59821. * Maximum power of emitting particles.
  59822. */
  59823. this.maxEmitPower = 1;
  59824. /**
  59825. * Minimum life time of emitting particles.
  59826. */
  59827. this.minLifeTime = 1;
  59828. /**
  59829. * Maximum life time of emitting particles.
  59830. */
  59831. this.maxLifeTime = 1;
  59832. /**
  59833. * Minimum Size of emitting particles.
  59834. */
  59835. this.minSize = 1;
  59836. /**
  59837. * Maximum Size of emitting particles.
  59838. */
  59839. this.maxSize = 1;
  59840. /**
  59841. * Minimum scale of emitting particles on X axis.
  59842. */
  59843. this.minScaleX = 1;
  59844. /**
  59845. * Maximum scale of emitting particles on X axis.
  59846. */
  59847. this.maxScaleX = 1;
  59848. /**
  59849. * Minimum scale of emitting particles on Y axis.
  59850. */
  59851. this.minScaleY = 1;
  59852. /**
  59853. * Maximum scale of emitting particles on Y axis.
  59854. */
  59855. this.maxScaleY = 1;
  59856. /**
  59857. * Gets or sets the minimal initial rotation in radians.
  59858. */
  59859. this.minInitialRotation = 0;
  59860. /**
  59861. * Gets or sets the maximal initial rotation in radians.
  59862. */
  59863. this.maxInitialRotation = 0;
  59864. /**
  59865. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59866. */
  59867. this.minAngularSpeed = 0;
  59868. /**
  59869. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59870. */
  59871. this.maxAngularSpeed = 0;
  59872. /**
  59873. * The layer mask we are rendering the particles through.
  59874. */
  59875. this.layerMask = 0x0FFFFFFF;
  59876. /**
  59877. * This can help using your own shader to render the particle system.
  59878. * The according effect will be created
  59879. */
  59880. this.customShader = null;
  59881. /**
  59882. * By default particle system starts as soon as they are created. This prevents the
  59883. * automatic start to happen and let you decide when to start emitting particles.
  59884. */
  59885. this.preventAutoStart = false;
  59886. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59887. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59888. /**
  59889. * Callback triggered when the particle animation is ending.
  59890. */
  59891. this.onAnimationEnd = null;
  59892. /**
  59893. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59894. */
  59895. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59896. /**
  59897. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59898. * to override the particles.
  59899. */
  59900. this.forceDepthWrite = false;
  59901. /** 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 */
  59902. this.preWarmCycles = 0;
  59903. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59904. this.preWarmStepOffset = 1;
  59905. /**
  59906. * 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)
  59907. */
  59908. this.spriteCellChangeSpeed = 1;
  59909. /**
  59910. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59911. */
  59912. this.startSpriteCellID = 0;
  59913. /**
  59914. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59915. */
  59916. this.endSpriteCellID = 0;
  59917. /**
  59918. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59919. */
  59920. this.spriteCellWidth = 0;
  59921. /**
  59922. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59923. */
  59924. this.spriteCellHeight = 0;
  59925. /**
  59926. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  59927. */
  59928. this.spriteRandomStartCell = false;
  59929. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59930. this.translationPivot = new BABYLON.Vector2(0, 0);
  59931. /**
  59932. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  59933. */
  59934. this.beginAnimationOnStart = false;
  59935. /**
  59936. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  59937. */
  59938. this.beginAnimationFrom = 0;
  59939. /**
  59940. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  59941. */
  59942. this.beginAnimationTo = 60;
  59943. /**
  59944. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  59945. */
  59946. this.beginAnimationLoop = false;
  59947. /**
  59948. * You can use gravity if you want to give an orientation to your particles.
  59949. */
  59950. this.gravity = BABYLON.Vector3.Zero();
  59951. this._colorGradients = null;
  59952. this._sizeGradients = null;
  59953. this._lifeTimeGradients = null;
  59954. this._angularSpeedGradients = null;
  59955. this._velocityGradients = null;
  59956. this._limitVelocityGradients = null;
  59957. this._dragGradients = null;
  59958. this._emitRateGradients = null;
  59959. this._startSizeGradients = null;
  59960. this._rampGradients = null;
  59961. this._colorRemapGradients = null;
  59962. this._alphaRemapGradients = null;
  59963. /**
  59964. * Defines the delay in milliseconds before starting the system (0 by default)
  59965. */
  59966. this.startDelay = 0;
  59967. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  59968. this.limitVelocityDamping = 0.4;
  59969. /**
  59970. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59971. */
  59972. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59973. /**
  59974. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  59975. */
  59976. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59977. /**
  59978. * Color the particle will have at the end of its lifetime
  59979. */
  59980. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  59981. /**
  59982. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  59983. */
  59984. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59985. /** @hidden */
  59986. this._isSubEmitter = false;
  59987. /**
  59988. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59989. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  59990. */
  59991. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  59992. this._isBillboardBased = true;
  59993. /**
  59994. * Local cache of defines for image processing.
  59995. */
  59996. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  59997. this.id = name;
  59998. this.name = name;
  59999. }
  60000. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  60001. /**
  60002. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  60003. */
  60004. get: function () {
  60005. return this._isAnimationSheetEnabled;
  60006. },
  60007. set: function (value) {
  60008. if (this._isAnimationSheetEnabled == value) {
  60009. return;
  60010. }
  60011. this._isAnimationSheetEnabled = value;
  60012. this._reset();
  60013. },
  60014. enumerable: true,
  60015. configurable: true
  60016. });
  60017. /**
  60018. * Get hosting scene
  60019. * @returns the scene
  60020. */
  60021. BaseParticleSystem.prototype.getScene = function () {
  60022. return this._scene;
  60023. };
  60024. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  60025. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  60026. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  60027. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  60028. };
  60029. /**
  60030. * Gets the current list of drag gradients.
  60031. * You must use addDragGradient and removeDragGradient to udpate this list
  60032. * @returns the list of drag gradients
  60033. */
  60034. BaseParticleSystem.prototype.getDragGradients = function () {
  60035. return this._dragGradients;
  60036. };
  60037. /**
  60038. * Gets the current list of limit velocity gradients.
  60039. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  60040. * @returns the list of limit velocity gradients
  60041. */
  60042. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  60043. return this._limitVelocityGradients;
  60044. };
  60045. /**
  60046. * Gets the current list of color gradients.
  60047. * You must use addColorGradient and removeColorGradient to udpate this list
  60048. * @returns the list of color gradients
  60049. */
  60050. BaseParticleSystem.prototype.getColorGradients = function () {
  60051. return this._colorGradients;
  60052. };
  60053. /**
  60054. * Gets the current list of size gradients.
  60055. * You must use addSizeGradient and removeSizeGradient to udpate this list
  60056. * @returns the list of size gradients
  60057. */
  60058. BaseParticleSystem.prototype.getSizeGradients = function () {
  60059. return this._sizeGradients;
  60060. };
  60061. /**
  60062. * Gets the current list of color remap gradients.
  60063. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  60064. * @returns the list of color remap gradients
  60065. */
  60066. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  60067. return this._colorRemapGradients;
  60068. };
  60069. /**
  60070. * Gets the current list of alpha remap gradients.
  60071. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  60072. * @returns the list of alpha remap gradients
  60073. */
  60074. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  60075. return this._alphaRemapGradients;
  60076. };
  60077. /**
  60078. * Gets the current list of life time gradients.
  60079. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  60080. * @returns the list of life time gradients
  60081. */
  60082. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  60083. return this._lifeTimeGradients;
  60084. };
  60085. /**
  60086. * Gets the current list of angular speed gradients.
  60087. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  60088. * @returns the list of angular speed gradients
  60089. */
  60090. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  60091. return this._angularSpeedGradients;
  60092. };
  60093. /**
  60094. * Gets the current list of velocity gradients.
  60095. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60096. * @returns the list of velocity gradients
  60097. */
  60098. BaseParticleSystem.prototype.getVelocityGradients = function () {
  60099. return this._velocityGradients;
  60100. };
  60101. /**
  60102. * Gets the current list of start size gradients.
  60103. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  60104. * @returns the list of start size gradients
  60105. */
  60106. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  60107. return this._startSizeGradients;
  60108. };
  60109. /**
  60110. * Gets the current list of emit rate gradients.
  60111. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  60112. * @returns the list of emit rate gradients
  60113. */
  60114. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  60115. return this._emitRateGradients;
  60116. };
  60117. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  60118. /**
  60119. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60120. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60121. */
  60122. get: function () {
  60123. if (this.particleEmitterType.direction1) {
  60124. return this.particleEmitterType.direction1;
  60125. }
  60126. return BABYLON.Vector3.Zero();
  60127. },
  60128. set: function (value) {
  60129. if (this.particleEmitterType.direction1) {
  60130. this.particleEmitterType.direction1 = value;
  60131. }
  60132. },
  60133. enumerable: true,
  60134. configurable: true
  60135. });
  60136. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  60137. /**
  60138. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60139. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60140. */
  60141. get: function () {
  60142. if (this.particleEmitterType.direction2) {
  60143. return this.particleEmitterType.direction2;
  60144. }
  60145. return BABYLON.Vector3.Zero();
  60146. },
  60147. set: function (value) {
  60148. if (this.particleEmitterType.direction2) {
  60149. this.particleEmitterType.direction2 = value;
  60150. }
  60151. },
  60152. enumerable: true,
  60153. configurable: true
  60154. });
  60155. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  60156. /**
  60157. * 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.
  60158. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60159. */
  60160. get: function () {
  60161. if (this.particleEmitterType.minEmitBox) {
  60162. return this.particleEmitterType.minEmitBox;
  60163. }
  60164. return BABYLON.Vector3.Zero();
  60165. },
  60166. set: function (value) {
  60167. if (this.particleEmitterType.minEmitBox) {
  60168. this.particleEmitterType.minEmitBox = value;
  60169. }
  60170. },
  60171. enumerable: true,
  60172. configurable: true
  60173. });
  60174. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  60175. /**
  60176. * 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.
  60177. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60178. */
  60179. get: function () {
  60180. if (this.particleEmitterType.maxEmitBox) {
  60181. return this.particleEmitterType.maxEmitBox;
  60182. }
  60183. return BABYLON.Vector3.Zero();
  60184. },
  60185. set: function (value) {
  60186. if (this.particleEmitterType.maxEmitBox) {
  60187. this.particleEmitterType.maxEmitBox = value;
  60188. }
  60189. },
  60190. enumerable: true,
  60191. configurable: true
  60192. });
  60193. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  60194. /**
  60195. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60196. */
  60197. get: function () {
  60198. return this._isBillboardBased;
  60199. },
  60200. set: function (value) {
  60201. if (this._isBillboardBased === value) {
  60202. return;
  60203. }
  60204. this._isBillboardBased = value;
  60205. this._reset();
  60206. },
  60207. enumerable: true,
  60208. configurable: true
  60209. });
  60210. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  60211. /**
  60212. * Gets the image processing configuration used either in this material.
  60213. */
  60214. get: function () {
  60215. return this._imageProcessingConfiguration;
  60216. },
  60217. /**
  60218. * Sets the Default image processing configuration used either in the this material.
  60219. *
  60220. * If sets to null, the scene one is in use.
  60221. */
  60222. set: function (value) {
  60223. this._attachImageProcessingConfiguration(value);
  60224. },
  60225. enumerable: true,
  60226. configurable: true
  60227. });
  60228. /**
  60229. * Attaches a new image processing configuration to the Standard Material.
  60230. * @param configuration
  60231. */
  60232. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  60233. if (configuration === this._imageProcessingConfiguration) {
  60234. return;
  60235. }
  60236. // Pick the scene configuration if needed.
  60237. if (!configuration) {
  60238. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  60239. }
  60240. else {
  60241. this._imageProcessingConfiguration = configuration;
  60242. }
  60243. };
  60244. /** @hidden */
  60245. BaseParticleSystem.prototype._reset = function () {
  60246. };
  60247. /** @hidden */
  60248. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  60249. if (!gradients) {
  60250. return this;
  60251. }
  60252. var index = 0;
  60253. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60254. var valueGradient = gradients_1[_i];
  60255. if (valueGradient.gradient === gradient) {
  60256. gradients.splice(index, 1);
  60257. break;
  60258. }
  60259. index++;
  60260. }
  60261. if (texture) {
  60262. texture.dispose();
  60263. }
  60264. return this;
  60265. };
  60266. /**
  60267. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  60268. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60269. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60270. * @returns the emitter
  60271. */
  60272. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  60273. var particleEmitter = new BABYLON.PointParticleEmitter();
  60274. particleEmitter.direction1 = direction1;
  60275. particleEmitter.direction2 = direction2;
  60276. this.particleEmitterType = particleEmitter;
  60277. return particleEmitter;
  60278. };
  60279. /**
  60280. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  60281. * @param radius The radius of the hemisphere to emit from
  60282. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60283. * @returns the emitter
  60284. */
  60285. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  60286. if (radius === void 0) { radius = 1; }
  60287. if (radiusRange === void 0) { radiusRange = 1; }
  60288. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  60289. this.particleEmitterType = particleEmitter;
  60290. return particleEmitter;
  60291. };
  60292. /**
  60293. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  60294. * @param radius The radius of the sphere to emit from
  60295. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60296. * @returns the emitter
  60297. */
  60298. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  60299. if (radius === void 0) { radius = 1; }
  60300. if (radiusRange === void 0) { radiusRange = 1; }
  60301. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  60302. this.particleEmitterType = particleEmitter;
  60303. return particleEmitter;
  60304. };
  60305. /**
  60306. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  60307. * @param radius The radius of the sphere to emit from
  60308. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  60309. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  60310. * @returns the emitter
  60311. */
  60312. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  60313. if (radius === void 0) { radius = 1; }
  60314. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60315. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60316. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  60317. this.particleEmitterType = particleEmitter;
  60318. return particleEmitter;
  60319. };
  60320. /**
  60321. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  60322. * @param radius The radius of the emission cylinder
  60323. * @param height The height of the emission cylinder
  60324. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  60325. * @param directionRandomizer How much to randomize the particle direction [0-1]
  60326. * @returns the emitter
  60327. */
  60328. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  60329. if (radius === void 0) { radius = 1; }
  60330. if (height === void 0) { height = 1; }
  60331. if (radiusRange === void 0) { radiusRange = 1; }
  60332. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60333. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  60334. this.particleEmitterType = particleEmitter;
  60335. return particleEmitter;
  60336. };
  60337. /**
  60338. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  60339. * @param radius The radius of the cylinder to emit from
  60340. * @param height The height of the emission cylinder
  60341. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60342. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  60343. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  60344. * @returns the emitter
  60345. */
  60346. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  60347. if (radius === void 0) { radius = 1; }
  60348. if (height === void 0) { height = 1; }
  60349. if (radiusRange === void 0) { radiusRange = 1; }
  60350. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60351. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60352. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  60353. this.particleEmitterType = particleEmitter;
  60354. return particleEmitter;
  60355. };
  60356. /**
  60357. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  60358. * @param radius The radius of the cone to emit from
  60359. * @param angle The base angle of the cone
  60360. * @returns the emitter
  60361. */
  60362. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  60363. if (radius === void 0) { radius = 1; }
  60364. if (angle === void 0) { angle = Math.PI / 4; }
  60365. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  60366. this.particleEmitterType = particleEmitter;
  60367. return particleEmitter;
  60368. };
  60369. /**
  60370. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  60371. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60372. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60373. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60374. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60375. * @returns the emitter
  60376. */
  60377. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  60378. var particleEmitter = new BABYLON.BoxParticleEmitter();
  60379. this.particleEmitterType = particleEmitter;
  60380. this.direction1 = direction1;
  60381. this.direction2 = direction2;
  60382. this.minEmitBox = minEmitBox;
  60383. this.maxEmitBox = maxEmitBox;
  60384. return particleEmitter;
  60385. };
  60386. /**
  60387. * Source color is added to the destination color without alpha affecting the result
  60388. */
  60389. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  60390. /**
  60391. * Blend current color and particle color using particle’s alpha
  60392. */
  60393. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  60394. /**
  60395. * Add current color and particle color multiplied by particle’s alpha
  60396. */
  60397. BaseParticleSystem.BLENDMODE_ADD = 2;
  60398. /**
  60399. * Multiply current color with particle color
  60400. */
  60401. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  60402. /**
  60403. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  60404. */
  60405. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  60406. return BaseParticleSystem;
  60407. }());
  60408. BABYLON.BaseParticleSystem = BaseParticleSystem;
  60409. })(BABYLON || (BABYLON = {}));
  60410. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  60411. var BABYLON;
  60412. (function (BABYLON) {
  60413. /**
  60414. * This represents a particle system in Babylon.
  60415. * 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.
  60416. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60417. * @example https://doc.babylonjs.com/babylon101/particles
  60418. */
  60419. var ParticleSystem = /** @class */ (function (_super) {
  60420. __extends(ParticleSystem, _super);
  60421. /**
  60422. * Instantiates a particle system.
  60423. * 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.
  60424. * @param name The name of the particle system
  60425. * @param capacity The max number of particles alive at the same time
  60426. * @param scene The scene the particle system belongs to
  60427. * @param customEffect a custom effect used to change the way particles are rendered by default
  60428. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60429. * @param epsilon Offset used to render the particles
  60430. */
  60431. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  60432. if (customEffect === void 0) { customEffect = null; }
  60433. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60434. if (epsilon === void 0) { epsilon = 0.01; }
  60435. var _this = _super.call(this, name) || this;
  60436. /**
  60437. * @hidden
  60438. */
  60439. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  60440. /**
  60441. * An event triggered when the system is disposed
  60442. */
  60443. _this.onDisposeObservable = new BABYLON.Observable();
  60444. _this._particles = new Array();
  60445. _this._stockParticles = new Array();
  60446. _this._newPartsExcess = 0;
  60447. _this._vertexBuffers = {};
  60448. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  60449. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  60450. _this._scaledDirection = BABYLON.Vector3.Zero();
  60451. _this._scaledGravity = BABYLON.Vector3.Zero();
  60452. _this._currentRenderId = -1;
  60453. _this._useInstancing = false;
  60454. _this._started = false;
  60455. _this._stopped = false;
  60456. _this._actualFrame = 0;
  60457. /** @hidden */
  60458. _this._currentEmitRate1 = 0;
  60459. /** @hidden */
  60460. _this._currentEmitRate2 = 0;
  60461. /** @hidden */
  60462. _this._currentStartSize1 = 0;
  60463. /** @hidden */
  60464. _this._currentStartSize2 = 0;
  60465. _this._rawTextureWidth = 256;
  60466. _this._useRampGradients = false;
  60467. /**
  60468. * @hidden
  60469. * If the particle systems emitter should be disposed when the particle system is disposed
  60470. */
  60471. _this._disposeEmitterOnDispose = false;
  60472. // start of sub system methods
  60473. /**
  60474. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  60475. * Its lifetime will start back at 0.
  60476. */
  60477. _this.recycleParticle = function (particle) {
  60478. // move particle from activeParticle list to stock particles
  60479. var lastParticle = _this._particles.pop();
  60480. if (lastParticle !== particle) {
  60481. lastParticle.copyTo(particle);
  60482. }
  60483. _this._stockParticles.push(lastParticle);
  60484. };
  60485. _this._createParticle = function () {
  60486. var particle;
  60487. if (_this._stockParticles.length !== 0) {
  60488. particle = _this._stockParticles.pop();
  60489. particle._reset();
  60490. }
  60491. else {
  60492. particle = new BABYLON.Particle(_this);
  60493. }
  60494. // Attach emitters
  60495. if (_this._subEmitters && _this._subEmitters.length > 0) {
  60496. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  60497. particle._attachedSubEmitters = [];
  60498. subEmitters.forEach(function (subEmitter) {
  60499. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  60500. var newEmitter = subEmitter.clone();
  60501. particle._attachedSubEmitters.push(newEmitter);
  60502. newEmitter.particleSystem.start();
  60503. }
  60504. });
  60505. }
  60506. return particle;
  60507. };
  60508. _this._emitFromParticle = function (particle) {
  60509. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  60510. return;
  60511. }
  60512. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  60513. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  60514. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  60515. var subSystem = subEmitter.clone();
  60516. particle._inheritParticleInfoToSubEmitter(subSystem);
  60517. subSystem.particleSystem._rootParticleSystem = _this;
  60518. _this.activeSubSystems.push(subSystem.particleSystem);
  60519. subSystem.particleSystem.start();
  60520. }
  60521. });
  60522. };
  60523. _this._capacity = capacity;
  60524. _this._epsilon = epsilon;
  60525. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60526. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60527. // Setup the default processing configuration to the scene.
  60528. _this._attachImageProcessingConfiguration(null);
  60529. _this._customEffect = customEffect;
  60530. _this._scene.particleSystems.push(_this);
  60531. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  60532. _this._createIndexBuffer();
  60533. _this._createVertexBuffers();
  60534. // Default emitter type
  60535. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60536. // Update
  60537. _this.updateFunction = function (particles) {
  60538. var noiseTextureSize = null;
  60539. var noiseTextureData = null;
  60540. if (_this.noiseTexture) { // We need to get texture data back to CPU
  60541. noiseTextureSize = _this.noiseTexture.getSize();
  60542. noiseTextureData = (_this.noiseTexture.getContent());
  60543. }
  60544. var _loop_1 = function () {
  60545. particle = particles[index];
  60546. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  60547. var previousAge = particle.age;
  60548. particle.age += scaledUpdateSpeed;
  60549. // Evaluate step to death
  60550. if (particle.age > particle.lifeTime) {
  60551. var diff = particle.age - previousAge;
  60552. var oldDiff = particle.lifeTime - previousAge;
  60553. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  60554. particle.age = particle.lifeTime;
  60555. }
  60556. var ratio = particle.age / particle.lifeTime;
  60557. // Color
  60558. if (_this._colorGradients && _this._colorGradients.length > 0) {
  60559. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  60560. if (currentGradient !== particle._currentColorGradient) {
  60561. particle._currentColor1.copyFrom(particle._currentColor2);
  60562. nextGradient.getColorToRef(particle._currentColor2);
  60563. particle._currentColorGradient = currentGradient;
  60564. }
  60565. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  60566. });
  60567. }
  60568. else {
  60569. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  60570. particle.color.addInPlace(_this._scaledColorStep);
  60571. if (particle.color.a < 0) {
  60572. particle.color.a = 0;
  60573. }
  60574. }
  60575. // Angular speed
  60576. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  60577. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  60578. if (currentGradient !== particle._currentAngularSpeedGradient) {
  60579. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  60580. particle._currentAngularSpeed2 = nextGradient.getFactor();
  60581. particle._currentAngularSpeedGradient = currentGradient;
  60582. }
  60583. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  60584. });
  60585. }
  60586. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  60587. // Direction
  60588. var directionScale = scaledUpdateSpeed;
  60589. /// Velocity
  60590. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  60591. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  60592. if (currentGradient !== particle._currentVelocityGradient) {
  60593. particle._currentVelocity1 = particle._currentVelocity2;
  60594. particle._currentVelocity2 = nextGradient.getFactor();
  60595. particle._currentVelocityGradient = currentGradient;
  60596. }
  60597. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  60598. });
  60599. }
  60600. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  60601. /// Limit velocity
  60602. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  60603. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  60604. if (currentGradient !== particle._currentLimitVelocityGradient) {
  60605. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  60606. particle._currentLimitVelocity2 = nextGradient.getFactor();
  60607. particle._currentLimitVelocityGradient = currentGradient;
  60608. }
  60609. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  60610. var currentVelocity = particle.direction.length();
  60611. if (currentVelocity > limitVelocity) {
  60612. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  60613. }
  60614. });
  60615. }
  60616. /// Drag
  60617. if (_this._dragGradients && _this._dragGradients.length > 0) {
  60618. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  60619. if (currentGradient !== particle._currentDragGradient) {
  60620. particle._currentDrag1 = particle._currentDrag2;
  60621. particle._currentDrag2 = nextGradient.getFactor();
  60622. particle._currentDragGradient = currentGradient;
  60623. }
  60624. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  60625. _this._scaledDirection.scaleInPlace(1.0 - drag);
  60626. });
  60627. }
  60628. particle.position.addInPlace(_this._scaledDirection);
  60629. // Noise
  60630. if (noiseTextureData && noiseTextureSize) {
  60631. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60632. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60633. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60634. var force = BABYLON.Tmp.Vector3[0];
  60635. var scaledForce = BABYLON.Tmp.Vector3[1];
  60636. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  60637. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  60638. particle.direction.addInPlace(scaledForce);
  60639. }
  60640. // Gravity
  60641. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  60642. particle.direction.addInPlace(_this._scaledGravity);
  60643. // Size
  60644. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  60645. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  60646. if (currentGradient !== particle._currentSizeGradient) {
  60647. particle._currentSize1 = particle._currentSize2;
  60648. particle._currentSize2 = nextGradient.getFactor();
  60649. particle._currentSizeGradient = currentGradient;
  60650. }
  60651. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  60652. });
  60653. }
  60654. // Remap data
  60655. if (_this._useRampGradients) {
  60656. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  60657. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  60658. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60659. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60660. particle.remapData.x = min;
  60661. particle.remapData.y = max - min;
  60662. });
  60663. }
  60664. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  60665. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  60666. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60667. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60668. particle.remapData.z = min;
  60669. particle.remapData.w = max - min;
  60670. });
  60671. }
  60672. }
  60673. if (_this._isAnimationSheetEnabled) {
  60674. particle.updateCellIndex();
  60675. }
  60676. // Update the position of the attached sub-emitters to match their attached particle
  60677. particle._inheritParticleInfoToSubEmitters();
  60678. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  60679. _this._emitFromParticle(particle);
  60680. if (particle._attachedSubEmitters) {
  60681. particle._attachedSubEmitters.forEach(function (subEmitter) {
  60682. subEmitter.particleSystem.disposeOnStop = true;
  60683. subEmitter.particleSystem.stop();
  60684. });
  60685. particle._attachedSubEmitters = null;
  60686. }
  60687. _this.recycleParticle(particle);
  60688. index--;
  60689. return "continue";
  60690. }
  60691. };
  60692. var particle;
  60693. for (var index = 0; index < particles.length; index++) {
  60694. _loop_1();
  60695. }
  60696. };
  60697. return _this;
  60698. }
  60699. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  60700. /**
  60701. * Sets a callback that will be triggered when the system is disposed
  60702. */
  60703. set: function (callback) {
  60704. if (this._onDisposeObserver) {
  60705. this.onDisposeObservable.remove(this._onDisposeObserver);
  60706. }
  60707. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  60708. },
  60709. enumerable: true,
  60710. configurable: true
  60711. });
  60712. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  60713. /** Gets or sets a boolean indicating that ramp gradients must be used
  60714. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  60715. */
  60716. get: function () {
  60717. return this._useRampGradients;
  60718. },
  60719. set: function (value) {
  60720. if (this._useRampGradients === value) {
  60721. return;
  60722. }
  60723. this._useRampGradients = value;
  60724. this._resetEffect();
  60725. },
  60726. enumerable: true,
  60727. configurable: true
  60728. });
  60729. Object.defineProperty(ParticleSystem.prototype, "particles", {
  60730. //end of Sub-emitter
  60731. /**
  60732. * Gets the current list of active particles
  60733. */
  60734. get: function () {
  60735. return this._particles;
  60736. },
  60737. enumerable: true,
  60738. configurable: true
  60739. });
  60740. /**
  60741. * Returns the string "ParticleSystem"
  60742. * @returns a string containing the class name
  60743. */
  60744. ParticleSystem.prototype.getClassName = function () {
  60745. return "ParticleSystem";
  60746. };
  60747. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  60748. var newGradient = new BABYLON.FactorGradient();
  60749. newGradient.gradient = gradient;
  60750. newGradient.factor1 = factor;
  60751. newGradient.factor2 = factor2;
  60752. factorGradients.push(newGradient);
  60753. factorGradients.sort(function (a, b) {
  60754. if (a.gradient < b.gradient) {
  60755. return -1;
  60756. }
  60757. else if (a.gradient > b.gradient) {
  60758. return 1;
  60759. }
  60760. return 0;
  60761. });
  60762. };
  60763. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  60764. if (!factorGradients) {
  60765. return;
  60766. }
  60767. var index = 0;
  60768. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  60769. var factorGradient = factorGradients_1[_i];
  60770. if (factorGradient.gradient === gradient) {
  60771. factorGradients.splice(index, 1);
  60772. break;
  60773. }
  60774. index++;
  60775. }
  60776. };
  60777. /**
  60778. * Adds a new life time gradient
  60779. * @param gradient defines the gradient to use (between 0 and 1)
  60780. * @param factor defines the life time factor to affect to the specified gradient
  60781. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60782. * @returns the current particle system
  60783. */
  60784. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  60785. if (!this._lifeTimeGradients) {
  60786. this._lifeTimeGradients = [];
  60787. }
  60788. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  60789. return this;
  60790. };
  60791. /**
  60792. * Remove a specific life time gradient
  60793. * @param gradient defines the gradient to remove
  60794. * @returns the current particle system
  60795. */
  60796. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  60797. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  60798. return this;
  60799. };
  60800. /**
  60801. * Adds a new size gradient
  60802. * @param gradient defines the gradient to use (between 0 and 1)
  60803. * @param factor defines the size factor to affect to the specified gradient
  60804. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60805. * @returns the current particle system
  60806. */
  60807. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  60808. if (!this._sizeGradients) {
  60809. this._sizeGradients = [];
  60810. }
  60811. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  60812. return this;
  60813. };
  60814. /**
  60815. * Remove a specific size gradient
  60816. * @param gradient defines the gradient to remove
  60817. * @returns the current particle system
  60818. */
  60819. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60820. this._removeFactorGradient(this._sizeGradients, gradient);
  60821. return this;
  60822. };
  60823. /**
  60824. * Adds a new color remap gradient
  60825. * @param gradient defines the gradient to use (between 0 and 1)
  60826. * @param min defines the color remap minimal range
  60827. * @param max defines the color remap maximal range
  60828. * @returns the current particle system
  60829. */
  60830. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  60831. if (!this._colorRemapGradients) {
  60832. this._colorRemapGradients = [];
  60833. }
  60834. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  60835. return this;
  60836. };
  60837. /**
  60838. * Remove a specific color remap gradient
  60839. * @param gradient defines the gradient to remove
  60840. * @returns the current particle system
  60841. */
  60842. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  60843. this._removeFactorGradient(this._colorRemapGradients, gradient);
  60844. return this;
  60845. };
  60846. /**
  60847. * Adds a new alpha remap gradient
  60848. * @param gradient defines the gradient to use (between 0 and 1)
  60849. * @param min defines the alpha remap minimal range
  60850. * @param max defines the alpha remap maximal range
  60851. * @returns the current particle system
  60852. */
  60853. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  60854. if (!this._alphaRemapGradients) {
  60855. this._alphaRemapGradients = [];
  60856. }
  60857. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  60858. return this;
  60859. };
  60860. /**
  60861. * Remove a specific alpha remap gradient
  60862. * @param gradient defines the gradient to remove
  60863. * @returns the current particle system
  60864. */
  60865. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  60866. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  60867. return this;
  60868. };
  60869. /**
  60870. * Adds a new angular speed gradient
  60871. * @param gradient defines the gradient to use (between 0 and 1)
  60872. * @param factor defines the angular speed to affect to the specified gradient
  60873. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60874. * @returns the current particle system
  60875. */
  60876. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  60877. if (!this._angularSpeedGradients) {
  60878. this._angularSpeedGradients = [];
  60879. }
  60880. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  60881. return this;
  60882. };
  60883. /**
  60884. * Remove a specific angular speed gradient
  60885. * @param gradient defines the gradient to remove
  60886. * @returns the current particle system
  60887. */
  60888. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60889. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  60890. return this;
  60891. };
  60892. /**
  60893. * Adds a new velocity gradient
  60894. * @param gradient defines the gradient to use (between 0 and 1)
  60895. * @param factor defines the velocity to affect to the specified gradient
  60896. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60897. * @returns the current particle system
  60898. */
  60899. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  60900. if (!this._velocityGradients) {
  60901. this._velocityGradients = [];
  60902. }
  60903. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  60904. return this;
  60905. };
  60906. /**
  60907. * Remove a specific velocity gradient
  60908. * @param gradient defines the gradient to remove
  60909. * @returns the current particle system
  60910. */
  60911. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60912. this._removeFactorGradient(this._velocityGradients, gradient);
  60913. return this;
  60914. };
  60915. /**
  60916. * Adds a new limit velocity gradient
  60917. * @param gradient defines the gradient to use (between 0 and 1)
  60918. * @param factor defines the limit velocity value to affect to the specified gradient
  60919. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60920. * @returns the current particle system
  60921. */
  60922. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  60923. if (!this._limitVelocityGradients) {
  60924. this._limitVelocityGradients = [];
  60925. }
  60926. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  60927. return this;
  60928. };
  60929. /**
  60930. * Remove a specific limit velocity gradient
  60931. * @param gradient defines the gradient to remove
  60932. * @returns the current particle system
  60933. */
  60934. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60935. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  60936. return this;
  60937. };
  60938. /**
  60939. * Adds a new drag gradient
  60940. * @param gradient defines the gradient to use (between 0 and 1)
  60941. * @param factor defines the drag value to affect to the specified gradient
  60942. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60943. * @returns the current particle system
  60944. */
  60945. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  60946. if (!this._dragGradients) {
  60947. this._dragGradients = [];
  60948. }
  60949. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  60950. return this;
  60951. };
  60952. /**
  60953. * Remove a specific drag gradient
  60954. * @param gradient defines the gradient to remove
  60955. * @returns the current particle system
  60956. */
  60957. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  60958. this._removeFactorGradient(this._dragGradients, gradient);
  60959. return this;
  60960. };
  60961. /**
  60962. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  60963. * @param gradient defines the gradient to use (between 0 and 1)
  60964. * @param factor defines the emit rate value to affect to the specified gradient
  60965. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60966. * @returns the current particle system
  60967. */
  60968. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  60969. if (!this._emitRateGradients) {
  60970. this._emitRateGradients = [];
  60971. }
  60972. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  60973. return this;
  60974. };
  60975. /**
  60976. * Remove a specific emit rate gradient
  60977. * @param gradient defines the gradient to remove
  60978. * @returns the current particle system
  60979. */
  60980. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  60981. this._removeFactorGradient(this._emitRateGradients, gradient);
  60982. return this;
  60983. };
  60984. /**
  60985. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  60986. * @param gradient defines the gradient to use (between 0 and 1)
  60987. * @param factor defines the start size value to affect to the specified gradient
  60988. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60989. * @returns the current particle system
  60990. */
  60991. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  60992. if (!this._startSizeGradients) {
  60993. this._startSizeGradients = [];
  60994. }
  60995. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  60996. return this;
  60997. };
  60998. /**
  60999. * Remove a specific start size gradient
  61000. * @param gradient defines the gradient to remove
  61001. * @returns the current particle system
  61002. */
  61003. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61004. this._removeFactorGradient(this._emitRateGradients, gradient);
  61005. return this;
  61006. };
  61007. ParticleSystem.prototype._createRampGradientTexture = function () {
  61008. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  61009. return;
  61010. }
  61011. var data = new Uint8Array(this._rawTextureWidth * 4);
  61012. var tmpColor = BABYLON.Tmp.Color3[0];
  61013. for (var x = 0; x < this._rawTextureWidth; x++) {
  61014. var ratio = x / this._rawTextureWidth;
  61015. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  61016. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  61017. data[x * 4] = tmpColor.r * 255;
  61018. data[x * 4 + 1] = tmpColor.g * 255;
  61019. data[x * 4 + 2] = tmpColor.b * 255;
  61020. data[x * 4 + 3] = 255;
  61021. });
  61022. }
  61023. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61024. };
  61025. /**
  61026. * Gets the current list of ramp gradients.
  61027. * You must use addRampGradient and removeRampGradient to udpate this list
  61028. * @returns the list of ramp gradients
  61029. */
  61030. ParticleSystem.prototype.getRampGradients = function () {
  61031. return this._rampGradients;
  61032. };
  61033. /**
  61034. * Adds a new ramp gradient used to remap particle colors
  61035. * @param gradient defines the gradient to use (between 0 and 1)
  61036. * @param color defines the color to affect to the specified gradient
  61037. * @returns the current particle system
  61038. */
  61039. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61040. if (!this._rampGradients) {
  61041. this._rampGradients = [];
  61042. }
  61043. var rampGradient = new BABYLON.Color3Gradient();
  61044. rampGradient.gradient = gradient;
  61045. rampGradient.color = color;
  61046. this._rampGradients.push(rampGradient);
  61047. this._rampGradients.sort(function (a, b) {
  61048. if (a.gradient < b.gradient) {
  61049. return -1;
  61050. }
  61051. else if (a.gradient > b.gradient) {
  61052. return 1;
  61053. }
  61054. return 0;
  61055. });
  61056. if (this._rampGradientsTexture) {
  61057. this._rampGradientsTexture.dispose();
  61058. this._rampGradientsTexture = null;
  61059. }
  61060. this._createRampGradientTexture();
  61061. return this;
  61062. };
  61063. /**
  61064. * Remove a specific ramp gradient
  61065. * @param gradient defines the gradient to remove
  61066. * @returns the current particle system
  61067. */
  61068. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  61069. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  61070. this._rampGradientsTexture = null;
  61071. if (this._rampGradients && this._rampGradients.length > 0) {
  61072. this._createRampGradientTexture();
  61073. }
  61074. return this;
  61075. };
  61076. /**
  61077. * Adds a new color gradient
  61078. * @param gradient defines the gradient to use (between 0 and 1)
  61079. * @param color1 defines the color to affect to the specified gradient
  61080. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61081. * @returns this particle system
  61082. */
  61083. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61084. if (!this._colorGradients) {
  61085. this._colorGradients = [];
  61086. }
  61087. var colorGradient = new BABYLON.ColorGradient();
  61088. colorGradient.gradient = gradient;
  61089. colorGradient.color1 = color1;
  61090. colorGradient.color2 = color2;
  61091. this._colorGradients.push(colorGradient);
  61092. this._colorGradients.sort(function (a, b) {
  61093. if (a.gradient < b.gradient) {
  61094. return -1;
  61095. }
  61096. else if (a.gradient > b.gradient) {
  61097. return 1;
  61098. }
  61099. return 0;
  61100. });
  61101. return this;
  61102. };
  61103. /**
  61104. * Remove a specific color gradient
  61105. * @param gradient defines the gradient to remove
  61106. * @returns this particle system
  61107. */
  61108. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  61109. if (!this._colorGradients) {
  61110. return this;
  61111. }
  61112. var index = 0;
  61113. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  61114. var colorGradient = _a[_i];
  61115. if (colorGradient.gradient === gradient) {
  61116. this._colorGradients.splice(index, 1);
  61117. break;
  61118. }
  61119. index++;
  61120. }
  61121. return this;
  61122. };
  61123. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  61124. u = Math.abs(u) * 0.5 + 0.5;
  61125. v = Math.abs(v) * 0.5 + 0.5;
  61126. var wrappedU = ((u * width) % width) | 0;
  61127. var wrappedV = ((v * height) % height) | 0;
  61128. var position = (wrappedU + wrappedV * width) * 4;
  61129. return pixels[position] / 255;
  61130. };
  61131. ParticleSystem.prototype._reset = function () {
  61132. this._resetEffect();
  61133. };
  61134. ParticleSystem.prototype._resetEffect = function () {
  61135. if (this._vertexBuffer) {
  61136. this._vertexBuffer.dispose();
  61137. this._vertexBuffer = null;
  61138. }
  61139. if (this._spriteBuffer) {
  61140. this._spriteBuffer.dispose();
  61141. this._spriteBuffer = null;
  61142. }
  61143. this._createVertexBuffers();
  61144. };
  61145. ParticleSystem.prototype._createVertexBuffers = function () {
  61146. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  61147. if (this._isAnimationSheetEnabled) {
  61148. this._vertexBufferSize += 1;
  61149. }
  61150. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61151. this._vertexBufferSize += 3;
  61152. }
  61153. if (this._useRampGradients) {
  61154. this._vertexBufferSize += 4;
  61155. }
  61156. var engine = this._scene.getEngine();
  61157. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  61158. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  61159. var dataOffset = 0;
  61160. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61161. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  61162. dataOffset += 3;
  61163. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61164. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  61165. dataOffset += 4;
  61166. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61167. this._vertexBuffers["angle"] = options;
  61168. dataOffset += 1;
  61169. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61170. this._vertexBuffers["size"] = size;
  61171. dataOffset += 2;
  61172. if (this._isAnimationSheetEnabled) {
  61173. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61174. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  61175. dataOffset += 1;
  61176. }
  61177. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61178. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61179. this._vertexBuffers["direction"] = directionBuffer;
  61180. dataOffset += 3;
  61181. }
  61182. if (this._useRampGradients) {
  61183. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61184. this._vertexBuffers["remapData"] = rampDataBuffer;
  61185. dataOffset += 4;
  61186. }
  61187. var offsets;
  61188. if (this._useInstancing) {
  61189. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  61190. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  61191. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  61192. }
  61193. else {
  61194. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61195. dataOffset += 2;
  61196. }
  61197. this._vertexBuffers["offset"] = offsets;
  61198. };
  61199. ParticleSystem.prototype._createIndexBuffer = function () {
  61200. if (this._useInstancing) {
  61201. return;
  61202. }
  61203. var indices = [];
  61204. var index = 0;
  61205. for (var count = 0; count < this._capacity; count++) {
  61206. indices.push(index);
  61207. indices.push(index + 1);
  61208. indices.push(index + 2);
  61209. indices.push(index);
  61210. indices.push(index + 2);
  61211. indices.push(index + 3);
  61212. index += 4;
  61213. }
  61214. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  61215. };
  61216. /**
  61217. * Gets the maximum number of particles active at the same time.
  61218. * @returns The max number of active particles.
  61219. */
  61220. ParticleSystem.prototype.getCapacity = function () {
  61221. return this._capacity;
  61222. };
  61223. /**
  61224. * Gets whether there are still active particles in the system.
  61225. * @returns True if it is alive, otherwise false.
  61226. */
  61227. ParticleSystem.prototype.isAlive = function () {
  61228. return this._alive;
  61229. };
  61230. /**
  61231. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61232. * @returns True if it has been started, otherwise false.
  61233. */
  61234. ParticleSystem.prototype.isStarted = function () {
  61235. return this._started;
  61236. };
  61237. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  61238. var _this = this;
  61239. this._subEmitters = new Array();
  61240. if (this.subEmitters) {
  61241. this.subEmitters.forEach(function (subEmitter) {
  61242. if (subEmitter instanceof ParticleSystem) {
  61243. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  61244. }
  61245. else if (subEmitter instanceof BABYLON.SubEmitter) {
  61246. _this._subEmitters.push([subEmitter]);
  61247. }
  61248. else if (subEmitter instanceof Array) {
  61249. _this._subEmitters.push(subEmitter);
  61250. }
  61251. });
  61252. }
  61253. };
  61254. /**
  61255. * Starts the particle system and begins to emit
  61256. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61257. */
  61258. ParticleSystem.prototype.start = function (delay) {
  61259. var _this = this;
  61260. if (delay === void 0) { delay = this.startDelay; }
  61261. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61262. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61263. }
  61264. if (delay) {
  61265. setTimeout(function () {
  61266. _this.start(0);
  61267. }, delay);
  61268. return;
  61269. }
  61270. // Convert the subEmitters field to the constant type field _subEmitters
  61271. this._prepareSubEmitterInternalArray();
  61272. this._started = true;
  61273. this._stopped = false;
  61274. this._actualFrame = 0;
  61275. if (this._subEmitters && this._subEmitters.length != 0) {
  61276. this.activeSubSystems = new Array();
  61277. }
  61278. // Reset emit gradient so it acts the same on every start
  61279. if (this._emitRateGradients) {
  61280. if (this._emitRateGradients.length > 0) {
  61281. this._currentEmitRateGradient = this._emitRateGradients[0];
  61282. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  61283. this._currentEmitRate2 = this._currentEmitRate1;
  61284. }
  61285. if (this._emitRateGradients.length > 1) {
  61286. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  61287. }
  61288. }
  61289. // Reset start size gradient so it acts the same on every start
  61290. if (this._startSizeGradients) {
  61291. if (this._startSizeGradients.length > 0) {
  61292. this._currentStartSizeGradient = this._startSizeGradients[0];
  61293. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  61294. this._currentStartSize2 = this._currentStartSize1;
  61295. }
  61296. if (this._startSizeGradients.length > 1) {
  61297. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  61298. }
  61299. }
  61300. if (this.preWarmCycles) {
  61301. if (this.emitter instanceof BABYLON.AbstractMesh) {
  61302. this.emitter.computeWorldMatrix(true);
  61303. }
  61304. var noiseTextureAsProcedural_1 = this.noiseTexture;
  61305. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  61306. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  61307. setTimeout(function () {
  61308. for (var index = 0; index < _this.preWarmCycles; index++) {
  61309. _this.animate(true);
  61310. noiseTextureAsProcedural_1.render();
  61311. }
  61312. });
  61313. });
  61314. }
  61315. else {
  61316. for (var index = 0; index < this.preWarmCycles; index++) {
  61317. this.animate(true);
  61318. }
  61319. }
  61320. }
  61321. // Animations
  61322. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  61323. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  61324. }
  61325. };
  61326. /**
  61327. * Stops the particle system.
  61328. * @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.
  61329. */
  61330. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  61331. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  61332. this._stopped = true;
  61333. if (stopSubEmitters) {
  61334. this._stopSubEmitters();
  61335. }
  61336. };
  61337. // animation sheet
  61338. /**
  61339. * Remove all active particles
  61340. */
  61341. ParticleSystem.prototype.reset = function () {
  61342. this._stockParticles = [];
  61343. this._particles = [];
  61344. };
  61345. /**
  61346. * @hidden (for internal use only)
  61347. */
  61348. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  61349. var offset = index * this._vertexBufferSize;
  61350. this._vertexData[offset++] = particle.position.x;
  61351. this._vertexData[offset++] = particle.position.y;
  61352. this._vertexData[offset++] = particle.position.z;
  61353. this._vertexData[offset++] = particle.color.r;
  61354. this._vertexData[offset++] = particle.color.g;
  61355. this._vertexData[offset++] = particle.color.b;
  61356. this._vertexData[offset++] = particle.color.a;
  61357. this._vertexData[offset++] = particle.angle;
  61358. this._vertexData[offset++] = particle.scale.x * particle.size;
  61359. this._vertexData[offset++] = particle.scale.y * particle.size;
  61360. if (this._isAnimationSheetEnabled) {
  61361. this._vertexData[offset++] = particle.cellIndex;
  61362. }
  61363. if (!this._isBillboardBased) {
  61364. if (particle._initialDirection) {
  61365. this._vertexData[offset++] = particle._initialDirection.x;
  61366. this._vertexData[offset++] = particle._initialDirection.y;
  61367. this._vertexData[offset++] = particle._initialDirection.z;
  61368. }
  61369. else {
  61370. this._vertexData[offset++] = particle.direction.x;
  61371. this._vertexData[offset++] = particle.direction.y;
  61372. this._vertexData[offset++] = particle.direction.z;
  61373. }
  61374. }
  61375. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61376. this._vertexData[offset++] = particle.direction.x;
  61377. this._vertexData[offset++] = particle.direction.y;
  61378. this._vertexData[offset++] = particle.direction.z;
  61379. }
  61380. if (this._useRampGradients) {
  61381. this._vertexData[offset++] = particle.remapData.x;
  61382. this._vertexData[offset++] = particle.remapData.y;
  61383. this._vertexData[offset++] = particle.remapData.z;
  61384. this._vertexData[offset++] = particle.remapData.w;
  61385. }
  61386. if (!this._useInstancing) {
  61387. if (this._isAnimationSheetEnabled) {
  61388. if (offsetX === 0) {
  61389. offsetX = this._epsilon;
  61390. }
  61391. else if (offsetX === 1) {
  61392. offsetX = 1 - this._epsilon;
  61393. }
  61394. if (offsetY === 0) {
  61395. offsetY = this._epsilon;
  61396. }
  61397. else if (offsetY === 1) {
  61398. offsetY = 1 - this._epsilon;
  61399. }
  61400. }
  61401. this._vertexData[offset++] = offsetX;
  61402. this._vertexData[offset++] = offsetY;
  61403. }
  61404. };
  61405. ParticleSystem.prototype._stopSubEmitters = function () {
  61406. if (!this.activeSubSystems) {
  61407. return;
  61408. }
  61409. this.activeSubSystems.forEach(function (subSystem) {
  61410. subSystem.stop(true);
  61411. });
  61412. this.activeSubSystems = new Array();
  61413. };
  61414. ParticleSystem.prototype._removeFromRoot = function () {
  61415. if (!this._rootParticleSystem) {
  61416. return;
  61417. }
  61418. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  61419. if (index !== -1) {
  61420. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  61421. }
  61422. this._rootParticleSystem = null;
  61423. };
  61424. // End of sub system methods
  61425. ParticleSystem.prototype._update = function (newParticles) {
  61426. var _this = this;
  61427. // Update current
  61428. this._alive = this._particles.length > 0;
  61429. if (this.emitter.position) {
  61430. var emitterMesh = this.emitter;
  61431. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  61432. }
  61433. else {
  61434. var emitterPosition = this.emitter;
  61435. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61436. }
  61437. this.updateFunction(this._particles);
  61438. // Add new ones
  61439. var particle;
  61440. var _loop_2 = function () {
  61441. if (this_1._particles.length === this_1._capacity) {
  61442. return "break";
  61443. }
  61444. particle = this_1._createParticle();
  61445. this_1._particles.push(particle);
  61446. // Emitter
  61447. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  61448. if (this_1.startPositionFunction) {
  61449. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61450. }
  61451. else {
  61452. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61453. }
  61454. if (this_1.startDirectionFunction) {
  61455. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61456. }
  61457. else {
  61458. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61459. }
  61460. if (emitPower === 0) {
  61461. if (!particle._initialDirection) {
  61462. particle._initialDirection = particle.direction.clone();
  61463. }
  61464. else {
  61465. particle._initialDirection.copyFrom(particle.direction);
  61466. }
  61467. }
  61468. else {
  61469. particle._initialDirection = null;
  61470. }
  61471. particle.direction.scaleInPlace(emitPower);
  61472. // Life time
  61473. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  61474. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  61475. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  61476. var factorGradient1 = currentGradient;
  61477. var factorGradient2 = nextGradient;
  61478. var lifeTime1 = factorGradient1.getFactor();
  61479. var lifeTime2 = factorGradient2.getFactor();
  61480. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  61481. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  61482. });
  61483. }
  61484. else {
  61485. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  61486. }
  61487. // Size
  61488. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  61489. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  61490. }
  61491. else {
  61492. particle._currentSizeGradient = this_1._sizeGradients[0];
  61493. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  61494. particle.size = particle._currentSize1;
  61495. if (this_1._sizeGradients.length > 1) {
  61496. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  61497. }
  61498. else {
  61499. particle._currentSize2 = particle._currentSize1;
  61500. }
  61501. }
  61502. // Size and scale
  61503. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  61504. // Adjust scale by start size
  61505. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  61506. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  61507. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  61508. if (currentGradient !== _this._currentStartSizeGradient) {
  61509. _this._currentStartSize1 = _this._currentStartSize2;
  61510. _this._currentStartSize2 = nextGradient.getFactor();
  61511. _this._currentStartSizeGradient = currentGradient;
  61512. }
  61513. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  61514. particle.scale.scaleInPlace(value);
  61515. });
  61516. }
  61517. // Angle
  61518. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  61519. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  61520. }
  61521. else {
  61522. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  61523. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  61524. particle._currentAngularSpeed1 = particle.angularSpeed;
  61525. if (this_1._angularSpeedGradients.length > 1) {
  61526. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  61527. }
  61528. else {
  61529. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  61530. }
  61531. }
  61532. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  61533. // Velocity
  61534. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  61535. particle._currentVelocityGradient = this_1._velocityGradients[0];
  61536. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  61537. if (this_1._velocityGradients.length > 1) {
  61538. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  61539. }
  61540. else {
  61541. particle._currentVelocity2 = particle._currentVelocity1;
  61542. }
  61543. }
  61544. // Limit velocity
  61545. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  61546. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  61547. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  61548. if (this_1._limitVelocityGradients.length > 1) {
  61549. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  61550. }
  61551. else {
  61552. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  61553. }
  61554. }
  61555. // Drag
  61556. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  61557. particle._currentDragGradient = this_1._dragGradients[0];
  61558. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  61559. if (this_1._dragGradients.length > 1) {
  61560. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  61561. }
  61562. else {
  61563. particle._currentDrag2 = particle._currentDrag1;
  61564. }
  61565. }
  61566. // Color
  61567. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  61568. step = BABYLON.Scalar.RandomRange(0, 1.0);
  61569. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  61570. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  61571. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  61572. }
  61573. else {
  61574. particle._currentColorGradient = this_1._colorGradients[0];
  61575. particle._currentColorGradient.getColorToRef(particle.color);
  61576. particle._currentColor1.copyFrom(particle.color);
  61577. if (this_1._colorGradients.length > 1) {
  61578. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  61579. }
  61580. else {
  61581. particle._currentColor2.copyFrom(particle.color);
  61582. }
  61583. }
  61584. // Sheet
  61585. if (this_1._isAnimationSheetEnabled) {
  61586. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  61587. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  61588. }
  61589. // Inherited Velocity
  61590. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  61591. // Ramp
  61592. if (this_1._useRampGradients) {
  61593. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  61594. }
  61595. // Noise texture coordinates
  61596. if (this_1.noiseTexture) {
  61597. if (particle._randomNoiseCoordinates1) {
  61598. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  61599. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  61600. }
  61601. else {
  61602. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61603. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61604. }
  61605. }
  61606. // Update the position of the attached sub-emitters to match their attached particle
  61607. particle._inheritParticleInfoToSubEmitters();
  61608. };
  61609. var this_1 = this, step;
  61610. for (var index = 0; index < newParticles; index++) {
  61611. var state_1 = _loop_2();
  61612. if (state_1 === "break")
  61613. break;
  61614. }
  61615. };
  61616. /** @hidden */
  61617. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  61618. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61619. if (isBillboardBased === void 0) { isBillboardBased = false; }
  61620. if (useRampGradients === void 0) { useRampGradients = false; }
  61621. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  61622. if (isAnimationSheetEnabled) {
  61623. attributeNamesOrOptions.push("cellIndex");
  61624. }
  61625. if (!isBillboardBased) {
  61626. attributeNamesOrOptions.push("direction");
  61627. }
  61628. if (useRampGradients) {
  61629. attributeNamesOrOptions.push("remapData");
  61630. }
  61631. return attributeNamesOrOptions;
  61632. };
  61633. /** @hidden */
  61634. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  61635. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61636. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  61637. if (isAnimationSheetEnabled) {
  61638. effectCreationOption.push("particlesInfos");
  61639. }
  61640. return effectCreationOption;
  61641. };
  61642. /** @hidden */
  61643. ParticleSystem.prototype._getEffect = function (blendMode) {
  61644. if (this._customEffect) {
  61645. return this._customEffect;
  61646. }
  61647. var defines = [];
  61648. if (this._scene.clipPlane) {
  61649. defines.push("#define CLIPPLANE");
  61650. }
  61651. if (this._scene.clipPlane2) {
  61652. defines.push("#define CLIPPLANE2");
  61653. }
  61654. if (this._scene.clipPlane3) {
  61655. defines.push("#define CLIPPLANE3");
  61656. }
  61657. if (this._scene.clipPlane4) {
  61658. defines.push("#define CLIPPLANE4");
  61659. }
  61660. if (this._isAnimationSheetEnabled) {
  61661. defines.push("#define ANIMATESHEET");
  61662. }
  61663. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  61664. defines.push("#define BLENDMULTIPLYMODE");
  61665. }
  61666. if (this._useRampGradients) {
  61667. defines.push("#define RAMPGRADIENT");
  61668. }
  61669. if (this._isBillboardBased) {
  61670. defines.push("#define BILLBOARD");
  61671. switch (this.billboardMode) {
  61672. case ParticleSystem.BILLBOARDMODE_Y:
  61673. defines.push("#define BILLBOARDY");
  61674. break;
  61675. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  61676. defines.push("#define BILLBOARDSTRETCHED");
  61677. break;
  61678. case ParticleSystem.BILLBOARDMODE_ALL:
  61679. default:
  61680. break;
  61681. }
  61682. }
  61683. if (this._imageProcessingConfiguration) {
  61684. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61685. defines.push(this._imageProcessingConfigurationDefines.toString());
  61686. }
  61687. // Effect
  61688. var join = defines.join("\n");
  61689. if (this._cachedDefines !== join) {
  61690. this._cachedDefines = join;
  61691. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  61692. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  61693. var samplers = ["diffuseSampler", "rampSampler"];
  61694. if (BABYLON.ImageProcessingConfiguration) {
  61695. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  61696. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61697. }
  61698. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  61699. }
  61700. return this._effect;
  61701. };
  61702. /**
  61703. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61704. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  61705. */
  61706. ParticleSystem.prototype.animate = function (preWarmOnly) {
  61707. var _this = this;
  61708. if (preWarmOnly === void 0) { preWarmOnly = false; }
  61709. if (!this._started) {
  61710. return;
  61711. }
  61712. if (!preWarmOnly) {
  61713. // Check
  61714. if (!this.isReady()) {
  61715. return;
  61716. }
  61717. if (this._currentRenderId === this._scene.getFrameId()) {
  61718. return;
  61719. }
  61720. this._currentRenderId = this._scene.getFrameId();
  61721. }
  61722. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61723. // Determine the number of particles we need to create
  61724. var newParticles;
  61725. if (this.manualEmitCount > -1) {
  61726. newParticles = this.manualEmitCount;
  61727. this._newPartsExcess = 0;
  61728. this.manualEmitCount = 0;
  61729. }
  61730. else {
  61731. var rate_1 = this.emitRate;
  61732. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  61733. var ratio = this._actualFrame / this.targetStopDuration;
  61734. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  61735. if (currentGradient !== _this._currentEmitRateGradient) {
  61736. _this._currentEmitRate1 = _this._currentEmitRate2;
  61737. _this._currentEmitRate2 = nextGradient.getFactor();
  61738. _this._currentEmitRateGradient = currentGradient;
  61739. }
  61740. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  61741. });
  61742. }
  61743. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  61744. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  61745. }
  61746. if (this._newPartsExcess > 1.0) {
  61747. newParticles += this._newPartsExcess >> 0;
  61748. this._newPartsExcess -= this._newPartsExcess >> 0;
  61749. }
  61750. this._alive = false;
  61751. if (!this._stopped) {
  61752. this._actualFrame += this._scaledUpdateSpeed;
  61753. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61754. this.stop();
  61755. }
  61756. }
  61757. else {
  61758. newParticles = 0;
  61759. }
  61760. this._update(newParticles);
  61761. // Stopped?
  61762. if (this._stopped) {
  61763. if (!this._alive) {
  61764. this._started = false;
  61765. if (this.onAnimationEnd) {
  61766. this.onAnimationEnd();
  61767. }
  61768. if (this.disposeOnStop) {
  61769. this._scene._toBeDisposed.push(this);
  61770. }
  61771. }
  61772. }
  61773. if (!preWarmOnly) {
  61774. // Update VBO
  61775. var offset = 0;
  61776. for (var index = 0; index < this._particles.length; index++) {
  61777. var particle = this._particles[index];
  61778. this._appendParticleVertices(offset, particle);
  61779. offset += this._useInstancing ? 1 : 4;
  61780. }
  61781. if (this._vertexBuffer) {
  61782. this._vertexBuffer.update(this._vertexData);
  61783. }
  61784. }
  61785. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  61786. this.stop();
  61787. }
  61788. };
  61789. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  61790. this._appendParticleVertex(offset++, particle, 0, 0);
  61791. if (!this._useInstancing) {
  61792. this._appendParticleVertex(offset++, particle, 1, 0);
  61793. this._appendParticleVertex(offset++, particle, 1, 1);
  61794. this._appendParticleVertex(offset++, particle, 0, 1);
  61795. }
  61796. };
  61797. /**
  61798. * Rebuilds the particle system.
  61799. */
  61800. ParticleSystem.prototype.rebuild = function () {
  61801. this._createIndexBuffer();
  61802. if (this._vertexBuffer) {
  61803. this._vertexBuffer._rebuild();
  61804. }
  61805. };
  61806. /**
  61807. * Is this system ready to be used/rendered
  61808. * @return true if the system is ready
  61809. */
  61810. ParticleSystem.prototype.isReady = function () {
  61811. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61812. return false;
  61813. }
  61814. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61815. if (!this._getEffect(this.blendMode).isReady()) {
  61816. return false;
  61817. }
  61818. }
  61819. else {
  61820. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  61821. return false;
  61822. }
  61823. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  61824. return false;
  61825. }
  61826. }
  61827. return true;
  61828. };
  61829. ParticleSystem.prototype._render = function (blendMode) {
  61830. var effect = this._getEffect(blendMode);
  61831. var engine = this._scene.getEngine();
  61832. // Render
  61833. engine.enableEffect(effect);
  61834. var viewMatrix = this._scene.getViewMatrix();
  61835. effect.setTexture("diffuseSampler", this.particleTexture);
  61836. effect.setMatrix("view", viewMatrix);
  61837. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  61838. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61839. var baseSize = this.particleTexture.getBaseSize();
  61840. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61841. }
  61842. effect.setVector2("translationPivot", this.translationPivot);
  61843. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  61844. if (this._isBillboardBased) {
  61845. var camera = this._scene.activeCamera;
  61846. effect.setVector3("eyePosition", camera.globalPosition);
  61847. }
  61848. if (this._rampGradientsTexture) {
  61849. effect.setTexture("rampSampler", this._rampGradientsTexture);
  61850. }
  61851. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61852. var invView = viewMatrix.clone();
  61853. invView.invert();
  61854. effect.setMatrix("invView", invView);
  61855. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  61856. }
  61857. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  61858. // image processing
  61859. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61860. this._imageProcessingConfiguration.bind(effect);
  61861. }
  61862. // Draw order
  61863. switch (blendMode) {
  61864. case ParticleSystem.BLENDMODE_ADD:
  61865. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61866. break;
  61867. case ParticleSystem.BLENDMODE_ONEONE:
  61868. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61869. break;
  61870. case ParticleSystem.BLENDMODE_STANDARD:
  61871. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61872. break;
  61873. case ParticleSystem.BLENDMODE_MULTIPLY:
  61874. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  61875. break;
  61876. }
  61877. if (this._useInstancing) {
  61878. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  61879. }
  61880. else {
  61881. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  61882. }
  61883. return this._particles.length;
  61884. };
  61885. /**
  61886. * Renders the particle system in its current state.
  61887. * @returns the current number of particles
  61888. */
  61889. ParticleSystem.prototype.render = function () {
  61890. // Check
  61891. if (!this.isReady() || !this._particles.length) {
  61892. return 0;
  61893. }
  61894. var engine = this._scene.getEngine();
  61895. engine.setState(false);
  61896. if (this.forceDepthWrite) {
  61897. engine.setDepthWrite(true);
  61898. }
  61899. var outparticles = 0;
  61900. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61901. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  61902. }
  61903. outparticles = this._render(this.blendMode);
  61904. engine.unbindInstanceAttributes();
  61905. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61906. return outparticles;
  61907. };
  61908. /**
  61909. * Disposes the particle system and free the associated resources
  61910. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61911. */
  61912. ParticleSystem.prototype.dispose = function (disposeTexture) {
  61913. if (disposeTexture === void 0) { disposeTexture = true; }
  61914. if (this._vertexBuffer) {
  61915. this._vertexBuffer.dispose();
  61916. this._vertexBuffer = null;
  61917. }
  61918. if (this._spriteBuffer) {
  61919. this._spriteBuffer.dispose();
  61920. this._spriteBuffer = null;
  61921. }
  61922. if (this._indexBuffer) {
  61923. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61924. this._indexBuffer = null;
  61925. }
  61926. if (disposeTexture && this.particleTexture) {
  61927. this.particleTexture.dispose();
  61928. this.particleTexture = null;
  61929. }
  61930. if (disposeTexture && this.noiseTexture) {
  61931. this.noiseTexture.dispose();
  61932. this.noiseTexture = null;
  61933. }
  61934. if (this._rampGradientsTexture) {
  61935. this._rampGradientsTexture.dispose();
  61936. this._rampGradientsTexture = null;
  61937. }
  61938. this._removeFromRoot();
  61939. if (this._subEmitters && this._subEmitters.length) {
  61940. for (var index = 0; index < this._subEmitters.length; index++) {
  61941. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  61942. var subEmitter = _a[_i];
  61943. subEmitter.dispose();
  61944. }
  61945. }
  61946. this._subEmitters = [];
  61947. this.subEmitters = [];
  61948. }
  61949. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  61950. this.emitter.dispose(true);
  61951. }
  61952. // Remove from scene
  61953. var index = this._scene.particleSystems.indexOf(this);
  61954. if (index > -1) {
  61955. this._scene.particleSystems.splice(index, 1);
  61956. }
  61957. this._scene._activeParticleSystems.dispose();
  61958. // Callback
  61959. this.onDisposeObservable.notifyObservers(this);
  61960. this.onDisposeObservable.clear();
  61961. this.reset();
  61962. };
  61963. // Clone
  61964. /**
  61965. * Clones the particle system.
  61966. * @param name The name of the cloned object
  61967. * @param newEmitter The new emitter to use
  61968. * @returns the cloned particle system
  61969. */
  61970. ParticleSystem.prototype.clone = function (name, newEmitter) {
  61971. var custom = null;
  61972. var program = null;
  61973. if (this.customShader != null) {
  61974. program = this.customShader;
  61975. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61976. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61977. }
  61978. else if (this._customEffect) {
  61979. custom = this._customEffect;
  61980. }
  61981. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  61982. result.customShader = program;
  61983. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  61984. if (newEmitter === undefined) {
  61985. newEmitter = this.emitter;
  61986. }
  61987. result.noiseTexture = this.noiseTexture;
  61988. result.emitter = newEmitter;
  61989. if (this.particleTexture) {
  61990. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61991. }
  61992. // Clone gradients
  61993. if (this._colorGradients) {
  61994. this._colorGradients.forEach(function (v) {
  61995. result.addColorGradient(v.gradient, v.color1, v.color2);
  61996. });
  61997. }
  61998. if (this._dragGradients) {
  61999. this._dragGradients.forEach(function (v) {
  62000. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  62001. });
  62002. }
  62003. if (this._angularSpeedGradients) {
  62004. this._angularSpeedGradients.forEach(function (v) {
  62005. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  62006. });
  62007. }
  62008. if (this._emitRateGradients) {
  62009. this._emitRateGradients.forEach(function (v) {
  62010. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  62011. });
  62012. }
  62013. if (this._lifeTimeGradients) {
  62014. this._lifeTimeGradients.forEach(function (v) {
  62015. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  62016. });
  62017. }
  62018. if (this._limitVelocityGradients) {
  62019. this._limitVelocityGradients.forEach(function (v) {
  62020. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  62021. });
  62022. }
  62023. if (this._sizeGradients) {
  62024. this._sizeGradients.forEach(function (v) {
  62025. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  62026. });
  62027. }
  62028. if (this._startSizeGradients) {
  62029. this._startSizeGradients.forEach(function (v) {
  62030. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  62031. });
  62032. }
  62033. if (this._velocityGradients) {
  62034. this._velocityGradients.forEach(function (v) {
  62035. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  62036. });
  62037. }
  62038. if (this._rampGradients) {
  62039. this._rampGradients.forEach(function (v) {
  62040. result.addRampGradient(v.gradient, v.color);
  62041. });
  62042. }
  62043. if (this._colorRemapGradients) {
  62044. this._colorRemapGradients.forEach(function (v) {
  62045. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  62046. });
  62047. }
  62048. if (this._alphaRemapGradients) {
  62049. this._alphaRemapGradients.forEach(function (v) {
  62050. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  62051. });
  62052. }
  62053. if (!this.preventAutoStart) {
  62054. result.start();
  62055. }
  62056. return result;
  62057. };
  62058. /**
  62059. * Serializes the particle system to a JSON object.
  62060. * @returns the JSON object
  62061. */
  62062. ParticleSystem.prototype.serialize = function () {
  62063. var serializationObject = {};
  62064. ParticleSystem._Serialize(serializationObject, this);
  62065. serializationObject.textureMask = this.textureMask.asArray();
  62066. serializationObject.customShader = this.customShader;
  62067. serializationObject.preventAutoStart = this.preventAutoStart;
  62068. // SubEmitters
  62069. if (this.subEmitters) {
  62070. serializationObject.subEmitters = [];
  62071. if (!this._subEmitters) {
  62072. this._prepareSubEmitterInternalArray();
  62073. }
  62074. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  62075. var subs = _a[_i];
  62076. var cell = [];
  62077. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  62078. var sub = subs_1[_b];
  62079. cell.push(sub.serialize());
  62080. }
  62081. serializationObject.subEmitters.push(cell);
  62082. }
  62083. }
  62084. return serializationObject;
  62085. };
  62086. /** @hidden */
  62087. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  62088. serializationObject.name = particleSystem.name;
  62089. serializationObject.id = particleSystem.id;
  62090. serializationObject.capacity = particleSystem.getCapacity();
  62091. // Emitter
  62092. if (particleSystem.emitter.position) {
  62093. var emitterMesh = particleSystem.emitter;
  62094. serializationObject.emitterId = emitterMesh.id;
  62095. }
  62096. else {
  62097. var emitterPosition = particleSystem.emitter;
  62098. serializationObject.emitter = emitterPosition.asArray();
  62099. }
  62100. // Emitter
  62101. if (particleSystem.particleEmitterType) {
  62102. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  62103. }
  62104. if (particleSystem.particleTexture) {
  62105. serializationObject.textureName = particleSystem.particleTexture.name;
  62106. serializationObject.invertY = particleSystem.particleTexture._invertY;
  62107. }
  62108. // Animations
  62109. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  62110. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  62111. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  62112. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  62113. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  62114. // Particle system
  62115. serializationObject.startDelay = particleSystem.startDelay;
  62116. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  62117. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  62118. serializationObject.billboardMode = particleSystem.billboardMode;
  62119. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  62120. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  62121. serializationObject.minSize = particleSystem.minSize;
  62122. serializationObject.maxSize = particleSystem.maxSize;
  62123. serializationObject.minScaleX = particleSystem.minScaleX;
  62124. serializationObject.maxScaleX = particleSystem.maxScaleX;
  62125. serializationObject.minScaleY = particleSystem.minScaleY;
  62126. serializationObject.maxScaleY = particleSystem.maxScaleY;
  62127. serializationObject.minEmitPower = particleSystem.minEmitPower;
  62128. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  62129. serializationObject.minLifeTime = particleSystem.minLifeTime;
  62130. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  62131. serializationObject.emitRate = particleSystem.emitRate;
  62132. serializationObject.gravity = particleSystem.gravity.asArray();
  62133. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  62134. serializationObject.color1 = particleSystem.color1.asArray();
  62135. serializationObject.color2 = particleSystem.color2.asArray();
  62136. serializationObject.colorDead = particleSystem.colorDead.asArray();
  62137. serializationObject.updateSpeed = particleSystem.updateSpeed;
  62138. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  62139. serializationObject.blendMode = particleSystem.blendMode;
  62140. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  62141. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  62142. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  62143. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  62144. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  62145. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  62146. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  62147. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  62148. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  62149. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  62150. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  62151. var colorGradients = particleSystem.getColorGradients();
  62152. if (colorGradients) {
  62153. serializationObject.colorGradients = [];
  62154. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  62155. var colorGradient = colorGradients_1[_i];
  62156. var serializedGradient = {
  62157. gradient: colorGradient.gradient,
  62158. color1: colorGradient.color1.asArray()
  62159. };
  62160. if (colorGradient.color2) {
  62161. serializedGradient.color2 = colorGradient.color2.asArray();
  62162. }
  62163. serializationObject.colorGradients.push(serializedGradient);
  62164. }
  62165. }
  62166. var rampGradients = particleSystem.getRampGradients();
  62167. if (rampGradients) {
  62168. serializationObject.rampGradients = [];
  62169. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  62170. var rampGradient = rampGradients_1[_a];
  62171. var serializedGradient = {
  62172. gradient: rampGradient.gradient,
  62173. color: rampGradient.color.asArray()
  62174. };
  62175. serializationObject.rampGradients.push(serializedGradient);
  62176. }
  62177. serializationObject.useRampGradients = particleSystem.useRampGradients;
  62178. }
  62179. var colorRemapGradients = particleSystem.getColorRemapGradients();
  62180. if (colorRemapGradients) {
  62181. serializationObject.colorRemapGradients = [];
  62182. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  62183. var colorRemapGradient = colorRemapGradients_1[_b];
  62184. var serializedGradient = {
  62185. gradient: colorRemapGradient.gradient,
  62186. factor1: colorRemapGradient.factor1
  62187. };
  62188. if (colorRemapGradient.factor2 !== undefined) {
  62189. serializedGradient.factor2 = colorRemapGradient.factor2;
  62190. }
  62191. serializationObject.colorRemapGradients.push(serializedGradient);
  62192. }
  62193. }
  62194. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  62195. if (alphaRemapGradients) {
  62196. serializationObject.alphaRemapGradients = [];
  62197. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  62198. var alphaRemapGradient = alphaRemapGradients_1[_c];
  62199. var serializedGradient = {
  62200. gradient: alphaRemapGradient.gradient,
  62201. factor1: alphaRemapGradient.factor1
  62202. };
  62203. if (alphaRemapGradient.factor2 !== undefined) {
  62204. serializedGradient.factor2 = alphaRemapGradient.factor2;
  62205. }
  62206. serializationObject.alphaRemapGradients.push(serializedGradient);
  62207. }
  62208. }
  62209. var sizeGradients = particleSystem.getSizeGradients();
  62210. if (sizeGradients) {
  62211. serializationObject.sizeGradients = [];
  62212. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  62213. var sizeGradient = sizeGradients_1[_d];
  62214. var serializedGradient = {
  62215. gradient: sizeGradient.gradient,
  62216. factor1: sizeGradient.factor1
  62217. };
  62218. if (sizeGradient.factor2 !== undefined) {
  62219. serializedGradient.factor2 = sizeGradient.factor2;
  62220. }
  62221. serializationObject.sizeGradients.push(serializedGradient);
  62222. }
  62223. }
  62224. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  62225. if (angularSpeedGradients) {
  62226. serializationObject.angularSpeedGradients = [];
  62227. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  62228. var angularSpeedGradient = angularSpeedGradients_1[_e];
  62229. var serializedGradient = {
  62230. gradient: angularSpeedGradient.gradient,
  62231. factor1: angularSpeedGradient.factor1
  62232. };
  62233. if (angularSpeedGradient.factor2 !== undefined) {
  62234. serializedGradient.factor2 = angularSpeedGradient.factor2;
  62235. }
  62236. serializationObject.angularSpeedGradients.push(serializedGradient);
  62237. }
  62238. }
  62239. var velocityGradients = particleSystem.getVelocityGradients();
  62240. if (velocityGradients) {
  62241. serializationObject.velocityGradients = [];
  62242. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  62243. var velocityGradient = velocityGradients_1[_f];
  62244. var serializedGradient = {
  62245. gradient: velocityGradient.gradient,
  62246. factor1: velocityGradient.factor1
  62247. };
  62248. if (velocityGradient.factor2 !== undefined) {
  62249. serializedGradient.factor2 = velocityGradient.factor2;
  62250. }
  62251. serializationObject.velocityGradients.push(serializedGradient);
  62252. }
  62253. }
  62254. var dragGradients = particleSystem.getDragGradients();
  62255. if (dragGradients) {
  62256. serializationObject.dragyGradients = [];
  62257. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  62258. var dragGradient = dragGradients_1[_g];
  62259. var serializedGradient = {
  62260. gradient: dragGradient.gradient,
  62261. factor1: dragGradient.factor1
  62262. };
  62263. if (dragGradient.factor2 !== undefined) {
  62264. serializedGradient.factor2 = dragGradient.factor2;
  62265. }
  62266. serializationObject.dragGradients.push(serializedGradient);
  62267. }
  62268. }
  62269. var emitRateGradients = particleSystem.getEmitRateGradients();
  62270. if (emitRateGradients) {
  62271. serializationObject.emitRateGradients = [];
  62272. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  62273. var emitRateGradient = emitRateGradients_1[_h];
  62274. var serializedGradient = {
  62275. gradient: emitRateGradient.gradient,
  62276. factor1: emitRateGradient.factor1
  62277. };
  62278. if (emitRateGradient.factor2 !== undefined) {
  62279. serializedGradient.factor2 = emitRateGradient.factor2;
  62280. }
  62281. serializationObject.emitRateGradients.push(serializedGradient);
  62282. }
  62283. }
  62284. var startSizeGradients = particleSystem.getStartSizeGradients();
  62285. if (startSizeGradients) {
  62286. serializationObject.startSizeGradients = [];
  62287. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  62288. var startSizeGradient = startSizeGradients_1[_j];
  62289. var serializedGradient = {
  62290. gradient: startSizeGradient.gradient,
  62291. factor1: startSizeGradient.factor1
  62292. };
  62293. if (startSizeGradient.factor2 !== undefined) {
  62294. serializedGradient.factor2 = startSizeGradient.factor2;
  62295. }
  62296. serializationObject.startSizeGradients.push(serializedGradient);
  62297. }
  62298. }
  62299. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  62300. if (lifeTimeGradients) {
  62301. serializationObject.lifeTimeGradients = [];
  62302. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  62303. var lifeTimeGradient = lifeTimeGradients_1[_k];
  62304. var serializedGradient = {
  62305. gradient: lifeTimeGradient.gradient,
  62306. factor1: lifeTimeGradient.factor1
  62307. };
  62308. if (lifeTimeGradient.factor2 !== undefined) {
  62309. serializedGradient.factor2 = lifeTimeGradient.factor2;
  62310. }
  62311. serializationObject.lifeTimeGradients.push(serializedGradient);
  62312. }
  62313. }
  62314. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  62315. if (limitVelocityGradients) {
  62316. serializationObject.limitVelocityGradients = [];
  62317. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  62318. var limitVelocityGradient = limitVelocityGradients_1[_l];
  62319. var serializedGradient = {
  62320. gradient: limitVelocityGradient.gradient,
  62321. factor1: limitVelocityGradient.factor1
  62322. };
  62323. if (limitVelocityGradient.factor2 !== undefined) {
  62324. serializedGradient.factor2 = limitVelocityGradient.factor2;
  62325. }
  62326. serializationObject.limitVelocityGradients.push(serializedGradient);
  62327. }
  62328. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  62329. }
  62330. if (particleSystem.noiseTexture) {
  62331. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  62332. }
  62333. };
  62334. /** @hidden */
  62335. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  62336. // Texture
  62337. if (parsedParticleSystem.textureName) {
  62338. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  62339. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  62340. }
  62341. // Emitter
  62342. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  62343. particleSystem.emitter = BABYLON.Vector3.Zero();
  62344. }
  62345. else if (parsedParticleSystem.emitterId) {
  62346. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  62347. }
  62348. else {
  62349. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  62350. }
  62351. // Misc.
  62352. if (parsedParticleSystem.renderingGroupId !== undefined) {
  62353. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  62354. }
  62355. if (parsedParticleSystem.isBillboardBased !== undefined) {
  62356. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  62357. }
  62358. if (parsedParticleSystem.billboardMode !== undefined) {
  62359. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  62360. }
  62361. // Animations
  62362. if (parsedParticleSystem.animations) {
  62363. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  62364. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  62365. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62366. }
  62367. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  62368. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  62369. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  62370. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  62371. }
  62372. if (parsedParticleSystem.autoAnimate) {
  62373. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  62374. }
  62375. // Particle system
  62376. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  62377. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  62378. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  62379. particleSystem.minSize = parsedParticleSystem.minSize;
  62380. particleSystem.maxSize = parsedParticleSystem.maxSize;
  62381. if (parsedParticleSystem.minScaleX) {
  62382. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  62383. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  62384. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  62385. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  62386. }
  62387. if (parsedParticleSystem.preWarmCycles !== undefined) {
  62388. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  62389. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  62390. }
  62391. if (parsedParticleSystem.minInitialRotation !== undefined) {
  62392. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  62393. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  62394. }
  62395. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  62396. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  62397. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  62398. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  62399. particleSystem.emitRate = parsedParticleSystem.emitRate;
  62400. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  62401. if (parsedParticleSystem.noiseStrength) {
  62402. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  62403. }
  62404. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  62405. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  62406. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  62407. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  62408. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  62409. particleSystem.blendMode = parsedParticleSystem.blendMode;
  62410. if (parsedParticleSystem.colorGradients) {
  62411. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  62412. var colorGradient = _a[_i];
  62413. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  62414. }
  62415. }
  62416. if (parsedParticleSystem.rampGradients) {
  62417. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  62418. var rampGradient = _c[_b];
  62419. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  62420. }
  62421. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  62422. }
  62423. if (parsedParticleSystem.colorRemapGradients) {
  62424. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  62425. var colorRemapGradient = _e[_d];
  62426. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  62427. }
  62428. }
  62429. if (parsedParticleSystem.alphaRemapGradients) {
  62430. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  62431. var alphaRemapGradient = _g[_f];
  62432. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  62433. }
  62434. }
  62435. if (parsedParticleSystem.sizeGradients) {
  62436. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  62437. var sizeGradient = _j[_h];
  62438. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62439. }
  62440. }
  62441. if (parsedParticleSystem.sizeGradients) {
  62442. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  62443. var sizeGradient = _l[_k];
  62444. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62445. }
  62446. }
  62447. if (parsedParticleSystem.angularSpeedGradients) {
  62448. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  62449. var angularSpeedGradient = _o[_m];
  62450. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  62451. }
  62452. }
  62453. if (parsedParticleSystem.velocityGradients) {
  62454. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  62455. var velocityGradient = _q[_p];
  62456. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  62457. }
  62458. }
  62459. if (parsedParticleSystem.dragGradients) {
  62460. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  62461. var dragGradient = _s[_r];
  62462. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  62463. }
  62464. }
  62465. if (parsedParticleSystem.emitRateGradients) {
  62466. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  62467. var emitRateGradient = _u[_t];
  62468. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  62469. }
  62470. }
  62471. if (parsedParticleSystem.startSizeGradients) {
  62472. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  62473. var startSizeGradient = _w[_v];
  62474. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  62475. }
  62476. }
  62477. if (parsedParticleSystem.lifeTimeGradients) {
  62478. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  62479. var lifeTimeGradient = _y[_x];
  62480. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  62481. }
  62482. }
  62483. if (parsedParticleSystem.limitVelocityGradients) {
  62484. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  62485. var limitVelocityGradient = _0[_z];
  62486. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  62487. }
  62488. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  62489. }
  62490. if (parsedParticleSystem.noiseTexture) {
  62491. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  62492. }
  62493. // Emitter
  62494. var emitterType;
  62495. if (parsedParticleSystem.particleEmitterType) {
  62496. switch (parsedParticleSystem.particleEmitterType.type) {
  62497. case "SphereParticleEmitter":
  62498. emitterType = new BABYLON.SphereParticleEmitter();
  62499. break;
  62500. case "SphereDirectedParticleEmitter":
  62501. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  62502. break;
  62503. case "ConeEmitter":
  62504. case "ConeParticleEmitter":
  62505. emitterType = new BABYLON.ConeParticleEmitter();
  62506. break;
  62507. case "CylinderParticleEmitter":
  62508. emitterType = new BABYLON.CylinderParticleEmitter();
  62509. break;
  62510. case "HemisphericParticleEmitter":
  62511. emitterType = new BABYLON.HemisphericParticleEmitter();
  62512. break;
  62513. case "BoxEmitter":
  62514. case "BoxParticleEmitter":
  62515. default:
  62516. emitterType = new BABYLON.BoxParticleEmitter();
  62517. break;
  62518. }
  62519. emitterType.parse(parsedParticleSystem.particleEmitterType);
  62520. }
  62521. else {
  62522. emitterType = new BABYLON.BoxParticleEmitter();
  62523. emitterType.parse(parsedParticleSystem);
  62524. }
  62525. particleSystem.particleEmitterType = emitterType;
  62526. // Animation sheet
  62527. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  62528. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  62529. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  62530. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  62531. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  62532. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  62533. };
  62534. /**
  62535. * Parses a JSON object to create a particle system.
  62536. * @param parsedParticleSystem The JSON object to parse
  62537. * @param scene The scene to create the particle system in
  62538. * @param rootUrl The root url to use to load external dependencies like texture
  62539. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  62540. * @returns the Parsed particle system
  62541. */
  62542. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  62543. if (doNotStart === void 0) { doNotStart = false; }
  62544. var name = parsedParticleSystem.name;
  62545. var custom = null;
  62546. var program = null;
  62547. if (parsedParticleSystem.customShader) {
  62548. program = parsedParticleSystem.customShader;
  62549. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62550. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62551. }
  62552. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  62553. particleSystem.customShader = program;
  62554. if (parsedParticleSystem.id) {
  62555. particleSystem.id = parsedParticleSystem.id;
  62556. }
  62557. // SubEmitters
  62558. if (parsedParticleSystem.subEmitters) {
  62559. particleSystem.subEmitters = [];
  62560. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  62561. var cell = _a[_i];
  62562. var cellArray = [];
  62563. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  62564. var sub = cell_1[_b];
  62565. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  62566. }
  62567. particleSystem.subEmitters.push(cellArray);
  62568. }
  62569. }
  62570. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62571. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  62572. // Auto start
  62573. if (parsedParticleSystem.preventAutoStart) {
  62574. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  62575. }
  62576. if (!doNotStart && !particleSystem.preventAutoStart) {
  62577. particleSystem.start();
  62578. }
  62579. return particleSystem;
  62580. };
  62581. /**
  62582. * Billboard mode will only apply to Y axis
  62583. */
  62584. ParticleSystem.BILLBOARDMODE_Y = 2;
  62585. /**
  62586. * Billboard mode will apply to all axes
  62587. */
  62588. ParticleSystem.BILLBOARDMODE_ALL = 7;
  62589. /**
  62590. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  62591. */
  62592. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  62593. return ParticleSystem;
  62594. }(BABYLON.BaseParticleSystem));
  62595. BABYLON.ParticleSystem = ParticleSystem;
  62596. })(BABYLON || (BABYLON = {}));
  62597. //# sourceMappingURL=babylon.particleSystem.js.map
  62598. var BABYLON;
  62599. (function (BABYLON) {
  62600. /**
  62601. * Particle emitter emitting particles from the inside of a box.
  62602. * It emits the particles randomly between 2 given directions.
  62603. */
  62604. var BoxParticleEmitter = /** @class */ (function () {
  62605. /**
  62606. * Creates a new instance BoxParticleEmitter
  62607. */
  62608. function BoxParticleEmitter() {
  62609. /**
  62610. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62611. */
  62612. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62613. /**
  62614. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62615. */
  62616. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62617. /**
  62618. * 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.
  62619. */
  62620. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  62621. /**
  62622. * 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.
  62623. */
  62624. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  62625. }
  62626. /**
  62627. * Called by the particle System when the direction is computed for the created particle.
  62628. * @param worldMatrix is the world matrix of the particle system
  62629. * @param directionToUpdate is the direction vector to update with the result
  62630. * @param particle is the particle we are computed the direction for
  62631. */
  62632. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62633. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62634. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62635. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62636. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62637. };
  62638. /**
  62639. * Called by the particle System when the position is computed for the created particle.
  62640. * @param worldMatrix is the world matrix of the particle system
  62641. * @param positionToUpdate is the position vector to update with the result
  62642. * @param particle is the particle we are computed the position for
  62643. */
  62644. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62645. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  62646. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  62647. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  62648. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  62649. };
  62650. /**
  62651. * Clones the current emitter and returns a copy of it
  62652. * @returns the new emitter
  62653. */
  62654. BoxParticleEmitter.prototype.clone = function () {
  62655. var newOne = new BoxParticleEmitter();
  62656. BABYLON.Tools.DeepCopy(this, newOne);
  62657. return newOne;
  62658. };
  62659. /**
  62660. * Called by the GPUParticleSystem to setup the update shader
  62661. * @param effect defines the update shader
  62662. */
  62663. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  62664. effect.setVector3("direction1", this.direction1);
  62665. effect.setVector3("direction2", this.direction2);
  62666. effect.setVector3("minEmitBox", this.minEmitBox);
  62667. effect.setVector3("maxEmitBox", this.maxEmitBox);
  62668. };
  62669. /**
  62670. * Returns a string to use to update the GPU particles update shader
  62671. * @returns a string containng the defines string
  62672. */
  62673. BoxParticleEmitter.prototype.getEffectDefines = function () {
  62674. return "#define BOXEMITTER";
  62675. };
  62676. /**
  62677. * Returns the string "BoxParticleEmitter"
  62678. * @returns a string containing the class name
  62679. */
  62680. BoxParticleEmitter.prototype.getClassName = function () {
  62681. return "BoxParticleEmitter";
  62682. };
  62683. /**
  62684. * Serializes the particle system to a JSON object.
  62685. * @returns the JSON object
  62686. */
  62687. BoxParticleEmitter.prototype.serialize = function () {
  62688. var serializationObject = {};
  62689. serializationObject.type = this.getClassName();
  62690. serializationObject.direction1 = this.direction1.asArray();
  62691. serializationObject.direction2 = this.direction2.asArray();
  62692. serializationObject.minEmitBox = this.minEmitBox.asArray();
  62693. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  62694. return serializationObject;
  62695. };
  62696. /**
  62697. * Parse properties from a JSON object
  62698. * @param serializationObject defines the JSON object
  62699. */
  62700. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  62701. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62702. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62703. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  62704. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  62705. };
  62706. return BoxParticleEmitter;
  62707. }());
  62708. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  62709. })(BABYLON || (BABYLON = {}));
  62710. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  62711. var BABYLON;
  62712. (function (BABYLON) {
  62713. /**
  62714. * Particle emitter emitting particles from the inside of a cylinder.
  62715. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  62716. */
  62717. var CylinderParticleEmitter = /** @class */ (function () {
  62718. /**
  62719. * Creates a new instance CylinderParticleEmitter
  62720. * @param radius the radius of the emission cylinder (1 by default)
  62721. * @param height the height of the emission cylinder (1 by default)
  62722. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62723. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62724. */
  62725. function CylinderParticleEmitter(
  62726. /**
  62727. * The radius of the emission cylinder.
  62728. */
  62729. radius,
  62730. /**
  62731. * The height of the emission cylinder.
  62732. */
  62733. height,
  62734. /**
  62735. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62736. */
  62737. radiusRange,
  62738. /**
  62739. * How much to randomize the particle direction [0-1].
  62740. */
  62741. directionRandomizer) {
  62742. if (radius === void 0) { radius = 1; }
  62743. if (height === void 0) { height = 1; }
  62744. if (radiusRange === void 0) { radiusRange = 1; }
  62745. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62746. this.radius = radius;
  62747. this.height = height;
  62748. this.radiusRange = radiusRange;
  62749. this.directionRandomizer = directionRandomizer;
  62750. }
  62751. /**
  62752. * Called by the particle System when the direction is computed for the created particle.
  62753. * @param worldMatrix is the world matrix of the particle system
  62754. * @param directionToUpdate is the direction vector to update with the result
  62755. * @param particle is the particle we are computed the direction for
  62756. */
  62757. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62758. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62759. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  62760. var angle = Math.atan2(direction.x, direction.z);
  62761. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  62762. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  62763. direction.x = Math.sin(angle);
  62764. direction.z = Math.cos(angle);
  62765. direction.normalize();
  62766. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62767. };
  62768. /**
  62769. * Called by the particle System when the position is computed for the created particle.
  62770. * @param worldMatrix is the world matrix of the particle system
  62771. * @param positionToUpdate is the position vector to update with the result
  62772. * @param particle is the particle we are computed the position for
  62773. */
  62774. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62775. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  62776. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62777. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  62778. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  62779. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  62780. var xPos = positionRadius * Math.cos(angle);
  62781. var zPos = positionRadius * Math.sin(angle);
  62782. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  62783. };
  62784. /**
  62785. * Clones the current emitter and returns a copy of it
  62786. * @returns the new emitter
  62787. */
  62788. CylinderParticleEmitter.prototype.clone = function () {
  62789. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  62790. BABYLON.Tools.DeepCopy(this, newOne);
  62791. return newOne;
  62792. };
  62793. /**
  62794. * Called by the GPUParticleSystem to setup the update shader
  62795. * @param effect defines the update shader
  62796. */
  62797. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  62798. effect.setFloat("radius", this.radius);
  62799. effect.setFloat("height", this.height);
  62800. effect.setFloat("radiusRange", this.radiusRange);
  62801. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62802. };
  62803. /**
  62804. * Returns a string to use to update the GPU particles update shader
  62805. * @returns a string containng the defines string
  62806. */
  62807. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  62808. return "#define CYLINDEREMITTER";
  62809. };
  62810. /**
  62811. * Returns the string "CylinderParticleEmitter"
  62812. * @returns a string containing the class name
  62813. */
  62814. CylinderParticleEmitter.prototype.getClassName = function () {
  62815. return "CylinderParticleEmitter";
  62816. };
  62817. /**
  62818. * Serializes the particle system to a JSON object.
  62819. * @returns the JSON object
  62820. */
  62821. CylinderParticleEmitter.prototype.serialize = function () {
  62822. var serializationObject = {};
  62823. serializationObject.type = this.getClassName();
  62824. serializationObject.radius = this.radius;
  62825. serializationObject.height = this.height;
  62826. serializationObject.radiusRange = this.radiusRange;
  62827. serializationObject.directionRandomizer = this.directionRandomizer;
  62828. return serializationObject;
  62829. };
  62830. /**
  62831. * Parse properties from a JSON object
  62832. * @param serializationObject defines the JSON object
  62833. */
  62834. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  62835. this.radius = serializationObject.radius;
  62836. this.height = serializationObject.height;
  62837. this.radiusRange = serializationObject.radiusRange;
  62838. this.directionRandomizer = serializationObject.directionRandomizer;
  62839. };
  62840. return CylinderParticleEmitter;
  62841. }());
  62842. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  62843. /**
  62844. * Particle emitter emitting particles from the inside of a cylinder.
  62845. * It emits the particles randomly between two vectors.
  62846. */
  62847. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  62848. __extends(CylinderDirectedParticleEmitter, _super);
  62849. /**
  62850. * Creates a new instance CylinderDirectedParticleEmitter
  62851. * @param radius the radius of the emission cylinder (1 by default)
  62852. * @param height the height of the emission cylinder (1 by default)
  62853. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62854. * @param direction1 the min limit of the emission direction (up vector by default)
  62855. * @param direction2 the max limit of the emission direction (up vector by default)
  62856. */
  62857. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  62858. /**
  62859. * The min limit of the emission direction.
  62860. */
  62861. direction1,
  62862. /**
  62863. * The max limit of the emission direction.
  62864. */
  62865. direction2) {
  62866. if (radius === void 0) { radius = 1; }
  62867. if (height === void 0) { height = 1; }
  62868. if (radiusRange === void 0) { radiusRange = 1; }
  62869. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62870. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62871. var _this = _super.call(this, radius, height, radiusRange) || this;
  62872. _this.direction1 = direction1;
  62873. _this.direction2 = direction2;
  62874. return _this;
  62875. }
  62876. /**
  62877. * Called by the particle System when the direction is computed for the created particle.
  62878. * @param worldMatrix is the world matrix of the particle system
  62879. * @param directionToUpdate is the direction vector to update with the result
  62880. * @param particle is the particle we are computed the direction for
  62881. */
  62882. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62883. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62884. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62885. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62886. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62887. };
  62888. /**
  62889. * Clones the current emitter and returns a copy of it
  62890. * @returns the new emitter
  62891. */
  62892. CylinderDirectedParticleEmitter.prototype.clone = function () {
  62893. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  62894. BABYLON.Tools.DeepCopy(this, newOne);
  62895. return newOne;
  62896. };
  62897. /**
  62898. * Called by the GPUParticleSystem to setup the update shader
  62899. * @param effect defines the update shader
  62900. */
  62901. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62902. effect.setFloat("radius", this.radius);
  62903. effect.setFloat("height", this.height);
  62904. effect.setFloat("radiusRange", this.radiusRange);
  62905. effect.setVector3("direction1", this.direction1);
  62906. effect.setVector3("direction2", this.direction2);
  62907. };
  62908. /**
  62909. * Returns a string to use to update the GPU particles update shader
  62910. * @returns a string containng the defines string
  62911. */
  62912. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62913. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  62914. };
  62915. /**
  62916. * Returns the string "CylinderDirectedParticleEmitter"
  62917. * @returns a string containing the class name
  62918. */
  62919. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  62920. return "CylinderDirectedParticleEmitter";
  62921. };
  62922. /**
  62923. * Serializes the particle system to a JSON object.
  62924. * @returns the JSON object
  62925. */
  62926. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  62927. var serializationObject = _super.prototype.serialize.call(this);
  62928. serializationObject.direction1 = this.direction1.asArray();
  62929. serializationObject.direction2 = this.direction2.asArray();
  62930. return serializationObject;
  62931. };
  62932. /**
  62933. * Parse properties from a JSON object
  62934. * @param serializationObject defines the JSON object
  62935. */
  62936. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62937. _super.prototype.parse.call(this, serializationObject);
  62938. this.direction1.copyFrom(serializationObject.direction1);
  62939. this.direction2.copyFrom(serializationObject.direction2);
  62940. };
  62941. return CylinderDirectedParticleEmitter;
  62942. }(CylinderParticleEmitter));
  62943. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  62944. })(BABYLON || (BABYLON = {}));
  62945. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  62946. var BABYLON;
  62947. (function (BABYLON) {
  62948. /**
  62949. * Particle emitter emitting particles from the inside of a cone.
  62950. * It emits the particles alongside the cone volume from the base to the particle.
  62951. * The emission direction might be randomized.
  62952. */
  62953. var ConeParticleEmitter = /** @class */ (function () {
  62954. /**
  62955. * Creates a new instance ConeParticleEmitter
  62956. * @param radius the radius of the emission cone (1 by default)
  62957. * @param angles the cone base angle (PI by default)
  62958. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  62959. */
  62960. function ConeParticleEmitter(radius, angle,
  62961. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  62962. directionRandomizer) {
  62963. if (radius === void 0) { radius = 1; }
  62964. if (angle === void 0) { angle = Math.PI; }
  62965. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62966. this.directionRandomizer = directionRandomizer;
  62967. /**
  62968. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  62969. */
  62970. this.radiusRange = 1;
  62971. /**
  62972. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  62973. */
  62974. this.heightRange = 1;
  62975. /**
  62976. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  62977. */
  62978. this.emitFromSpawnPointOnly = false;
  62979. this.angle = angle;
  62980. this.radius = radius;
  62981. }
  62982. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  62983. /**
  62984. * Gets or sets the radius of the emission cone
  62985. */
  62986. get: function () {
  62987. return this._radius;
  62988. },
  62989. set: function (value) {
  62990. this._radius = value;
  62991. this._buildHeight();
  62992. },
  62993. enumerable: true,
  62994. configurable: true
  62995. });
  62996. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  62997. /**
  62998. * Gets or sets the angle of the emission cone
  62999. */
  63000. get: function () {
  63001. return this._angle;
  63002. },
  63003. set: function (value) {
  63004. this._angle = value;
  63005. this._buildHeight();
  63006. },
  63007. enumerable: true,
  63008. configurable: true
  63009. });
  63010. ConeParticleEmitter.prototype._buildHeight = function () {
  63011. if (this._angle !== 0) {
  63012. this._height = this._radius / Math.tan(this._angle / 2);
  63013. }
  63014. else {
  63015. this._height = 1;
  63016. }
  63017. };
  63018. /**
  63019. * Called by the particle System when the direction is computed for the created particle.
  63020. * @param worldMatrix is the world matrix of the particle system
  63021. * @param directionToUpdate is the direction vector to update with the result
  63022. * @param particle is the particle we are computed the direction for
  63023. */
  63024. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63025. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  63026. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  63027. }
  63028. else {
  63029. // measure the direction Vector from the emitter to the particle.
  63030. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63031. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63032. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63033. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63034. direction.x += randX;
  63035. direction.y += randY;
  63036. direction.z += randZ;
  63037. direction.normalize();
  63038. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63039. }
  63040. };
  63041. /**
  63042. * Called by the particle System when the position is computed for the created particle.
  63043. * @param worldMatrix is the world matrix of the particle system
  63044. * @param positionToUpdate is the position vector to update with the result
  63045. * @param particle is the particle we are computed the position for
  63046. */
  63047. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63048. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  63049. var h;
  63050. if (!this.emitFromSpawnPointOnly) {
  63051. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  63052. // Better distribution in a cone at normal angles.
  63053. h = 1 - h * h;
  63054. }
  63055. else {
  63056. h = 0.0001;
  63057. }
  63058. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  63059. radius = radius * h;
  63060. var randX = radius * Math.sin(s);
  63061. var randZ = radius * Math.cos(s);
  63062. var randY = h * this._height;
  63063. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63064. };
  63065. /**
  63066. * Clones the current emitter and returns a copy of it
  63067. * @returns the new emitter
  63068. */
  63069. ConeParticleEmitter.prototype.clone = function () {
  63070. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  63071. BABYLON.Tools.DeepCopy(this, newOne);
  63072. return newOne;
  63073. };
  63074. /**
  63075. * Called by the GPUParticleSystem to setup the update shader
  63076. * @param effect defines the update shader
  63077. */
  63078. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  63079. effect.setFloat2("radius", this._radius, this.radiusRange);
  63080. effect.setFloat("coneAngle", this._angle);
  63081. effect.setFloat2("height", this._height, this.heightRange);
  63082. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63083. };
  63084. /**
  63085. * Returns a string to use to update the GPU particles update shader
  63086. * @returns a string containng the defines string
  63087. */
  63088. ConeParticleEmitter.prototype.getEffectDefines = function () {
  63089. var defines = "#define CONEEMITTER";
  63090. if (this.emitFromSpawnPointOnly) {
  63091. defines += "\n#define CONEEMITTERSPAWNPOINT";
  63092. }
  63093. return defines;
  63094. };
  63095. /**
  63096. * Returns the string "ConeParticleEmitter"
  63097. * @returns a string containing the class name
  63098. */
  63099. ConeParticleEmitter.prototype.getClassName = function () {
  63100. return "ConeParticleEmitter";
  63101. };
  63102. /**
  63103. * Serializes the particle system to a JSON object.
  63104. * @returns the JSON object
  63105. */
  63106. ConeParticleEmitter.prototype.serialize = function () {
  63107. var serializationObject = {};
  63108. serializationObject.type = this.getClassName();
  63109. serializationObject.radius = this._radius;
  63110. serializationObject.angle = this._angle;
  63111. serializationObject.directionRandomizer = this.directionRandomizer;
  63112. return serializationObject;
  63113. };
  63114. /**
  63115. * Parse properties from a JSON object
  63116. * @param serializationObject defines the JSON object
  63117. */
  63118. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  63119. this.radius = serializationObject.radius;
  63120. this.angle = serializationObject.angle;
  63121. this.directionRandomizer = serializationObject.directionRandomizer;
  63122. };
  63123. return ConeParticleEmitter;
  63124. }());
  63125. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  63126. })(BABYLON || (BABYLON = {}));
  63127. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  63128. var BABYLON;
  63129. (function (BABYLON) {
  63130. /**
  63131. * Particle emitter emitting particles from the inside of a sphere.
  63132. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  63133. */
  63134. var SphereParticleEmitter = /** @class */ (function () {
  63135. /**
  63136. * Creates a new instance SphereParticleEmitter
  63137. * @param radius the radius of the emission sphere (1 by default)
  63138. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63139. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63140. */
  63141. function SphereParticleEmitter(
  63142. /**
  63143. * The radius of the emission sphere.
  63144. */
  63145. radius,
  63146. /**
  63147. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63148. */
  63149. radiusRange,
  63150. /**
  63151. * How much to randomize the particle direction [0-1].
  63152. */
  63153. directionRandomizer) {
  63154. if (radius === void 0) { radius = 1; }
  63155. if (radiusRange === void 0) { radiusRange = 1; }
  63156. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63157. this.radius = radius;
  63158. this.radiusRange = radiusRange;
  63159. this.directionRandomizer = directionRandomizer;
  63160. }
  63161. /**
  63162. * Called by the particle System when the direction is computed for the created particle.
  63163. * @param worldMatrix is the world matrix of the particle system
  63164. * @param directionToUpdate is the direction vector to update with the result
  63165. * @param particle is the particle we are computed the direction for
  63166. */
  63167. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63168. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63169. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63170. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63171. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63172. direction.x += randX;
  63173. direction.y += randY;
  63174. direction.z += randZ;
  63175. direction.normalize();
  63176. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63177. };
  63178. /**
  63179. * Called by the particle System when the position is computed for the created particle.
  63180. * @param worldMatrix is the world matrix of the particle system
  63181. * @param positionToUpdate is the position vector to update with the result
  63182. * @param particle is the particle we are computed the position for
  63183. */
  63184. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63185. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63186. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63187. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63188. var theta = Math.acos(2 * v - 1);
  63189. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63190. var randY = randRadius * Math.cos(theta);
  63191. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63192. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63193. };
  63194. /**
  63195. * Clones the current emitter and returns a copy of it
  63196. * @returns the new emitter
  63197. */
  63198. SphereParticleEmitter.prototype.clone = function () {
  63199. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  63200. BABYLON.Tools.DeepCopy(this, newOne);
  63201. return newOne;
  63202. };
  63203. /**
  63204. * Called by the GPUParticleSystem to setup the update shader
  63205. * @param effect defines the update shader
  63206. */
  63207. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  63208. effect.setFloat("radius", this.radius);
  63209. effect.setFloat("radiusRange", this.radiusRange);
  63210. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63211. };
  63212. /**
  63213. * Returns a string to use to update the GPU particles update shader
  63214. * @returns a string containng the defines string
  63215. */
  63216. SphereParticleEmitter.prototype.getEffectDefines = function () {
  63217. return "#define SPHEREEMITTER";
  63218. };
  63219. /**
  63220. * Returns the string "SphereParticleEmitter"
  63221. * @returns a string containing the class name
  63222. */
  63223. SphereParticleEmitter.prototype.getClassName = function () {
  63224. return "SphereParticleEmitter";
  63225. };
  63226. /**
  63227. * Serializes the particle system to a JSON object.
  63228. * @returns the JSON object
  63229. */
  63230. SphereParticleEmitter.prototype.serialize = function () {
  63231. var serializationObject = {};
  63232. serializationObject.type = this.getClassName();
  63233. serializationObject.radius = this.radius;
  63234. serializationObject.radiusRange = this.radiusRange;
  63235. serializationObject.directionRandomizer = this.directionRandomizer;
  63236. return serializationObject;
  63237. };
  63238. /**
  63239. * Parse properties from a JSON object
  63240. * @param serializationObject defines the JSON object
  63241. */
  63242. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  63243. this.radius = serializationObject.radius;
  63244. this.radiusRange = serializationObject.radiusRange;
  63245. this.directionRandomizer = serializationObject.directionRandomizer;
  63246. };
  63247. return SphereParticleEmitter;
  63248. }());
  63249. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  63250. /**
  63251. * Particle emitter emitting particles from the inside of a sphere.
  63252. * It emits the particles randomly between two vectors.
  63253. */
  63254. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  63255. __extends(SphereDirectedParticleEmitter, _super);
  63256. /**
  63257. * Creates a new instance SphereDirectedParticleEmitter
  63258. * @param radius the radius of the emission sphere (1 by default)
  63259. * @param direction1 the min limit of the emission direction (up vector by default)
  63260. * @param direction2 the max limit of the emission direction (up vector by default)
  63261. */
  63262. function SphereDirectedParticleEmitter(radius,
  63263. /**
  63264. * The min limit of the emission direction.
  63265. */
  63266. direction1,
  63267. /**
  63268. * The max limit of the emission direction.
  63269. */
  63270. direction2) {
  63271. if (radius === void 0) { radius = 1; }
  63272. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63273. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63274. var _this = _super.call(this, radius) || this;
  63275. _this.direction1 = direction1;
  63276. _this.direction2 = direction2;
  63277. return _this;
  63278. }
  63279. /**
  63280. * Called by the particle System when the direction is computed for the created particle.
  63281. * @param worldMatrix is the world matrix of the particle system
  63282. * @param directionToUpdate is the direction vector to update with the result
  63283. * @param particle is the particle we are computed the direction for
  63284. */
  63285. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63286. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63287. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63288. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63289. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63290. };
  63291. /**
  63292. * Clones the current emitter and returns a copy of it
  63293. * @returns the new emitter
  63294. */
  63295. SphereDirectedParticleEmitter.prototype.clone = function () {
  63296. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  63297. BABYLON.Tools.DeepCopy(this, newOne);
  63298. return newOne;
  63299. };
  63300. /**
  63301. * Called by the GPUParticleSystem to setup the update shader
  63302. * @param effect defines the update shader
  63303. */
  63304. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63305. effect.setFloat("radius", this.radius);
  63306. effect.setFloat("radiusRange", this.radiusRange);
  63307. effect.setVector3("direction1", this.direction1);
  63308. effect.setVector3("direction2", this.direction2);
  63309. };
  63310. /**
  63311. * Returns a string to use to update the GPU particles update shader
  63312. * @returns a string containng the defines string
  63313. */
  63314. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63315. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  63316. };
  63317. /**
  63318. * Returns the string "SphereDirectedParticleEmitter"
  63319. * @returns a string containing the class name
  63320. */
  63321. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  63322. return "SphereDirectedParticleEmitter";
  63323. };
  63324. /**
  63325. * Serializes the particle system to a JSON object.
  63326. * @returns the JSON object
  63327. */
  63328. SphereDirectedParticleEmitter.prototype.serialize = function () {
  63329. var serializationObject = _super.prototype.serialize.call(this);
  63330. serializationObject.direction1 = this.direction1.asArray();
  63331. serializationObject.direction2 = this.direction2.asArray();
  63332. return serializationObject;
  63333. };
  63334. /**
  63335. * Parse properties from a JSON object
  63336. * @param serializationObject defines the JSON object
  63337. */
  63338. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63339. _super.prototype.parse.call(this, serializationObject);
  63340. this.direction1.copyFrom(serializationObject.direction1);
  63341. this.direction2.copyFrom(serializationObject.direction2);
  63342. };
  63343. return SphereDirectedParticleEmitter;
  63344. }(SphereParticleEmitter));
  63345. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  63346. })(BABYLON || (BABYLON = {}));
  63347. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  63348. var BABYLON;
  63349. (function (BABYLON) {
  63350. /**
  63351. * Particle emitter emitting particles from the inside of a hemisphere.
  63352. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  63353. */
  63354. var HemisphericParticleEmitter = /** @class */ (function () {
  63355. /**
  63356. * Creates a new instance HemisphericParticleEmitter
  63357. * @param radius the radius of the emission hemisphere (1 by default)
  63358. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63359. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63360. */
  63361. function HemisphericParticleEmitter(
  63362. /**
  63363. * The radius of the emission hemisphere.
  63364. */
  63365. radius,
  63366. /**
  63367. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63368. */
  63369. radiusRange,
  63370. /**
  63371. * How much to randomize the particle direction [0-1].
  63372. */
  63373. directionRandomizer) {
  63374. if (radius === void 0) { radius = 1; }
  63375. if (radiusRange === void 0) { radiusRange = 1; }
  63376. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63377. this.radius = radius;
  63378. this.radiusRange = radiusRange;
  63379. this.directionRandomizer = directionRandomizer;
  63380. }
  63381. /**
  63382. * Called by the particle System when the direction is computed for the created particle.
  63383. * @param worldMatrix is the world matrix of the particle system
  63384. * @param directionToUpdate is the direction vector to update with the result
  63385. * @param particle is the particle we are computed the direction for
  63386. */
  63387. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63388. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63389. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63390. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63391. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63392. direction.x += randX;
  63393. direction.y += randY;
  63394. direction.z += randZ;
  63395. direction.normalize();
  63396. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63397. };
  63398. /**
  63399. * Called by the particle System when the position is computed for the created particle.
  63400. * @param worldMatrix is the world matrix of the particle system
  63401. * @param positionToUpdate is the position vector to update with the result
  63402. * @param particle is the particle we are computed the position for
  63403. */
  63404. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63405. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63406. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63407. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63408. var theta = Math.acos(2 * v - 1);
  63409. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63410. var randY = randRadius * Math.cos(theta);
  63411. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  63413. };
  63414. /**
  63415. * Clones the current emitter and returns a copy of it
  63416. * @returns the new emitter
  63417. */
  63418. HemisphericParticleEmitter.prototype.clone = function () {
  63419. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  63420. BABYLON.Tools.DeepCopy(this, newOne);
  63421. return newOne;
  63422. };
  63423. /**
  63424. * Called by the GPUParticleSystem to setup the update shader
  63425. * @param effect defines the update shader
  63426. */
  63427. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  63428. effect.setFloat("radius", this.radius);
  63429. effect.setFloat("radiusRange", this.radiusRange);
  63430. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63431. };
  63432. /**
  63433. * Returns a string to use to update the GPU particles update shader
  63434. * @returns a string containng the defines string
  63435. */
  63436. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  63437. return "#define HEMISPHERICEMITTER";
  63438. };
  63439. /**
  63440. * Returns the string "HemisphericParticleEmitter"
  63441. * @returns a string containing the class name
  63442. */
  63443. HemisphericParticleEmitter.prototype.getClassName = function () {
  63444. return "HemisphericParticleEmitter";
  63445. };
  63446. /**
  63447. * Serializes the particle system to a JSON object.
  63448. * @returns the JSON object
  63449. */
  63450. HemisphericParticleEmitter.prototype.serialize = function () {
  63451. var serializationObject = {};
  63452. serializationObject.type = this.getClassName();
  63453. serializationObject.radius = this.radius;
  63454. serializationObject.radiusRange = this.radiusRange;
  63455. serializationObject.directionRandomizer = this.directionRandomizer;
  63456. return serializationObject;
  63457. };
  63458. /**
  63459. * Parse properties from a JSON object
  63460. * @param serializationObject defines the JSON object
  63461. */
  63462. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  63463. this.radius = serializationObject.radius;
  63464. this.radiusRange = serializationObject.radiusRange;
  63465. this.directionRandomizer = serializationObject.directionRandomizer;
  63466. };
  63467. return HemisphericParticleEmitter;
  63468. }());
  63469. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  63470. })(BABYLON || (BABYLON = {}));
  63471. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  63472. var BABYLON;
  63473. (function (BABYLON) {
  63474. /**
  63475. * Particle emitter emitting particles from a point.
  63476. * It emits the particles randomly between 2 given directions.
  63477. */
  63478. var PointParticleEmitter = /** @class */ (function () {
  63479. /**
  63480. * Creates a new instance PointParticleEmitter
  63481. */
  63482. function PointParticleEmitter() {
  63483. /**
  63484. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63485. */
  63486. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63487. /**
  63488. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63489. */
  63490. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63491. }
  63492. /**
  63493. * Called by the particle System when the direction is computed for the created particle.
  63494. * @param worldMatrix is the world matrix of the particle system
  63495. * @param directionToUpdate is the direction vector to update with the result
  63496. * @param particle is the particle we are computed the direction for
  63497. */
  63498. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63499. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63500. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63501. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63502. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63503. };
  63504. /**
  63505. * Called by the particle System when the position is computed for the created particle.
  63506. * @param worldMatrix is the world matrix of the particle system
  63507. * @param positionToUpdate is the position vector to update with the result
  63508. * @param particle is the particle we are computed the position for
  63509. */
  63510. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63511. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  63512. };
  63513. /**
  63514. * Clones the current emitter and returns a copy of it
  63515. * @returns the new emitter
  63516. */
  63517. PointParticleEmitter.prototype.clone = function () {
  63518. var newOne = new PointParticleEmitter();
  63519. BABYLON.Tools.DeepCopy(this, newOne);
  63520. return newOne;
  63521. };
  63522. /**
  63523. * Called by the GPUParticleSystem to setup the update shader
  63524. * @param effect defines the update shader
  63525. */
  63526. PointParticleEmitter.prototype.applyToShader = function (effect) {
  63527. effect.setVector3("direction1", this.direction1);
  63528. effect.setVector3("direction2", this.direction2);
  63529. };
  63530. /**
  63531. * Returns a string to use to update the GPU particles update shader
  63532. * @returns a string containng the defines string
  63533. */
  63534. PointParticleEmitter.prototype.getEffectDefines = function () {
  63535. return "#define POINTEMITTER";
  63536. };
  63537. /**
  63538. * Returns the string "PointParticleEmitter"
  63539. * @returns a string containing the class name
  63540. */
  63541. PointParticleEmitter.prototype.getClassName = function () {
  63542. return "PointParticleEmitter";
  63543. };
  63544. /**
  63545. * Serializes the particle system to a JSON object.
  63546. * @returns the JSON object
  63547. */
  63548. PointParticleEmitter.prototype.serialize = function () {
  63549. var serializationObject = {};
  63550. serializationObject.type = this.getClassName();
  63551. serializationObject.direction1 = this.direction1.asArray();
  63552. serializationObject.direction2 = this.direction2.asArray();
  63553. return serializationObject;
  63554. };
  63555. /**
  63556. * Parse properties from a JSON object
  63557. * @param serializationObject defines the JSON object
  63558. */
  63559. PointParticleEmitter.prototype.parse = function (serializationObject) {
  63560. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63561. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63562. };
  63563. return PointParticleEmitter;
  63564. }());
  63565. BABYLON.PointParticleEmitter = PointParticleEmitter;
  63566. })(BABYLON || (BABYLON = {}));
  63567. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  63568. var BABYLON;
  63569. (function (BABYLON) {
  63570. // Adds the parsers to the scene parsers.
  63571. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  63572. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  63573. if (!individualParser) {
  63574. return;
  63575. }
  63576. // Particles Systems
  63577. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63578. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63579. var parsedParticleSystem = parsedData.particleSystems[index];
  63580. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  63581. }
  63582. }
  63583. });
  63584. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  63585. if (parsedParticleSystem.activeParticleCount) {
  63586. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63587. return ps;
  63588. }
  63589. else {
  63590. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63591. return ps;
  63592. }
  63593. });
  63594. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  63595. if (uniformsNames === void 0) { uniformsNames = []; }
  63596. if (samplers === void 0) { samplers = []; }
  63597. if (defines === void 0) { defines = ""; }
  63598. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  63599. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  63600. if (defines.indexOf(" BILLBOARD") === -1) {
  63601. defines += "\n#define BILLBOARD\n";
  63602. }
  63603. if (samplers.indexOf("diffuseSampler") === -1) {
  63604. samplers.push("diffuseSampler");
  63605. }
  63606. return this.createEffect({
  63607. vertex: "particles",
  63608. fragmentElement: fragmentName
  63609. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  63610. };
  63611. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  63612. var results = new Array();
  63613. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63614. var particleSystem = this.getScene().particleSystems[index];
  63615. if (particleSystem.emitter === this) {
  63616. results.push(particleSystem);
  63617. }
  63618. }
  63619. return results;
  63620. };
  63621. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  63622. var results = new Array();
  63623. var descendants = this.getDescendants();
  63624. descendants.push(this);
  63625. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63626. var particleSystem = this.getScene().particleSystems[index];
  63627. var emitter = particleSystem.emitter;
  63628. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  63629. results.push(particleSystem);
  63630. }
  63631. }
  63632. return results;
  63633. };
  63634. })(BABYLON || (BABYLON = {}));
  63635. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  63636. var BABYLON;
  63637. (function (BABYLON) {
  63638. /**
  63639. * Type of sub emitter
  63640. */
  63641. var SubEmitterType;
  63642. (function (SubEmitterType) {
  63643. /**
  63644. * Attached to the particle over it's lifetime
  63645. */
  63646. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  63647. /**
  63648. * Created when the particle dies
  63649. */
  63650. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  63651. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  63652. /**
  63653. * Sub emitter class used to emit particles from an existing particle
  63654. */
  63655. var SubEmitter = /** @class */ (function () {
  63656. /**
  63657. * Creates a sub emitter
  63658. * @param particleSystem the particle system to be used by the sub emitter
  63659. */
  63660. function SubEmitter(
  63661. /**
  63662. * the particle system to be used by the sub emitter
  63663. */
  63664. particleSystem) {
  63665. this.particleSystem = particleSystem;
  63666. /**
  63667. * Type of the submitter (Default: END)
  63668. */
  63669. this.type = SubEmitterType.END;
  63670. /**
  63671. * 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)
  63672. * Note: This only is supported when using an emitter of type Mesh
  63673. */
  63674. this.inheritDirection = false;
  63675. /**
  63676. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  63677. */
  63678. this.inheritedVelocityAmount = 0;
  63679. // Create mesh as emitter to support rotation
  63680. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  63681. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  63682. }
  63683. // Automatically dispose of subemitter when system is disposed
  63684. particleSystem.onDisposeObservable.add(function () {
  63685. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  63686. particleSystem.emitter.dispose();
  63687. }
  63688. });
  63689. }
  63690. /**
  63691. * Clones the sub emitter
  63692. * @returns the cloned sub emitter
  63693. */
  63694. SubEmitter.prototype.clone = function () {
  63695. // Clone particle system
  63696. var emitter = this.particleSystem.emitter;
  63697. if (!emitter) {
  63698. emitter = new BABYLON.Vector3();
  63699. }
  63700. else if (emitter instanceof BABYLON.Vector3) {
  63701. emitter = emitter.clone();
  63702. }
  63703. else if (emitter instanceof BABYLON.AbstractMesh) {
  63704. emitter = new BABYLON.Mesh("", emitter.getScene());
  63705. emitter.isVisible = false;
  63706. }
  63707. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  63708. // Clone properties
  63709. clone.type = this.type;
  63710. clone.inheritDirection = this.inheritDirection;
  63711. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63712. clone.particleSystem._disposeEmitterOnDispose = true;
  63713. clone.particleSystem.disposeOnStop = true;
  63714. return clone;
  63715. };
  63716. /**
  63717. * Serialize current object to a JSON object
  63718. * @returns the serialized object
  63719. */
  63720. SubEmitter.prototype.serialize = function () {
  63721. var serializationObject = {};
  63722. serializationObject.type = this.type;
  63723. serializationObject.inheritDirection = this.inheritDirection;
  63724. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63725. serializationObject.particleSystem = this.particleSystem.serialize();
  63726. return serializationObject;
  63727. };
  63728. /**
  63729. * Creates a new SubEmitter from a serialized JSON version
  63730. * @param serializationObject defines the JSON object to read from
  63731. * @param scene defines the hosting scene
  63732. * @param rootUrl defines the rootUrl for data loading
  63733. * @returns a new SubEmitter
  63734. */
  63735. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  63736. var system = serializationObject.particleSystem;
  63737. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  63738. subEmitter.type = serializationObject.type;
  63739. subEmitter.inheritDirection = serializationObject.inheritDirection;
  63740. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  63741. subEmitter.particleSystem._isSubEmitter = true;
  63742. return subEmitter;
  63743. };
  63744. /** Release associated resources */
  63745. SubEmitter.prototype.dispose = function () {
  63746. this.particleSystem.dispose();
  63747. };
  63748. return SubEmitter;
  63749. }());
  63750. BABYLON.SubEmitter = SubEmitter;
  63751. })(BABYLON || (BABYLON = {}));
  63752. //# sourceMappingURL=babylon.subEmitter.js.map
  63753. var BABYLON;
  63754. (function (BABYLON) {
  63755. /**
  63756. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  63757. *
  63758. * This returned material effects how the mesh will look based on the code in the shaders.
  63759. *
  63760. * @see http://doc.babylonjs.com/how_to/shader_material
  63761. */
  63762. var ShaderMaterial = /** @class */ (function (_super) {
  63763. __extends(ShaderMaterial, _super);
  63764. /**
  63765. * Instantiate a new shader material.
  63766. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  63767. * This returned material effects how the mesh will look based on the code in the shaders.
  63768. * @see http://doc.babylonjs.com/how_to/shader_material
  63769. * @param name Define the name of the material in the scene
  63770. * @param scene Define the scene the material belongs to
  63771. * @param shaderPath Defines the route to the shader code in one of three ways:
  63772. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  63773. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  63774. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  63775. * @param options Define the options used to create the shader
  63776. */
  63777. function ShaderMaterial(name, scene, shaderPath, options) {
  63778. if (options === void 0) { options = {}; }
  63779. var _this = _super.call(this, name, scene) || this;
  63780. _this._textures = {};
  63781. _this._textureArrays = {};
  63782. _this._floats = {};
  63783. _this._ints = {};
  63784. _this._floatsArrays = {};
  63785. _this._colors3 = {};
  63786. _this._colors3Arrays = {};
  63787. _this._colors4 = {};
  63788. _this._vectors2 = {};
  63789. _this._vectors3 = {};
  63790. _this._vectors4 = {};
  63791. _this._matrices = {};
  63792. _this._matrices3x3 = {};
  63793. _this._matrices2x2 = {};
  63794. _this._vectors2Arrays = {};
  63795. _this._vectors3Arrays = {};
  63796. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  63797. _this._shaderPath = shaderPath;
  63798. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  63799. return _this;
  63800. }
  63801. /**
  63802. * Gets the current class name of the material e.g. "ShaderMaterial"
  63803. * Mainly use in serialization.
  63804. * @returns the class name
  63805. */
  63806. ShaderMaterial.prototype.getClassName = function () {
  63807. return "ShaderMaterial";
  63808. };
  63809. /**
  63810. * Specifies if the material will require alpha blending
  63811. * @returns a boolean specifying if alpha blending is needed
  63812. */
  63813. ShaderMaterial.prototype.needAlphaBlending = function () {
  63814. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  63815. };
  63816. /**
  63817. * Specifies if this material should be rendered in alpha test mode
  63818. * @returns a boolean specifying if an alpha test is needed.
  63819. */
  63820. ShaderMaterial.prototype.needAlphaTesting = function () {
  63821. return this._options.needAlphaTesting;
  63822. };
  63823. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  63824. if (this._options.uniforms.indexOf(uniformName) === -1) {
  63825. this._options.uniforms.push(uniformName);
  63826. }
  63827. };
  63828. /**
  63829. * Set a texture in the shader.
  63830. * @param name Define the name of the uniform samplers as defined in the shader
  63831. * @param texture Define the texture to bind to this sampler
  63832. * @return the material itself allowing "fluent" like uniform updates
  63833. */
  63834. ShaderMaterial.prototype.setTexture = function (name, texture) {
  63835. if (this._options.samplers.indexOf(name) === -1) {
  63836. this._options.samplers.push(name);
  63837. }
  63838. this._textures[name] = texture;
  63839. return this;
  63840. };
  63841. /**
  63842. * Set a texture array in the shader.
  63843. * @param name Define the name of the uniform sampler array as defined in the shader
  63844. * @param textures Define the list of textures to bind to this sampler
  63845. * @return the material itself allowing "fluent" like uniform updates
  63846. */
  63847. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  63848. if (this._options.samplers.indexOf(name) === -1) {
  63849. this._options.samplers.push(name);
  63850. }
  63851. this._checkUniform(name);
  63852. this._textureArrays[name] = textures;
  63853. return this;
  63854. };
  63855. /**
  63856. * Set a float in the shader.
  63857. * @param name Define the name of the uniform as defined in the shader
  63858. * @param value Define the value to give to the uniform
  63859. * @return the material itself allowing "fluent" like uniform updates
  63860. */
  63861. ShaderMaterial.prototype.setFloat = function (name, value) {
  63862. this._checkUniform(name);
  63863. this._floats[name] = value;
  63864. return this;
  63865. };
  63866. /**
  63867. * Set a int in the shader.
  63868. * @param name Define the name of the uniform as defined in the shader
  63869. * @param value Define the value to give to the uniform
  63870. * @return the material itself allowing "fluent" like uniform updates
  63871. */
  63872. ShaderMaterial.prototype.setInt = function (name, value) {
  63873. this._checkUniform(name);
  63874. this._ints[name] = value;
  63875. return this;
  63876. };
  63877. /**
  63878. * Set an array of floats in the shader.
  63879. * @param name Define the name of the uniform as defined in the shader
  63880. * @param value Define the value to give to the uniform
  63881. * @return the material itself allowing "fluent" like uniform updates
  63882. */
  63883. ShaderMaterial.prototype.setFloats = function (name, value) {
  63884. this._checkUniform(name);
  63885. this._floatsArrays[name] = value;
  63886. return this;
  63887. };
  63888. /**
  63889. * Set a vec3 in the shader from a Color3.
  63890. * @param name Define the name of the uniform as defined in the shader
  63891. * @param value Define the value to give to the uniform
  63892. * @return the material itself allowing "fluent" like uniform updates
  63893. */
  63894. ShaderMaterial.prototype.setColor3 = function (name, value) {
  63895. this._checkUniform(name);
  63896. this._colors3[name] = value;
  63897. return this;
  63898. };
  63899. /**
  63900. * Set a vec3 array in the shader from a Color3 array.
  63901. * @param name Define the name of the uniform as defined in the shader
  63902. * @param value Define the value to give to the uniform
  63903. * @return the material itself allowing "fluent" like uniform updates
  63904. */
  63905. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  63906. this._checkUniform(name);
  63907. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  63908. color.toArray(arr, arr.length);
  63909. return arr;
  63910. }, []);
  63911. return this;
  63912. };
  63913. /**
  63914. * Set a vec4 in the shader from a Color4.
  63915. * @param name Define the name of the uniform as defined in the shader
  63916. * @param value Define the value to give to the uniform
  63917. * @return the material itself allowing "fluent" like uniform updates
  63918. */
  63919. ShaderMaterial.prototype.setColor4 = function (name, value) {
  63920. this._checkUniform(name);
  63921. this._colors4[name] = value;
  63922. return this;
  63923. };
  63924. /**
  63925. * Set a vec2 in the shader from a Vector2.
  63926. * @param name Define the name of the uniform as defined in the shader
  63927. * @param value Define the value to give to the uniform
  63928. * @return the material itself allowing "fluent" like uniform updates
  63929. */
  63930. ShaderMaterial.prototype.setVector2 = function (name, value) {
  63931. this._checkUniform(name);
  63932. this._vectors2[name] = value;
  63933. return this;
  63934. };
  63935. /**
  63936. * Set a vec3 in the shader from a Vector3.
  63937. * @param name Define the name of the uniform as defined in the shader
  63938. * @param value Define the value to give to the uniform
  63939. * @return the material itself allowing "fluent" like uniform updates
  63940. */
  63941. ShaderMaterial.prototype.setVector3 = function (name, value) {
  63942. this._checkUniform(name);
  63943. this._vectors3[name] = value;
  63944. return this;
  63945. };
  63946. /**
  63947. * Set a vec4 in the shader from a Vector4.
  63948. * @param name Define the name of the uniform as defined in the shader
  63949. * @param value Define the value to give to the uniform
  63950. * @return the material itself allowing "fluent" like uniform updates
  63951. */
  63952. ShaderMaterial.prototype.setVector4 = function (name, value) {
  63953. this._checkUniform(name);
  63954. this._vectors4[name] = value;
  63955. return this;
  63956. };
  63957. /**
  63958. * Set a mat4 in the shader from a Matrix.
  63959. * @param name Define the name of the uniform as defined in the shader
  63960. * @param value Define the value to give to the uniform
  63961. * @return the material itself allowing "fluent" like uniform updates
  63962. */
  63963. ShaderMaterial.prototype.setMatrix = function (name, value) {
  63964. this._checkUniform(name);
  63965. this._matrices[name] = value;
  63966. return this;
  63967. };
  63968. /**
  63969. * Set a mat3 in the shader from a Float32Array.
  63970. * @param name Define the name of the uniform as defined in the shader
  63971. * @param value Define the value to give to the uniform
  63972. * @return the material itself allowing "fluent" like uniform updates
  63973. */
  63974. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  63975. this._checkUniform(name);
  63976. this._matrices3x3[name] = value;
  63977. return this;
  63978. };
  63979. /**
  63980. * Set a mat2 in the shader from a Float32Array.
  63981. * @param name Define the name of the uniform as defined in the shader
  63982. * @param value Define the value to give to the uniform
  63983. * @return the material itself allowing "fluent" like uniform updates
  63984. */
  63985. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  63986. this._checkUniform(name);
  63987. this._matrices2x2[name] = value;
  63988. return this;
  63989. };
  63990. /**
  63991. * Set a vec2 array in the shader from a number array.
  63992. * @param name Define the name of the uniform as defined in the shader
  63993. * @param value Define the value to give to the uniform
  63994. * @return the material itself allowing "fluent" like uniform updates
  63995. */
  63996. ShaderMaterial.prototype.setArray2 = function (name, value) {
  63997. this._checkUniform(name);
  63998. this._vectors2Arrays[name] = value;
  63999. return this;
  64000. };
  64001. /**
  64002. * Set a vec3 array in the shader from a number array.
  64003. * @param name Define the name of the uniform as defined in the shader
  64004. * @param value Define the value to give to the uniform
  64005. * @return the material itself allowing "fluent" like uniform updates
  64006. */
  64007. ShaderMaterial.prototype.setArray3 = function (name, value) {
  64008. this._checkUniform(name);
  64009. this._vectors3Arrays[name] = value;
  64010. return this;
  64011. };
  64012. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  64013. if (!mesh) {
  64014. return true;
  64015. }
  64016. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  64017. return false;
  64018. }
  64019. return false;
  64020. };
  64021. /**
  64022. * Checks if the material is ready to render the requested mesh
  64023. * @param mesh Define the mesh to render
  64024. * @param useInstances Define whether or not the material is used with instances
  64025. * @returns true if ready, otherwise false
  64026. */
  64027. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  64028. var scene = this.getScene();
  64029. var engine = scene.getEngine();
  64030. if (!this.checkReadyOnEveryCall) {
  64031. if (this._renderId === scene.getRenderId()) {
  64032. if (this._checkCache(scene, mesh, useInstances)) {
  64033. return true;
  64034. }
  64035. }
  64036. }
  64037. // Instances
  64038. var defines = [];
  64039. var attribs = [];
  64040. var fallbacks = new BABYLON.EffectFallbacks();
  64041. for (var index = 0; index < this._options.defines.length; index++) {
  64042. defines.push(this._options.defines[index]);
  64043. }
  64044. for (var index = 0; index < this._options.attributes.length; index++) {
  64045. attribs.push(this._options.attributes[index]);
  64046. }
  64047. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  64048. attribs.push(BABYLON.VertexBuffer.ColorKind);
  64049. defines.push("#define VERTEXCOLOR");
  64050. }
  64051. if (useInstances) {
  64052. defines.push("#define INSTANCES");
  64053. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  64054. }
  64055. // Bones
  64056. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64057. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64058. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64059. if (mesh.numBoneInfluencers > 4) {
  64060. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64061. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64062. }
  64063. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64064. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64065. fallbacks.addCPUSkinningFallback(0, mesh);
  64066. if (this._options.uniforms.indexOf("mBones") === -1) {
  64067. this._options.uniforms.push("mBones");
  64068. }
  64069. }
  64070. else {
  64071. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64072. }
  64073. // Textures
  64074. for (var name in this._textures) {
  64075. if (!this._textures[name].isReady()) {
  64076. return false;
  64077. }
  64078. }
  64079. // Alpha test
  64080. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  64081. defines.push("#define ALPHATEST");
  64082. }
  64083. var previousEffect = this._effect;
  64084. var join = defines.join("\n");
  64085. this._effect = engine.createEffect(this._shaderPath, {
  64086. attributes: attribs,
  64087. uniformsNames: this._options.uniforms,
  64088. uniformBuffersNames: this._options.uniformBuffers,
  64089. samplers: this._options.samplers,
  64090. defines: join,
  64091. fallbacks: fallbacks,
  64092. onCompiled: this.onCompiled,
  64093. onError: this.onError
  64094. }, engine);
  64095. if (!this._effect.isReady()) {
  64096. return false;
  64097. }
  64098. if (previousEffect !== this._effect) {
  64099. scene.resetCachedMaterial();
  64100. }
  64101. this._renderId = scene.getRenderId();
  64102. return true;
  64103. };
  64104. /**
  64105. * Binds the world matrix to the material
  64106. * @param world defines the world transformation matrix
  64107. */
  64108. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  64109. var scene = this.getScene();
  64110. if (!this._effect) {
  64111. return;
  64112. }
  64113. if (this._options.uniforms.indexOf("world") !== -1) {
  64114. this._effect.setMatrix("world", world);
  64115. }
  64116. if (this._options.uniforms.indexOf("worldView") !== -1) {
  64117. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  64118. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  64119. }
  64120. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  64121. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  64122. }
  64123. };
  64124. /**
  64125. * Binds the material to the mesh
  64126. * @param world defines the world transformation matrix
  64127. * @param mesh defines the mesh to bind the material to
  64128. */
  64129. ShaderMaterial.prototype.bind = function (world, mesh) {
  64130. // Std values
  64131. this.bindOnlyWorldMatrix(world);
  64132. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  64133. if (this._options.uniforms.indexOf("view") !== -1) {
  64134. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  64135. }
  64136. if (this._options.uniforms.indexOf("projection") !== -1) {
  64137. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  64138. }
  64139. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  64140. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  64141. }
  64142. // Bones
  64143. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  64144. var name;
  64145. // Texture
  64146. for (name in this._textures) {
  64147. this._effect.setTexture(name, this._textures[name]);
  64148. }
  64149. // Texture arrays
  64150. for (name in this._textureArrays) {
  64151. this._effect.setTextureArray(name, this._textureArrays[name]);
  64152. }
  64153. // Int
  64154. for (name in this._ints) {
  64155. this._effect.setInt(name, this._ints[name]);
  64156. }
  64157. // Float
  64158. for (name in this._floats) {
  64159. this._effect.setFloat(name, this._floats[name]);
  64160. }
  64161. // Floats
  64162. for (name in this._floatsArrays) {
  64163. this._effect.setArray(name, this._floatsArrays[name]);
  64164. }
  64165. // Color3
  64166. for (name in this._colors3) {
  64167. this._effect.setColor3(name, this._colors3[name]);
  64168. }
  64169. for (name in this._colors3Arrays) {
  64170. this._effect.setArray3(name, this._colors3Arrays[name]);
  64171. }
  64172. // Color4
  64173. for (name in this._colors4) {
  64174. var color = this._colors4[name];
  64175. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64176. }
  64177. // Vector2
  64178. for (name in this._vectors2) {
  64179. this._effect.setVector2(name, this._vectors2[name]);
  64180. }
  64181. // Vector3
  64182. for (name in this._vectors3) {
  64183. this._effect.setVector3(name, this._vectors3[name]);
  64184. }
  64185. // Vector4
  64186. for (name in this._vectors4) {
  64187. this._effect.setVector4(name, this._vectors4[name]);
  64188. }
  64189. // Matrix
  64190. for (name in this._matrices) {
  64191. this._effect.setMatrix(name, this._matrices[name]);
  64192. }
  64193. // Matrix 3x3
  64194. for (name in this._matrices3x3) {
  64195. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  64196. }
  64197. // Matrix 2x2
  64198. for (name in this._matrices2x2) {
  64199. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  64200. }
  64201. // Vector2Array
  64202. for (name in this._vectors2Arrays) {
  64203. this._effect.setArray2(name, this._vectors2Arrays[name]);
  64204. }
  64205. // Vector3Array
  64206. for (name in this._vectors3Arrays) {
  64207. this._effect.setArray3(name, this._vectors3Arrays[name]);
  64208. }
  64209. }
  64210. this._afterBind(mesh);
  64211. };
  64212. /**
  64213. * Gets the active textures from the material
  64214. * @returns an array of textures
  64215. */
  64216. ShaderMaterial.prototype.getActiveTextures = function () {
  64217. var activeTextures = _super.prototype.getActiveTextures.call(this);
  64218. for (var name in this._textures) {
  64219. activeTextures.push(this._textures[name]);
  64220. }
  64221. for (var name in this._textureArrays) {
  64222. var array = this._textureArrays[name];
  64223. for (var index = 0; index < array.length; index++) {
  64224. activeTextures.push(array[index]);
  64225. }
  64226. }
  64227. return activeTextures;
  64228. };
  64229. /**
  64230. * Specifies if the material uses a texture
  64231. * @param texture defines the texture to check against the material
  64232. * @returns a boolean specifying if the material uses the texture
  64233. */
  64234. ShaderMaterial.prototype.hasTexture = function (texture) {
  64235. if (_super.prototype.hasTexture.call(this, texture)) {
  64236. return true;
  64237. }
  64238. for (var name in this._textures) {
  64239. if (this._textures[name] === texture) {
  64240. return true;
  64241. }
  64242. }
  64243. for (var name in this._textureArrays) {
  64244. var array = this._textureArrays[name];
  64245. for (var index = 0; index < array.length; index++) {
  64246. if (array[index] === texture) {
  64247. return true;
  64248. }
  64249. }
  64250. }
  64251. return false;
  64252. };
  64253. /**
  64254. * Makes a duplicate of the material, and gives it a new name
  64255. * @param name defines the new name for the duplicated material
  64256. * @returns the cloned material
  64257. */
  64258. ShaderMaterial.prototype.clone = function (name) {
  64259. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  64260. return newShaderMaterial;
  64261. };
  64262. /**
  64263. * Disposes the material
  64264. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  64265. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  64266. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  64267. */
  64268. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  64269. if (forceDisposeTextures) {
  64270. var name;
  64271. for (name in this._textures) {
  64272. this._textures[name].dispose();
  64273. }
  64274. for (name in this._textureArrays) {
  64275. var array = this._textureArrays[name];
  64276. for (var index = 0; index < array.length; index++) {
  64277. array[index].dispose();
  64278. }
  64279. }
  64280. }
  64281. this._textures = {};
  64282. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  64283. };
  64284. /**
  64285. * Serializes this material in a JSON representation
  64286. * @returns the serialized material object
  64287. */
  64288. ShaderMaterial.prototype.serialize = function () {
  64289. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64290. serializationObject.customType = "BABYLON.ShaderMaterial";
  64291. serializationObject.options = this._options;
  64292. serializationObject.shaderPath = this._shaderPath;
  64293. var name;
  64294. // Texture
  64295. serializationObject.textures = {};
  64296. for (name in this._textures) {
  64297. serializationObject.textures[name] = this._textures[name].serialize();
  64298. }
  64299. // Texture arrays
  64300. serializationObject.textureArrays = {};
  64301. for (name in this._textureArrays) {
  64302. serializationObject.textureArrays[name] = [];
  64303. var array = this._textureArrays[name];
  64304. for (var index = 0; index < array.length; index++) {
  64305. serializationObject.textureArrays[name].push(array[index].serialize());
  64306. }
  64307. }
  64308. // Float
  64309. serializationObject.floats = {};
  64310. for (name in this._floats) {
  64311. serializationObject.floats[name] = this._floats[name];
  64312. }
  64313. // Float s
  64314. serializationObject.FloatArrays = {};
  64315. for (name in this._floatsArrays) {
  64316. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  64317. }
  64318. // Color3
  64319. serializationObject.colors3 = {};
  64320. for (name in this._colors3) {
  64321. serializationObject.colors3[name] = this._colors3[name].asArray();
  64322. }
  64323. // Color3 array
  64324. serializationObject.colors3Arrays = {};
  64325. for (name in this._colors3Arrays) {
  64326. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  64327. }
  64328. // Color4
  64329. serializationObject.colors4 = {};
  64330. for (name in this._colors4) {
  64331. serializationObject.colors4[name] = this._colors4[name].asArray();
  64332. }
  64333. // Vector2
  64334. serializationObject.vectors2 = {};
  64335. for (name in this._vectors2) {
  64336. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  64337. }
  64338. // Vector3
  64339. serializationObject.vectors3 = {};
  64340. for (name in this._vectors3) {
  64341. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  64342. }
  64343. // Vector4
  64344. serializationObject.vectors4 = {};
  64345. for (name in this._vectors4) {
  64346. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  64347. }
  64348. // Matrix
  64349. serializationObject.matrices = {};
  64350. for (name in this._matrices) {
  64351. serializationObject.matrices[name] = this._matrices[name].asArray();
  64352. }
  64353. // Matrix 3x3
  64354. serializationObject.matrices3x3 = {};
  64355. for (name in this._matrices3x3) {
  64356. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  64357. }
  64358. // Matrix 2x2
  64359. serializationObject.matrices2x2 = {};
  64360. for (name in this._matrices2x2) {
  64361. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  64362. }
  64363. // Vector2Array
  64364. serializationObject.vectors2Arrays = {};
  64365. for (name in this._vectors2Arrays) {
  64366. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  64367. }
  64368. // Vector3Array
  64369. serializationObject.vectors3Arrays = {};
  64370. for (name in this._vectors3Arrays) {
  64371. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  64372. }
  64373. return serializationObject;
  64374. };
  64375. /**
  64376. * Creates a shader material from parsed shader material data
  64377. * @param source defines the JSON represnetation of the material
  64378. * @param scene defines the hosting scene
  64379. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  64380. * @returns a new material
  64381. */
  64382. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  64383. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  64384. var name;
  64385. // Texture
  64386. for (name in source.textures) {
  64387. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  64388. }
  64389. // Texture arrays
  64390. for (name in source.textureArrays) {
  64391. var array = source.textureArrays[name];
  64392. var textureArray = new Array();
  64393. for (var index = 0; index < array.length; index++) {
  64394. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  64395. }
  64396. material.setTextureArray(name, textureArray);
  64397. }
  64398. // Float
  64399. for (name in source.floats) {
  64400. material.setFloat(name, source.floats[name]);
  64401. }
  64402. // Float s
  64403. for (name in source.floatsArrays) {
  64404. material.setFloats(name, source.floatsArrays[name]);
  64405. }
  64406. // Color3
  64407. for (name in source.colors3) {
  64408. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  64409. }
  64410. // Color3 arrays
  64411. for (name in source.colors3Arrays) {
  64412. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  64413. if (i % 3 === 0) {
  64414. arr.push([num]);
  64415. }
  64416. else {
  64417. arr[arr.length - 1].push(num);
  64418. }
  64419. return arr;
  64420. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  64421. material.setColor3Array(name, colors);
  64422. }
  64423. // Color4
  64424. for (name in source.colors4) {
  64425. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  64426. }
  64427. // Vector2
  64428. for (name in source.vectors2) {
  64429. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  64430. }
  64431. // Vector3
  64432. for (name in source.vectors3) {
  64433. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  64434. }
  64435. // Vector4
  64436. for (name in source.vectors4) {
  64437. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  64438. }
  64439. // Matrix
  64440. for (name in source.matrices) {
  64441. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  64442. }
  64443. // Matrix 3x3
  64444. for (name in source.matrices3x3) {
  64445. material.setMatrix3x3(name, source.matrices3x3[name]);
  64446. }
  64447. // Matrix 2x2
  64448. for (name in source.matrices2x2) {
  64449. material.setMatrix2x2(name, source.matrices2x2[name]);
  64450. }
  64451. // Vector2Array
  64452. for (name in source.vectors2Arrays) {
  64453. material.setArray2(name, source.vectors2Arrays[name]);
  64454. }
  64455. // Vector3Array
  64456. for (name in source.vectors3Arrays) {
  64457. material.setArray3(name, source.vectors3Arrays[name]);
  64458. }
  64459. return material;
  64460. };
  64461. return ShaderMaterial;
  64462. }(BABYLON.Material));
  64463. BABYLON.ShaderMaterial = ShaderMaterial;
  64464. })(BABYLON || (BABYLON = {}));
  64465. //# sourceMappingURL=babylon.shaderMaterial.js.map
  64466. var BABYLON;
  64467. (function (BABYLON) {
  64468. /**
  64469. * Mesh representing the gorund
  64470. */
  64471. var GroundMesh = /** @class */ (function (_super) {
  64472. __extends(GroundMesh, _super);
  64473. function GroundMesh(name, scene) {
  64474. var _this = _super.call(this, name, scene) || this;
  64475. /** If octree should be generated */
  64476. _this.generateOctree = false;
  64477. return _this;
  64478. }
  64479. /**
  64480. * "GroundMesh"
  64481. * @returns "GroundMesh"
  64482. */
  64483. GroundMesh.prototype.getClassName = function () {
  64484. return "GroundMesh";
  64485. };
  64486. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  64487. /**
  64488. * The minimum of x and y subdivisions
  64489. */
  64490. get: function () {
  64491. return Math.min(this._subdivisionsX, this._subdivisionsY);
  64492. },
  64493. enumerable: true,
  64494. configurable: true
  64495. });
  64496. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  64497. /**
  64498. * X subdivisions
  64499. */
  64500. get: function () {
  64501. return this._subdivisionsX;
  64502. },
  64503. enumerable: true,
  64504. configurable: true
  64505. });
  64506. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  64507. /**
  64508. * Y subdivisions
  64509. */
  64510. get: function () {
  64511. return this._subdivisionsY;
  64512. },
  64513. enumerable: true,
  64514. configurable: true
  64515. });
  64516. /**
  64517. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  64518. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  64519. * @param chunksCount the number of subdivisions for x and y
  64520. * @param octreeBlocksSize (Default: 32)
  64521. */
  64522. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  64523. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  64524. this._subdivisionsX = chunksCount;
  64525. this._subdivisionsY = chunksCount;
  64526. this.subdivide(chunksCount);
  64527. // Call the octree system optimization if it is defined.
  64528. var thisAsAny = this;
  64529. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  64530. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  64531. }
  64532. };
  64533. /**
  64534. * Returns a height (y) value in the Worl system :
  64535. * the ground altitude at the coordinates (x, z) expressed in the World system.
  64536. * @param x x coordinate
  64537. * @param z z coordinate
  64538. * @returns the ground y position if (x, z) are outside the ground surface.
  64539. */
  64540. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  64541. var world = this.getWorldMatrix();
  64542. var invMat = BABYLON.Tmp.Matrix[5];
  64543. world.invertToRef(invMat);
  64544. var tmpVect = BABYLON.Tmp.Vector3[8];
  64545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  64546. x = tmpVect.x;
  64547. z = tmpVect.z;
  64548. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64549. return this.position.y;
  64550. }
  64551. if (!this._heightQuads || this._heightQuads.length == 0) {
  64552. this._initHeightQuads();
  64553. this._computeHeightQuads();
  64554. }
  64555. var facet = this._getFacetAt(x, z);
  64556. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  64557. // return y in the World system
  64558. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  64559. return tmpVect.y;
  64560. };
  64561. /**
  64562. * Returns a normalized vector (Vector3) orthogonal to the ground
  64563. * at the ground coordinates (x, z) expressed in the World system.
  64564. * @param x x coordinate
  64565. * @param z z coordinate
  64566. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  64567. */
  64568. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  64569. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  64570. this.getNormalAtCoordinatesToRef(x, z, normal);
  64571. return normal;
  64572. };
  64573. /**
  64574. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  64575. * at the ground coordinates (x, z) expressed in the World system.
  64576. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  64577. * @param x x coordinate
  64578. * @param z z coordinate
  64579. * @param ref vector to store the result
  64580. * @returns the GroundMesh.
  64581. */
  64582. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  64583. var world = this.getWorldMatrix();
  64584. var tmpMat = BABYLON.Tmp.Matrix[5];
  64585. world.invertToRef(tmpMat);
  64586. var tmpVect = BABYLON.Tmp.Vector3[8];
  64587. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  64588. x = tmpVect.x;
  64589. z = tmpVect.z;
  64590. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64591. return this;
  64592. }
  64593. if (!this._heightQuads || this._heightQuads.length == 0) {
  64594. this._initHeightQuads();
  64595. this._computeHeightQuads();
  64596. }
  64597. var facet = this._getFacetAt(x, z);
  64598. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  64599. return this;
  64600. };
  64601. /**
  64602. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  64603. * if the ground has been updated.
  64604. * This can be used in the render loop.
  64605. * @returns the GroundMesh.
  64606. */
  64607. GroundMesh.prototype.updateCoordinateHeights = function () {
  64608. if (!this._heightQuads || this._heightQuads.length == 0) {
  64609. this._initHeightQuads();
  64610. }
  64611. this._computeHeightQuads();
  64612. return this;
  64613. };
  64614. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  64615. GroundMesh.prototype._getFacetAt = function (x, z) {
  64616. // retrieve col and row from x, z coordinates in the ground local system
  64617. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  64618. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  64619. var quad = this._heightQuads[row * this._subdivisionsX + col];
  64620. var facet;
  64621. if (z < quad.slope.x * x + quad.slope.y) {
  64622. facet = quad.facet1;
  64623. }
  64624. else {
  64625. facet = quad.facet2;
  64626. }
  64627. return facet;
  64628. };
  64629. // Creates and populates the heightMap array with "facet" elements :
  64630. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  64631. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64632. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64633. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64634. // Returns the GroundMesh.
  64635. GroundMesh.prototype._initHeightQuads = function () {
  64636. var subdivisionsX = this._subdivisionsX;
  64637. var subdivisionsY = this._subdivisionsY;
  64638. this._heightQuads = new Array();
  64639. for (var row = 0; row < subdivisionsY; row++) {
  64640. for (var col = 0; col < subdivisionsX; col++) {
  64641. 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) };
  64642. this._heightQuads[row * subdivisionsX + col] = quad;
  64643. }
  64644. }
  64645. return this;
  64646. };
  64647. // Compute each quad element values and update the the heightMap array :
  64648. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64649. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64650. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64651. // Returns the GroundMesh.
  64652. GroundMesh.prototype._computeHeightQuads = function () {
  64653. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64654. if (!positions) {
  64655. return this;
  64656. }
  64657. var v1 = BABYLON.Tmp.Vector3[3];
  64658. var v2 = BABYLON.Tmp.Vector3[2];
  64659. var v3 = BABYLON.Tmp.Vector3[1];
  64660. var v4 = BABYLON.Tmp.Vector3[0];
  64661. var v1v2 = BABYLON.Tmp.Vector3[4];
  64662. var v1v3 = BABYLON.Tmp.Vector3[5];
  64663. var v1v4 = BABYLON.Tmp.Vector3[6];
  64664. var norm1 = BABYLON.Tmp.Vector3[7];
  64665. var norm2 = BABYLON.Tmp.Vector3[8];
  64666. var i = 0;
  64667. var j = 0;
  64668. var k = 0;
  64669. var cd = 0; // 2D slope coefficient : z = cd * x + h
  64670. var h = 0;
  64671. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  64672. var d2 = 0;
  64673. var subdivisionsX = this._subdivisionsX;
  64674. var subdivisionsY = this._subdivisionsY;
  64675. for (var row = 0; row < subdivisionsY; row++) {
  64676. for (var col = 0; col < subdivisionsX; col++) {
  64677. i = col * 3;
  64678. j = row * (subdivisionsX + 1) * 3;
  64679. k = (row + 1) * (subdivisionsX + 1) * 3;
  64680. v1.x = positions[j + i];
  64681. v1.y = positions[j + i + 1];
  64682. v1.z = positions[j + i + 2];
  64683. v2.x = positions[j + i + 3];
  64684. v2.y = positions[j + i + 4];
  64685. v2.z = positions[j + i + 5];
  64686. v3.x = positions[k + i];
  64687. v3.y = positions[k + i + 1];
  64688. v3.z = positions[k + i + 2];
  64689. v4.x = positions[k + i + 3];
  64690. v4.y = positions[k + i + 4];
  64691. v4.z = positions[k + i + 5];
  64692. // 2D slope V1V4
  64693. cd = (v4.z - v1.z) / (v4.x - v1.x);
  64694. h = v1.z - cd * v1.x; // v1 belongs to the slope
  64695. // facet equations :
  64696. // we compute each facet normal vector
  64697. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  64698. // we compute the value d by applying the equation to v1 which belongs to the plane
  64699. // then we store the facet equation in a Vector4
  64700. v2.subtractToRef(v1, v1v2);
  64701. v3.subtractToRef(v1, v1v3);
  64702. v4.subtractToRef(v1, v1v4);
  64703. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  64704. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  64705. norm1.normalize();
  64706. norm2.normalize();
  64707. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  64708. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  64709. var quad = this._heightQuads[row * subdivisionsX + col];
  64710. quad.slope.copyFromFloats(cd, h);
  64711. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  64712. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  64713. }
  64714. }
  64715. return this;
  64716. };
  64717. /**
  64718. * Serializes this ground mesh
  64719. * @param serializationObject object to write serialization to
  64720. */
  64721. GroundMesh.prototype.serialize = function (serializationObject) {
  64722. _super.prototype.serialize.call(this, serializationObject);
  64723. serializationObject.subdivisionsX = this._subdivisionsX;
  64724. serializationObject.subdivisionsY = this._subdivisionsY;
  64725. serializationObject.minX = this._minX;
  64726. serializationObject.maxX = this._maxX;
  64727. serializationObject.minZ = this._minZ;
  64728. serializationObject.maxZ = this._maxZ;
  64729. serializationObject.width = this._width;
  64730. serializationObject.height = this._height;
  64731. };
  64732. /**
  64733. * Parses a serialized ground mesh
  64734. * @param parsedMesh the serialized mesh
  64735. * @param scene the scene to create the ground mesh in
  64736. * @returns the created ground mesh
  64737. */
  64738. GroundMesh.Parse = function (parsedMesh, scene) {
  64739. var result = new GroundMesh(parsedMesh.name, scene);
  64740. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  64741. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  64742. result._minX = parsedMesh.minX;
  64743. result._maxX = parsedMesh.maxX;
  64744. result._minZ = parsedMesh.minZ;
  64745. result._maxZ = parsedMesh.maxZ;
  64746. result._width = parsedMesh.width;
  64747. result._height = parsedMesh.height;
  64748. return result;
  64749. };
  64750. return GroundMesh;
  64751. }(BABYLON.Mesh));
  64752. BABYLON.GroundMesh = GroundMesh;
  64753. })(BABYLON || (BABYLON = {}));
  64754. //# sourceMappingURL=babylon.groundMesh.js.map
  64755. var BABYLON;
  64756. (function (BABYLON) {
  64757. /**
  64758. * Creates an instance based on a source mesh.
  64759. */
  64760. var InstancedMesh = /** @class */ (function (_super) {
  64761. __extends(InstancedMesh, _super);
  64762. function InstancedMesh(name, source) {
  64763. var _this = _super.call(this, name, source.getScene()) || this;
  64764. /** @hidden */
  64765. _this._indexInSourceMeshInstanceArray = -1;
  64766. source.addInstance(_this);
  64767. _this._sourceMesh = source;
  64768. _this.position.copyFrom(source.position);
  64769. _this.rotation.copyFrom(source.rotation);
  64770. _this.scaling.copyFrom(source.scaling);
  64771. if (source.rotationQuaternion) {
  64772. _this.rotationQuaternion = source.rotationQuaternion.clone();
  64773. }
  64774. _this.infiniteDistance = source.infiniteDistance;
  64775. _this.setPivotMatrix(source.getPivotMatrix());
  64776. _this.refreshBoundingInfo();
  64777. _this._syncSubMeshes();
  64778. return _this;
  64779. }
  64780. /**
  64781. * Returns the string "InstancedMesh".
  64782. */
  64783. InstancedMesh.prototype.getClassName = function () {
  64784. return "InstancedMesh";
  64785. };
  64786. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  64787. // Methods
  64788. /**
  64789. * If the source mesh receives shadows
  64790. */
  64791. get: function () {
  64792. return this._sourceMesh.receiveShadows;
  64793. },
  64794. enumerable: true,
  64795. configurable: true
  64796. });
  64797. Object.defineProperty(InstancedMesh.prototype, "material", {
  64798. /**
  64799. * The material of the source mesh
  64800. */
  64801. get: function () {
  64802. return this._sourceMesh.material;
  64803. },
  64804. enumerable: true,
  64805. configurable: true
  64806. });
  64807. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  64808. /**
  64809. * Visibility of the source mesh
  64810. */
  64811. get: function () {
  64812. return this._sourceMesh.visibility;
  64813. },
  64814. enumerable: true,
  64815. configurable: true
  64816. });
  64817. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  64818. /**
  64819. * Skeleton of the source mesh
  64820. */
  64821. get: function () {
  64822. return this._sourceMesh.skeleton;
  64823. },
  64824. enumerable: true,
  64825. configurable: true
  64826. });
  64827. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  64828. /**
  64829. * Rendering ground id of the source mesh
  64830. */
  64831. get: function () {
  64832. return this._sourceMesh.renderingGroupId;
  64833. },
  64834. set: function (value) {
  64835. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  64836. return;
  64837. }
  64838. //no-op with warning
  64839. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  64840. },
  64841. enumerable: true,
  64842. configurable: true
  64843. });
  64844. /**
  64845. * Returns the total number of vertices (integer).
  64846. */
  64847. InstancedMesh.prototype.getTotalVertices = function () {
  64848. return this._sourceMesh.getTotalVertices();
  64849. };
  64850. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  64851. /**
  64852. * The source mesh of the instance
  64853. */
  64854. get: function () {
  64855. return this._sourceMesh;
  64856. },
  64857. enumerable: true,
  64858. configurable: true
  64859. });
  64860. /**
  64861. * Is this node ready to be used/rendered
  64862. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  64863. * @return {boolean} is it ready
  64864. */
  64865. InstancedMesh.prototype.isReady = function (completeCheck) {
  64866. if (completeCheck === void 0) { completeCheck = false; }
  64867. return this._sourceMesh.isReady(completeCheck, true);
  64868. };
  64869. /**
  64870. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  64871. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  64872. * @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.
  64873. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  64874. */
  64875. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  64876. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  64877. };
  64878. /**
  64879. * Sets the vertex data of the mesh geometry for the requested `kind`.
  64880. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  64881. * The `data` are either a numeric array either a Float32Array.
  64882. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  64883. * 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).
  64884. * Note that a new underlying VertexBuffer object is created each call.
  64885. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  64886. *
  64887. * Possible `kind` values :
  64888. * - BABYLON.VertexBuffer.PositionKind
  64889. * - BABYLON.VertexBuffer.UVKind
  64890. * - BABYLON.VertexBuffer.UV2Kind
  64891. * - BABYLON.VertexBuffer.UV3Kind
  64892. * - BABYLON.VertexBuffer.UV4Kind
  64893. * - BABYLON.VertexBuffer.UV5Kind
  64894. * - BABYLON.VertexBuffer.UV6Kind
  64895. * - BABYLON.VertexBuffer.ColorKind
  64896. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64897. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64898. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64899. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64900. *
  64901. * Returns the Mesh.
  64902. */
  64903. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  64904. if (this.sourceMesh) {
  64905. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  64906. }
  64907. return this.sourceMesh;
  64908. };
  64909. /**
  64910. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  64911. * If the mesh has no geometry, it is simply returned as it is.
  64912. * The `data` are either a numeric array either a Float32Array.
  64913. * No new underlying VertexBuffer object is created.
  64914. * 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.
  64915. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  64916. *
  64917. * Possible `kind` values :
  64918. * - BABYLON.VertexBuffer.PositionKind
  64919. * - BABYLON.VertexBuffer.UVKind
  64920. * - BABYLON.VertexBuffer.UV2Kind
  64921. * - BABYLON.VertexBuffer.UV3Kind
  64922. * - BABYLON.VertexBuffer.UV4Kind
  64923. * - BABYLON.VertexBuffer.UV5Kind
  64924. * - BABYLON.VertexBuffer.UV6Kind
  64925. * - BABYLON.VertexBuffer.ColorKind
  64926. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64927. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64928. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64929. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64930. *
  64931. * Returns the Mesh.
  64932. */
  64933. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  64934. if (this.sourceMesh) {
  64935. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  64936. }
  64937. return this.sourceMesh;
  64938. };
  64939. /**
  64940. * Sets the mesh indices.
  64941. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  64942. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  64943. * This method creates a new index buffer each call.
  64944. * Returns the Mesh.
  64945. */
  64946. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  64947. if (totalVertices === void 0) { totalVertices = null; }
  64948. if (this.sourceMesh) {
  64949. this.sourceMesh.setIndices(indices, totalVertices);
  64950. }
  64951. return this.sourceMesh;
  64952. };
  64953. /**
  64954. * Boolean : True if the mesh owns the requested kind of data.
  64955. */
  64956. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  64957. return this._sourceMesh.isVerticesDataPresent(kind);
  64958. };
  64959. /**
  64960. * Returns an array of indices (IndicesArray).
  64961. */
  64962. InstancedMesh.prototype.getIndices = function () {
  64963. return this._sourceMesh.getIndices();
  64964. };
  64965. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  64966. get: function () {
  64967. return this._sourceMesh._positions;
  64968. },
  64969. enumerable: true,
  64970. configurable: true
  64971. });
  64972. /**
  64973. * Sets a new updated BoundingInfo to the mesh.
  64974. * @returns the mesh.
  64975. */
  64976. InstancedMesh.prototype.refreshBoundingInfo = function () {
  64977. var meshBB = this._sourceMesh.getBoundingInfo();
  64978. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  64979. this._updateBoundingInfo();
  64980. return this;
  64981. };
  64982. /** @hidden */
  64983. InstancedMesh.prototype._preActivate = function () {
  64984. if (this._currentLOD) {
  64985. this._currentLOD._preActivate();
  64986. }
  64987. return this;
  64988. };
  64989. /** @hidden */
  64990. InstancedMesh.prototype._activate = function (renderId) {
  64991. if (this._currentLOD) {
  64992. this._currentLOD._registerInstanceForRenderId(this, renderId);
  64993. }
  64994. return this;
  64995. };
  64996. /**
  64997. * Returns the current associated LOD AbstractMesh.
  64998. */
  64999. InstancedMesh.prototype.getLOD = function (camera) {
  65000. if (!camera) {
  65001. return this;
  65002. }
  65003. var boundingInfo = this.getBoundingInfo();
  65004. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  65005. if (this._currentLOD === this.sourceMesh) {
  65006. return this;
  65007. }
  65008. return this._currentLOD;
  65009. };
  65010. /** @hidden */
  65011. InstancedMesh.prototype._syncSubMeshes = function () {
  65012. this.releaseSubMeshes();
  65013. if (this._sourceMesh.subMeshes) {
  65014. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  65015. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  65016. }
  65017. }
  65018. return this;
  65019. };
  65020. /** @hidden */
  65021. InstancedMesh.prototype._generatePointsArray = function () {
  65022. return this._sourceMesh._generatePointsArray();
  65023. };
  65024. /**
  65025. * Creates a new InstancedMesh from the current mesh.
  65026. * - name (string) : the cloned mesh name
  65027. * - newParent (optional Node) : the optional Node to parent the clone to.
  65028. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  65029. *
  65030. * Returns the clone.
  65031. */
  65032. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65033. var result = this._sourceMesh.createInstance(name);
  65034. // Deep copy
  65035. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  65036. // Bounding info
  65037. this.refreshBoundingInfo();
  65038. // Parent
  65039. if (newParent) {
  65040. result.parent = newParent;
  65041. }
  65042. if (!doNotCloneChildren) {
  65043. // Children
  65044. for (var index = 0; index < this.getScene().meshes.length; index++) {
  65045. var mesh = this.getScene().meshes[index];
  65046. if (mesh.parent === this) {
  65047. mesh.clone(mesh.name, result);
  65048. }
  65049. }
  65050. }
  65051. result.computeWorldMatrix(true);
  65052. return result;
  65053. };
  65054. /**
  65055. * Disposes the InstancedMesh.
  65056. * Returns nothing.
  65057. */
  65058. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  65059. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  65060. // Remove from mesh
  65061. this._sourceMesh.removeInstance(this);
  65062. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  65063. };
  65064. return InstancedMesh;
  65065. }(BABYLON.AbstractMesh));
  65066. BABYLON.InstancedMesh = InstancedMesh;
  65067. })(BABYLON || (BABYLON = {}));
  65068. //# sourceMappingURL=babylon.instancedMesh.js.map
  65069. var BABYLON;
  65070. (function (BABYLON) {
  65071. /**
  65072. * Line mesh
  65073. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  65074. */
  65075. var LinesMesh = /** @class */ (function (_super) {
  65076. __extends(LinesMesh, _super);
  65077. /**
  65078. * Creates a new LinesMesh
  65079. * @param name defines the name
  65080. * @param scene defines the hosting scene
  65081. * @param parent defines the parent mesh if any
  65082. * @param source defines the optional source LinesMesh used to clone data from
  65083. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  65084. * When false, achieved by calling a clone(), also passing False.
  65085. * This will make creation of children, recursive.
  65086. * @param useVertexColor defines if this LinesMesh supports vertex color
  65087. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  65088. */
  65089. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  65090. /**
  65091. * If vertex color should be applied to the mesh
  65092. */
  65093. useVertexColor,
  65094. /**
  65095. * If vertex alpha should be applied to the mesh
  65096. */
  65097. useVertexAlpha) {
  65098. if (scene === void 0) { scene = null; }
  65099. if (parent === void 0) { parent = null; }
  65100. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  65101. _this.useVertexColor = useVertexColor;
  65102. _this.useVertexAlpha = useVertexAlpha;
  65103. /**
  65104. * Color of the line (Default: White)
  65105. */
  65106. _this.color = new BABYLON.Color3(1, 1, 1);
  65107. /**
  65108. * Alpha of the line (Default: 1)
  65109. */
  65110. _this.alpha = 1;
  65111. if (source) {
  65112. _this.color = source.color.clone();
  65113. _this.alpha = source.alpha;
  65114. _this.useVertexColor = source.useVertexColor;
  65115. _this.useVertexAlpha = source.useVertexAlpha;
  65116. }
  65117. _this._intersectionThreshold = 0.1;
  65118. var defines = [];
  65119. var options = {
  65120. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  65121. uniforms: ["world", "viewProjection"],
  65122. needAlphaBlending: true,
  65123. defines: defines
  65124. };
  65125. if (useVertexAlpha === false) {
  65126. options.needAlphaBlending = false;
  65127. }
  65128. if (!useVertexColor) {
  65129. options.uniforms.push("color");
  65130. }
  65131. else {
  65132. options.defines.push("#define VERTEXCOLOR");
  65133. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  65134. }
  65135. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  65136. return _this;
  65137. }
  65138. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  65139. /**
  65140. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65141. * This margin is expressed in world space coordinates, so its value may vary.
  65142. * Default value is 0.1
  65143. * @returns the intersection Threshold value.
  65144. */
  65145. get: function () {
  65146. return this._intersectionThreshold;
  65147. },
  65148. /**
  65149. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65150. * This margin is expressed in world space coordinates, so its value may vary.
  65151. */
  65152. set: function (value) {
  65153. if (this._intersectionThreshold === value) {
  65154. return;
  65155. }
  65156. this._intersectionThreshold = value;
  65157. if (this.geometry) {
  65158. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  65159. }
  65160. },
  65161. enumerable: true,
  65162. configurable: true
  65163. });
  65164. /**
  65165. * Returns the string "LineMesh"
  65166. */
  65167. LinesMesh.prototype.getClassName = function () {
  65168. return "LinesMesh";
  65169. };
  65170. Object.defineProperty(LinesMesh.prototype, "material", {
  65171. /**
  65172. * @hidden
  65173. */
  65174. get: function () {
  65175. return this._colorShader;
  65176. },
  65177. /**
  65178. * @hidden
  65179. */
  65180. set: function (value) {
  65181. // Do nothing
  65182. },
  65183. enumerable: true,
  65184. configurable: true
  65185. });
  65186. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  65187. /**
  65188. * @hidden
  65189. */
  65190. get: function () {
  65191. return false;
  65192. },
  65193. enumerable: true,
  65194. configurable: true
  65195. });
  65196. /** @hidden */
  65197. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  65198. if (!this._geometry) {
  65199. return this;
  65200. }
  65201. // VBOs
  65202. this._geometry._bind(this._colorShader.getEffect());
  65203. // Color
  65204. if (!this.useVertexColor) {
  65205. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  65206. }
  65207. return this;
  65208. };
  65209. /** @hidden */
  65210. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  65211. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  65212. return this;
  65213. }
  65214. var engine = this.getScene().getEngine();
  65215. // Draw order
  65216. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  65217. return this;
  65218. };
  65219. /**
  65220. * Disposes of the line mesh
  65221. * @param doNotRecurse If children should be disposed
  65222. */
  65223. LinesMesh.prototype.dispose = function (doNotRecurse) {
  65224. this._colorShader.dispose(false, false, true);
  65225. _super.prototype.dispose.call(this, doNotRecurse);
  65226. };
  65227. /**
  65228. * Returns a new LineMesh object cloned from the current one.
  65229. */
  65230. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65231. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  65232. };
  65233. return LinesMesh;
  65234. }(BABYLON.Mesh));
  65235. BABYLON.LinesMesh = LinesMesh;
  65236. })(BABYLON || (BABYLON = {}));
  65237. //# sourceMappingURL=babylon.linesMesh.js.map
  65238. var BABYLON;
  65239. (function (BABYLON) {
  65240. /**
  65241. * This class implement a typical dictionary using a string as key and the generic type T as value.
  65242. * The underlying implementation relies on an associative array to ensure the best performances.
  65243. * The value can be anything including 'null' but except 'undefined'
  65244. */
  65245. var StringDictionary = /** @class */ (function () {
  65246. function StringDictionary() {
  65247. this._count = 0;
  65248. this._data = {};
  65249. }
  65250. /**
  65251. * This will clear this dictionary and copy the content from the 'source' one.
  65252. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  65253. * @param source the dictionary to take the content from and copy to this dictionary
  65254. */
  65255. StringDictionary.prototype.copyFrom = function (source) {
  65256. var _this = this;
  65257. this.clear();
  65258. source.forEach(function (t, v) { return _this.add(t, v); });
  65259. };
  65260. /**
  65261. * Get a value based from its key
  65262. * @param key the given key to get the matching value from
  65263. * @return the value if found, otherwise undefined is returned
  65264. */
  65265. StringDictionary.prototype.get = function (key) {
  65266. var val = this._data[key];
  65267. if (val !== undefined) {
  65268. return val;
  65269. }
  65270. return undefined;
  65271. };
  65272. /**
  65273. * Get a value from its key or add it if it doesn't exist.
  65274. * This method will ensure you that a given key/data will be present in the dictionary.
  65275. * @param key the given key to get the matching value from
  65276. * @param factory the factory that will create the value if the key is not present in the dictionary.
  65277. * The factory will only be invoked if there's no data for the given key.
  65278. * @return the value corresponding to the key.
  65279. */
  65280. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  65281. var val = this.get(key);
  65282. if (val !== undefined) {
  65283. return val;
  65284. }
  65285. val = factory(key);
  65286. if (val) {
  65287. this.add(key, val);
  65288. }
  65289. return val;
  65290. };
  65291. /**
  65292. * Get a value from its key if present in the dictionary otherwise add it
  65293. * @param key the key to get the value from
  65294. * @param val if there's no such key/value pair in the dictionary add it with this value
  65295. * @return the value corresponding to the key
  65296. */
  65297. StringDictionary.prototype.getOrAdd = function (key, val) {
  65298. var curVal = this.get(key);
  65299. if (curVal !== undefined) {
  65300. return curVal;
  65301. }
  65302. this.add(key, val);
  65303. return val;
  65304. };
  65305. /**
  65306. * Check if there's a given key in the dictionary
  65307. * @param key the key to check for
  65308. * @return true if the key is present, false otherwise
  65309. */
  65310. StringDictionary.prototype.contains = function (key) {
  65311. return this._data[key] !== undefined;
  65312. };
  65313. /**
  65314. * Add a new key and its corresponding value
  65315. * @param key the key to add
  65316. * @param value the value corresponding to the key
  65317. * @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
  65318. */
  65319. StringDictionary.prototype.add = function (key, value) {
  65320. if (this._data[key] !== undefined) {
  65321. return false;
  65322. }
  65323. this._data[key] = value;
  65324. ++this._count;
  65325. return true;
  65326. };
  65327. /**
  65328. * Update a specific value associated to a key
  65329. * @param key defines the key to use
  65330. * @param value defines the value to store
  65331. * @returns true if the value was updated (or false if the key was not found)
  65332. */
  65333. StringDictionary.prototype.set = function (key, value) {
  65334. if (this._data[key] === undefined) {
  65335. return false;
  65336. }
  65337. this._data[key] = value;
  65338. return true;
  65339. };
  65340. /**
  65341. * Get the element of the given key and remove it from the dictionary
  65342. * @param key defines the key to search
  65343. * @returns the value associated with the key or null if not found
  65344. */
  65345. StringDictionary.prototype.getAndRemove = function (key) {
  65346. var val = this.get(key);
  65347. if (val !== undefined) {
  65348. delete this._data[key];
  65349. --this._count;
  65350. return val;
  65351. }
  65352. return null;
  65353. };
  65354. /**
  65355. * Remove a key/value from the dictionary.
  65356. * @param key the key to remove
  65357. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  65358. */
  65359. StringDictionary.prototype.remove = function (key) {
  65360. if (this.contains(key)) {
  65361. delete this._data[key];
  65362. --this._count;
  65363. return true;
  65364. }
  65365. return false;
  65366. };
  65367. /**
  65368. * Clear the whole content of the dictionary
  65369. */
  65370. StringDictionary.prototype.clear = function () {
  65371. this._data = {};
  65372. this._count = 0;
  65373. };
  65374. Object.defineProperty(StringDictionary.prototype, "count", {
  65375. /**
  65376. * Gets the current count
  65377. */
  65378. get: function () {
  65379. return this._count;
  65380. },
  65381. enumerable: true,
  65382. configurable: true
  65383. });
  65384. /**
  65385. * Execute a callback on each key/val of the dictionary.
  65386. * Note that you can remove any element in this dictionary in the callback implementation
  65387. * @param callback the callback to execute on a given key/value pair
  65388. */
  65389. StringDictionary.prototype.forEach = function (callback) {
  65390. for (var cur in this._data) {
  65391. var val = this._data[cur];
  65392. callback(cur, val);
  65393. }
  65394. };
  65395. /**
  65396. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  65397. * If the callback returns null or undefined the method will iterate to the next key/value pair
  65398. * Note that you can remove any element in this dictionary in the callback implementation
  65399. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  65400. * @returns the first item
  65401. */
  65402. StringDictionary.prototype.first = function (callback) {
  65403. for (var cur in this._data) {
  65404. var val = this._data[cur];
  65405. var res = callback(cur, val);
  65406. if (res) {
  65407. return res;
  65408. }
  65409. }
  65410. return null;
  65411. };
  65412. return StringDictionary;
  65413. }());
  65414. BABYLON.StringDictionary = StringDictionary;
  65415. })(BABYLON || (BABYLON = {}));
  65416. //# sourceMappingURL=babylon.stringDictionary.js.map
  65417. var BABYLON;
  65418. (function (BABYLON) {
  65419. var Debug;
  65420. (function (Debug) {
  65421. /**
  65422. * Class used to render a debug view of a given skeleton
  65423. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  65424. */
  65425. var SkeletonViewer = /** @class */ (function () {
  65426. /**
  65427. * Creates a new SkeletonViewer
  65428. * @param skeleton defines the skeleton to render
  65429. * @param mesh defines the mesh attached to the skeleton
  65430. * @param scene defines the hosting scene
  65431. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  65432. * @param renderingGroupId defines the rendering group id to use with the viewer
  65433. */
  65434. function SkeletonViewer(
  65435. /** defines the skeleton to render */
  65436. skeleton,
  65437. /** defines the mesh attached to the skeleton */
  65438. mesh, scene,
  65439. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  65440. autoUpdateBonesMatrices,
  65441. /** defines the rendering group id to use with the viewer */
  65442. renderingGroupId) {
  65443. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65444. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65445. this.skeleton = skeleton;
  65446. this.mesh = mesh;
  65447. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65448. this.renderingGroupId = renderingGroupId;
  65449. /** Gets or sets the color used to render the skeleton */
  65450. this.color = BABYLON.Color3.White();
  65451. this._debugLines = new Array();
  65452. this._isEnabled = false;
  65453. this._scene = scene;
  65454. this.update();
  65455. this._renderFunction = this.update.bind(this);
  65456. }
  65457. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65458. get: function () {
  65459. return this._isEnabled;
  65460. },
  65461. /** Gets or sets a boolean indicating if the viewer is enabled */
  65462. set: function (value) {
  65463. if (this._isEnabled === value) {
  65464. return;
  65465. }
  65466. this._isEnabled = value;
  65467. if (value) {
  65468. this._scene.registerBeforeRender(this._renderFunction);
  65469. }
  65470. else {
  65471. this._scene.unregisterBeforeRender(this._renderFunction);
  65472. }
  65473. },
  65474. enumerable: true,
  65475. configurable: true
  65476. });
  65477. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65478. if (x === void 0) { x = 0; }
  65479. if (y === void 0) { y = 0; }
  65480. if (z === void 0) { z = 0; }
  65481. var tmat = BABYLON.Tmp.Matrix[0];
  65482. var parentBone = bone.getParent();
  65483. tmat.copyFrom(bone.getLocalMatrix());
  65484. if (x !== 0 || y !== 0 || z !== 0) {
  65485. var tmat2 = BABYLON.Tmp.Matrix[1];
  65486. BABYLON.Matrix.IdentityToRef(tmat2);
  65487. tmat2.m[12] = x;
  65488. tmat2.m[13] = y;
  65489. tmat2.m[14] = z;
  65490. tmat2.multiplyToRef(tmat, tmat);
  65491. }
  65492. if (parentBone) {
  65493. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65494. }
  65495. tmat.multiplyToRef(meshMat, tmat);
  65496. position.x = tmat.m[12];
  65497. position.y = tmat.m[13];
  65498. position.z = tmat.m[14];
  65499. };
  65500. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65501. var len = bones.length;
  65502. var meshPos = this.mesh.position;
  65503. for (var i = 0; i < len; i++) {
  65504. var bone = bones[i];
  65505. var points = this._debugLines[i];
  65506. if (!points) {
  65507. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65508. this._debugLines[i] = points;
  65509. }
  65510. this._getBonePosition(points[0], bone, meshMat);
  65511. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65512. points[0].subtractInPlace(meshPos);
  65513. points[1].subtractInPlace(meshPos);
  65514. }
  65515. };
  65516. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65517. var len = bones.length;
  65518. var boneNum = 0;
  65519. var meshPos = this.mesh.position;
  65520. for (var i = len - 1; i >= 0; i--) {
  65521. var childBone = bones[i];
  65522. var parentBone = childBone.getParent();
  65523. if (!parentBone) {
  65524. continue;
  65525. }
  65526. var points = this._debugLines[boneNum];
  65527. if (!points) {
  65528. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65529. this._debugLines[boneNum] = points;
  65530. }
  65531. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65532. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65533. points[0].subtractInPlace(meshPos);
  65534. points[1].subtractInPlace(meshPos);
  65535. boneNum++;
  65536. }
  65537. };
  65538. /** Update the viewer to sync with current skeleton state */
  65539. SkeletonViewer.prototype.update = function () {
  65540. if (this.autoUpdateBonesMatrices) {
  65541. this.skeleton.computeAbsoluteTransforms();
  65542. }
  65543. if (this.skeleton.bones[0].length === undefined) {
  65544. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65545. }
  65546. else {
  65547. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65548. }
  65549. if (!this._debugMesh) {
  65550. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  65551. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65552. }
  65553. else {
  65554. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  65555. }
  65556. this._debugMesh.position.copyFrom(this.mesh.position);
  65557. this._debugMesh.color = this.color;
  65558. };
  65559. /** Release associated resources */
  65560. SkeletonViewer.prototype.dispose = function () {
  65561. if (this._debugMesh) {
  65562. this.isEnabled = false;
  65563. this._debugMesh.dispose();
  65564. this._debugMesh = null;
  65565. }
  65566. };
  65567. return SkeletonViewer;
  65568. }());
  65569. Debug.SkeletonViewer = SkeletonViewer;
  65570. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65571. })(BABYLON || (BABYLON = {}));
  65572. //# sourceMappingURL=babylon.skeletonViewer.js.map
  65573. /**
  65574. * Module Debug contains the (visual) components to debug a scene correctly
  65575. */
  65576. var BABYLON;
  65577. (function (BABYLON) {
  65578. var Debug;
  65579. (function (Debug) {
  65580. /**
  65581. * The Axes viewer will show 3 axes in a specific point in space
  65582. */
  65583. var AxesViewer = /** @class */ (function () {
  65584. /**
  65585. * Creates a new AxesViewer
  65586. * @param scene defines the hosting scene
  65587. * @param scaleLines defines a number used to scale line length (1 by default)
  65588. */
  65589. function AxesViewer(scene, scaleLines) {
  65590. if (scaleLines === void 0) { scaleLines = 1; }
  65591. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65592. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65593. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65594. /**
  65595. * Gets or sets a number used to scale line length
  65596. */
  65597. this.scaleLines = 1;
  65598. this.scaleLines = scaleLines;
  65599. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  65600. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  65601. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  65602. this._xmesh.renderingGroupId = 2;
  65603. this._ymesh.renderingGroupId = 2;
  65604. this._zmesh.renderingGroupId = 2;
  65605. this._xmesh.material.checkReadyOnlyOnce = true;
  65606. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  65607. this._ymesh.material.checkReadyOnlyOnce = true;
  65608. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  65609. this._zmesh.material.checkReadyOnlyOnce = true;
  65610. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  65611. this.scene = scene;
  65612. }
  65613. /**
  65614. * Force the viewer to update
  65615. * @param position defines the position of the viewer
  65616. * @param xaxis defines the x axis of the viewer
  65617. * @param yaxis defines the y axis of the viewer
  65618. * @param zaxis defines the z axis of the viewer
  65619. */
  65620. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  65621. var scaleLines = this.scaleLines;
  65622. if (this._xmesh) {
  65623. this._xmesh.position.copyFrom(position);
  65624. }
  65625. if (this._ymesh) {
  65626. this._ymesh.position.copyFrom(position);
  65627. }
  65628. if (this._zmesh) {
  65629. this._zmesh.position.copyFrom(position);
  65630. }
  65631. var point2 = this._xline[1];
  65632. point2.x = xaxis.x * scaleLines;
  65633. point2.y = xaxis.y * scaleLines;
  65634. point2.z = xaxis.z * scaleLines;
  65635. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  65636. point2 = this._yline[1];
  65637. point2.x = yaxis.x * scaleLines;
  65638. point2.y = yaxis.y * scaleLines;
  65639. point2.z = yaxis.z * scaleLines;
  65640. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  65641. point2 = this._zline[1];
  65642. point2.x = zaxis.x * scaleLines;
  65643. point2.y = zaxis.y * scaleLines;
  65644. point2.z = zaxis.z * scaleLines;
  65645. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  65646. };
  65647. /** Releases resources */
  65648. AxesViewer.prototype.dispose = function () {
  65649. if (this._xmesh) {
  65650. this._xmesh.dispose();
  65651. }
  65652. if (this._ymesh) {
  65653. this._ymesh.dispose();
  65654. }
  65655. if (this._zmesh) {
  65656. this._zmesh.dispose();
  65657. }
  65658. this._xmesh = null;
  65659. this._ymesh = null;
  65660. this._zmesh = null;
  65661. this.scene = null;
  65662. };
  65663. return AxesViewer;
  65664. }());
  65665. Debug.AxesViewer = AxesViewer;
  65666. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65667. })(BABYLON || (BABYLON = {}));
  65668. //# sourceMappingURL=babylon.axesViewer.js.map
  65669. var BABYLON;
  65670. (function (BABYLON) {
  65671. var Debug;
  65672. (function (Debug) {
  65673. /**
  65674. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  65675. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  65676. */
  65677. var BoneAxesViewer = /** @class */ (function (_super) {
  65678. __extends(BoneAxesViewer, _super);
  65679. /**
  65680. * Creates a new BoneAxesViewer
  65681. * @param scene defines the hosting scene
  65682. * @param bone defines the target bone
  65683. * @param mesh defines the target mesh
  65684. * @param scaleLines defines a scaling factor for line length (1 by default)
  65685. */
  65686. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  65687. if (scaleLines === void 0) { scaleLines = 1; }
  65688. var _this = _super.call(this, scene, scaleLines) || this;
  65689. /** Gets current position */
  65690. _this.pos = BABYLON.Vector3.Zero();
  65691. /** Gets direction of X axis */
  65692. _this.xaxis = BABYLON.Vector3.Zero();
  65693. /** Gets direction of Y axis */
  65694. _this.yaxis = BABYLON.Vector3.Zero();
  65695. /** Gets direction of Z axis */
  65696. _this.zaxis = BABYLON.Vector3.Zero();
  65697. _this.mesh = mesh;
  65698. _this.bone = bone;
  65699. return _this;
  65700. }
  65701. /**
  65702. * Force the viewer to update
  65703. */
  65704. BoneAxesViewer.prototype.update = function () {
  65705. if (!this.mesh || !this.bone) {
  65706. return;
  65707. }
  65708. var bone = this.bone;
  65709. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  65710. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  65711. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  65712. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  65713. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  65714. };
  65715. /** Releases resources */
  65716. BoneAxesViewer.prototype.dispose = function () {
  65717. if (this.mesh) {
  65718. this.mesh = null;
  65719. this.bone = null;
  65720. _super.prototype.dispose.call(this);
  65721. }
  65722. };
  65723. return BoneAxesViewer;
  65724. }(Debug.AxesViewer));
  65725. Debug.BoneAxesViewer = BoneAxesViewer;
  65726. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65727. })(BABYLON || (BABYLON = {}));
  65728. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  65729. var BABYLON;
  65730. (function (BABYLON) {
  65731. /**
  65732. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65733. * in order to better appreciate the issue one might have.
  65734. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65735. */
  65736. var RayHelper = /** @class */ (function () {
  65737. /**
  65738. * Instantiate a new ray helper.
  65739. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65740. * in order to better appreciate the issue one might have.
  65741. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65742. * @param ray Defines the ray we are currently tryin to visualize
  65743. */
  65744. function RayHelper(ray) {
  65745. this.ray = ray;
  65746. }
  65747. /**
  65748. * Helper function to create a colored helper in a scene in one line.
  65749. * @param ray Defines the ray we are currently tryin to visualize
  65750. * @param scene Defines the scene the ray is used in
  65751. * @param color Defines the color we want to see the ray in
  65752. * @returns The newly created ray helper.
  65753. */
  65754. RayHelper.CreateAndShow = function (ray, scene, color) {
  65755. var helper = new RayHelper(ray);
  65756. helper.show(scene, color);
  65757. return helper;
  65758. };
  65759. /**
  65760. * Shows the ray we are willing to debug.
  65761. * @param scene Defines the scene the ray needs to be rendered in
  65762. * @param color Defines the color the ray needs to be rendered in
  65763. */
  65764. RayHelper.prototype.show = function (scene, color) {
  65765. if (!this._renderFunction && this.ray) {
  65766. var ray = this.ray;
  65767. this._renderFunction = this._render.bind(this);
  65768. this._scene = scene;
  65769. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  65770. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  65771. if (this._renderFunction) {
  65772. this._scene.registerBeforeRender(this._renderFunction);
  65773. }
  65774. }
  65775. if (color && this._renderLine) {
  65776. this._renderLine.color.copyFrom(color);
  65777. }
  65778. };
  65779. /**
  65780. * Hides the ray we are debugging.
  65781. */
  65782. RayHelper.prototype.hide = function () {
  65783. if (this._renderFunction && this._scene) {
  65784. this._scene.unregisterBeforeRender(this._renderFunction);
  65785. this._scene = null;
  65786. this._renderFunction = null;
  65787. if (this._renderLine) {
  65788. this._renderLine.dispose();
  65789. this._renderLine = null;
  65790. }
  65791. this._renderPoints = [];
  65792. }
  65793. };
  65794. RayHelper.prototype._render = function () {
  65795. var ray = this.ray;
  65796. if (!ray) {
  65797. return;
  65798. }
  65799. var point = this._renderPoints[1];
  65800. var len = Math.min(ray.length, 1000000);
  65801. point.copyFrom(ray.direction);
  65802. point.scaleInPlace(len);
  65803. point.addInPlace(ray.origin);
  65804. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  65805. };
  65806. /**
  65807. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  65808. * @param mesh Defines the mesh we want the helper attached to
  65809. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  65810. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  65811. * @param length Defines the length of the ray
  65812. */
  65813. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  65814. this._attachedToMesh = mesh;
  65815. var ray = this.ray;
  65816. if (!ray) {
  65817. return;
  65818. }
  65819. if (!ray.direction) {
  65820. ray.direction = BABYLON.Vector3.Zero();
  65821. }
  65822. if (!ray.origin) {
  65823. ray.origin = BABYLON.Vector3.Zero();
  65824. }
  65825. if (length) {
  65826. ray.length = length;
  65827. }
  65828. if (!meshSpaceOrigin) {
  65829. meshSpaceOrigin = BABYLON.Vector3.Zero();
  65830. }
  65831. if (!meshSpaceDirection) {
  65832. // -1 so that this will work with Mesh.lookAt
  65833. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  65834. }
  65835. if (!this._meshSpaceDirection) {
  65836. this._meshSpaceDirection = meshSpaceDirection.clone();
  65837. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  65838. }
  65839. else {
  65840. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  65841. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  65842. }
  65843. if (!this._updateToMeshFunction) {
  65844. this._updateToMeshFunction = this._updateToMesh.bind(this);
  65845. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  65846. }
  65847. this._updateToMesh();
  65848. };
  65849. /**
  65850. * Detach the ray helper from the mesh it has previously been attached to.
  65851. */
  65852. RayHelper.prototype.detachFromMesh = function () {
  65853. if (this._attachedToMesh) {
  65854. if (this._updateToMeshFunction) {
  65855. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  65856. }
  65857. this._attachedToMesh = null;
  65858. this._updateToMeshFunction = null;
  65859. }
  65860. };
  65861. RayHelper.prototype._updateToMesh = function () {
  65862. var ray = this.ray;
  65863. if (!this._attachedToMesh || !ray) {
  65864. return;
  65865. }
  65866. if (this._attachedToMesh._isDisposed) {
  65867. this.detachFromMesh();
  65868. return;
  65869. }
  65870. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  65871. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  65872. };
  65873. /**
  65874. * Dispose the helper and release its associated resources.
  65875. */
  65876. RayHelper.prototype.dispose = function () {
  65877. this.hide();
  65878. this.detachFromMesh();
  65879. this.ray = null;
  65880. };
  65881. return RayHelper;
  65882. }());
  65883. BABYLON.RayHelper = RayHelper;
  65884. })(BABYLON || (BABYLON = {}));
  65885. //# sourceMappingURL=babylon.rayHelper.js.map
  65886. var BABYLON;
  65887. (function (BABYLON) {
  65888. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  65889. get: function () {
  65890. if (!this._debugLayer) {
  65891. this._debugLayer = new DebugLayer(this);
  65892. }
  65893. return this._debugLayer;
  65894. },
  65895. enumerable: true,
  65896. configurable: true
  65897. });
  65898. /**
  65899. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65900. * what is happening in your scene
  65901. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65902. */
  65903. var DebugLayer = /** @class */ (function () {
  65904. /**
  65905. * Instantiates a new debug layer.
  65906. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65907. * what is happening in your scene
  65908. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65909. * @param scene Defines the scene to inspect
  65910. */
  65911. function DebugLayer(scene) {
  65912. var _this = this;
  65913. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65914. /**
  65915. * Observable triggered when a property is changed through the inspector.
  65916. */
  65917. this.onPropertyChangedObservable = new BABYLON.Observable();
  65918. this._scene = scene;
  65919. this._scene.onDisposeObservable.add(function () {
  65920. // Debug layer
  65921. if (_this._scene._debugLayer) {
  65922. _this._scene._debugLayer.hide();
  65923. }
  65924. });
  65925. }
  65926. /** Creates the inspector window. */
  65927. DebugLayer.prototype._createInspector = function (config) {
  65928. if (config === void 0) { config = {}; }
  65929. var popup = config.popup || false;
  65930. var initialTab = config.initialTab || 0;
  65931. var parentElement = config.parentElement || null;
  65932. if (!this._inspector) {
  65933. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  65934. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  65935. } // else nothing to do as instance is already created
  65936. };
  65937. /**
  65938. * Get if the inspector is visible or not.
  65939. * @returns true if visible otherwise, false
  65940. */
  65941. DebugLayer.prototype.isVisible = function () {
  65942. if (!this._inspector) {
  65943. return false;
  65944. }
  65945. return true;
  65946. };
  65947. /**
  65948. * Hide the inspector and close its window.
  65949. */
  65950. DebugLayer.prototype.hide = function () {
  65951. if (this._inspector) {
  65952. try {
  65953. this._inspector.dispose();
  65954. }
  65955. catch (e) {
  65956. // If the inspector has been removed directly from the inspector tool
  65957. }
  65958. this.onPropertyChangedObservable.clear();
  65959. this._inspector = null;
  65960. }
  65961. };
  65962. /**
  65963. *
  65964. * Launch the debugLayer.
  65965. *
  65966. * initialTab:
  65967. * | Value | Tab Name |
  65968. * | --- | --- |
  65969. * | 0 | Scene |
  65970. * | 1 | Console |
  65971. * | 2 | Stats |
  65972. * | 3 | Textures |
  65973. * | 4 | Mesh |
  65974. * | 5 | Light |
  65975. * | 6 | Material |
  65976. * | 7 | GLTF |
  65977. * | 8 | GUI |
  65978. * | 9 | Physics |
  65979. * | 10 | Camera |
  65980. * | 11 | Audio |
  65981. *
  65982. * @param config Define the configuration of the inspector
  65983. */
  65984. DebugLayer.prototype.show = function (config) {
  65985. if (config === void 0) { config = {}; }
  65986. if (typeof this.BJSINSPECTOR == 'undefined') {
  65987. // Load inspector and add it to the DOM
  65988. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  65989. }
  65990. else {
  65991. // Otherwise creates the inspector
  65992. this._createInspector(config);
  65993. }
  65994. };
  65995. /**
  65996. * Gets the active tab
  65997. * @return the index of the active tab or -1 if the inspector is hidden
  65998. */
  65999. DebugLayer.prototype.getActiveTab = function () {
  66000. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  66001. };
  66002. /**
  66003. * Define the url to get the inspector script from.
  66004. * By default it uses the babylonjs CDN.
  66005. * @ignoreNaming
  66006. */
  66007. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66008. return DebugLayer;
  66009. }());
  66010. BABYLON.DebugLayer = DebugLayer;
  66011. })(BABYLON || (BABYLON = {}));
  66012. //# sourceMappingURL=babylon.debugLayer.js.map
  66013. var BABYLON;
  66014. (function (BABYLON) {
  66015. var Debug;
  66016. (function (Debug) {
  66017. /**
  66018. * Used to show the physics impostor around the specific mesh
  66019. */
  66020. var PhysicsViewer = /** @class */ (function () {
  66021. /**
  66022. * Creates a new PhysicsViewer
  66023. * @param scene defines the hosting scene
  66024. */
  66025. function PhysicsViewer(scene) {
  66026. /** @hidden */
  66027. this._impostors = [];
  66028. /** @hidden */
  66029. this._meshes = [];
  66030. /** @hidden */
  66031. this._numMeshes = 0;
  66032. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66033. var physicEngine = this._scene.getPhysicsEngine();
  66034. if (physicEngine) {
  66035. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  66036. }
  66037. }
  66038. /** @hidden */
  66039. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66040. var plugin = this._physicsEnginePlugin;
  66041. for (var i = 0; i < this._numMeshes; i++) {
  66042. var impostor = this._impostors[i];
  66043. if (!impostor) {
  66044. continue;
  66045. }
  66046. if (impostor.isDisposed) {
  66047. this.hideImpostor(this._impostors[i--]);
  66048. }
  66049. else {
  66050. var mesh = this._meshes[i];
  66051. if (mesh && plugin) {
  66052. plugin.syncMeshWithImpostor(mesh, impostor);
  66053. }
  66054. }
  66055. }
  66056. };
  66057. /**
  66058. * Renders a specified physic impostor
  66059. * @param impostor defines the impostor to render
  66060. */
  66061. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66062. if (!this._scene) {
  66063. return;
  66064. }
  66065. for (var i = 0; i < this._numMeshes; i++) {
  66066. if (this._impostors[i] == impostor) {
  66067. return;
  66068. }
  66069. }
  66070. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66071. if (debugMesh) {
  66072. this._impostors[this._numMeshes] = impostor;
  66073. this._meshes[this._numMeshes] = debugMesh;
  66074. if (this._numMeshes === 0) {
  66075. this._renderFunction = this._updateDebugMeshes.bind(this);
  66076. this._scene.registerBeforeRender(this._renderFunction);
  66077. }
  66078. this._numMeshes++;
  66079. }
  66080. };
  66081. /**
  66082. * Hides a specified physic impostor
  66083. * @param impostor defines the impostor to hide
  66084. */
  66085. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66086. if (!impostor || !this._scene) {
  66087. return;
  66088. }
  66089. var removed = false;
  66090. for (var i = 0; i < this._numMeshes; i++) {
  66091. if (this._impostors[i] == impostor) {
  66092. var mesh = this._meshes[i];
  66093. if (!mesh) {
  66094. continue;
  66095. }
  66096. this._scene.removeMesh(mesh);
  66097. mesh.dispose();
  66098. this._numMeshes--;
  66099. if (this._numMeshes > 0) {
  66100. this._meshes[i] = this._meshes[this._numMeshes];
  66101. this._impostors[i] = this._impostors[this._numMeshes];
  66102. this._meshes[this._numMeshes] = null;
  66103. this._impostors[this._numMeshes] = null;
  66104. }
  66105. else {
  66106. this._meshes[0] = null;
  66107. this._impostors[0] = null;
  66108. }
  66109. removed = true;
  66110. break;
  66111. }
  66112. }
  66113. if (removed && this._numMeshes === 0) {
  66114. this._scene.unregisterBeforeRender(this._renderFunction);
  66115. }
  66116. };
  66117. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66118. if (!this._debugMaterial) {
  66119. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66120. this._debugMaterial.wireframe = true;
  66121. }
  66122. return this._debugMaterial;
  66123. };
  66124. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66125. if (!this._debugBoxMesh) {
  66126. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66127. this._debugBoxMesh.renderingGroupId = 1;
  66128. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66129. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66130. scene.removeMesh(this._debugBoxMesh);
  66131. }
  66132. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66133. };
  66134. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66135. if (!this._debugSphereMesh) {
  66136. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66137. this._debugSphereMesh.renderingGroupId = 1;
  66138. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66139. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66140. scene.removeMesh(this._debugSphereMesh);
  66141. }
  66142. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66143. };
  66144. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66145. var mesh = null;
  66146. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66147. mesh = this._getDebugBoxMesh(scene);
  66148. impostor.getBoxSizeToRef(mesh.scaling);
  66149. }
  66150. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66151. mesh = this._getDebugSphereMesh(scene);
  66152. var radius = impostor.getRadius();
  66153. mesh.scaling.x = radius * 2;
  66154. mesh.scaling.y = radius * 2;
  66155. mesh.scaling.z = radius * 2;
  66156. }
  66157. return mesh;
  66158. };
  66159. /** Releases all resources */
  66160. PhysicsViewer.prototype.dispose = function () {
  66161. for (var i = 0; i < this._numMeshes; i++) {
  66162. this.hideImpostor(this._impostors[i]);
  66163. }
  66164. if (this._debugBoxMesh) {
  66165. this._debugBoxMesh.dispose();
  66166. }
  66167. if (this._debugSphereMesh) {
  66168. this._debugSphereMesh.dispose();
  66169. }
  66170. if (this._debugMaterial) {
  66171. this._debugMaterial.dispose();
  66172. }
  66173. this._impostors.length = 0;
  66174. this._scene = null;
  66175. this._physicsEnginePlugin = null;
  66176. };
  66177. return PhysicsViewer;
  66178. }());
  66179. Debug.PhysicsViewer = PhysicsViewer;
  66180. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66181. })(BABYLON || (BABYLON = {}));
  66182. //# sourceMappingURL=babylon.physicsViewer.js.map
  66183. var BABYLON;
  66184. (function (BABYLON) {
  66185. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  66186. get: function () {
  66187. return this._forceShowBoundingBoxes || false;
  66188. },
  66189. set: function (value) {
  66190. this._forceShowBoundingBoxes = value;
  66191. // Lazyly creates a BB renderer if needed.
  66192. if (value) {
  66193. this.getBoundingBoxRenderer();
  66194. }
  66195. },
  66196. enumerable: true,
  66197. configurable: true
  66198. });
  66199. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  66200. if (!this._boundingBoxRenderer) {
  66201. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  66202. }
  66203. return this._boundingBoxRenderer;
  66204. };
  66205. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  66206. get: function () {
  66207. return this._showBoundingBox || false;
  66208. },
  66209. set: function (value) {
  66210. this._showBoundingBox = value;
  66211. // Lazyly creates a BB renderer if needed.
  66212. if (value) {
  66213. this.getScene().getBoundingBoxRenderer();
  66214. }
  66215. },
  66216. enumerable: true,
  66217. configurable: true
  66218. });
  66219. /**
  66220. * Component responsible of rendering the bounding box of the meshes in a scene.
  66221. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  66222. */
  66223. var BoundingBoxRenderer = /** @class */ (function () {
  66224. /**
  66225. * Instantiates a new bounding box renderer in a scene.
  66226. * @param scene the scene the renderer renders in
  66227. */
  66228. function BoundingBoxRenderer(scene) {
  66229. /**
  66230. * The component name helpfull to identify the component in the list of scene components.
  66231. */
  66232. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  66233. /**
  66234. * Color of the bounding box lines placed in front of an object
  66235. */
  66236. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66237. /**
  66238. * Color of the bounding box lines placed behind an object
  66239. */
  66240. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66241. /**
  66242. * Defines if the renderer should show the back lines or not
  66243. */
  66244. this.showBackLines = true;
  66245. /**
  66246. * @hidden
  66247. */
  66248. this.renderList = new BABYLON.SmartArray(32);
  66249. this._vertexBuffers = {};
  66250. this.scene = scene;
  66251. scene._addComponent(this);
  66252. }
  66253. /**
  66254. * Registers the component in a given scene
  66255. */
  66256. BoundingBoxRenderer.prototype.register = function () {
  66257. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  66258. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  66259. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  66260. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  66261. };
  66262. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  66263. if (mesh.showSubMeshesBoundingBox) {
  66264. var boundingInfo = subMesh.getBoundingInfo();
  66265. if (boundingInfo !== null && boundingInfo !== undefined) {
  66266. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66267. this.renderList.push(boundingInfo.boundingBox);
  66268. }
  66269. }
  66270. };
  66271. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  66272. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  66273. var boundingInfo = sourceMesh.getBoundingInfo();
  66274. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66275. this.renderList.push(boundingInfo.boundingBox);
  66276. }
  66277. };
  66278. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66279. if (this._colorShader) {
  66280. return;
  66281. }
  66282. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  66283. attributes: [BABYLON.VertexBuffer.PositionKind],
  66284. uniforms: ["world", "viewProjection", "color"]
  66285. });
  66286. var engine = this.scene.getEngine();
  66287. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66288. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66289. this._createIndexBuffer();
  66290. };
  66291. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66292. var engine = this.scene.getEngine();
  66293. 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]);
  66294. };
  66295. /**
  66296. * Rebuilds the elements related to this component in case of
  66297. * context lost for instance.
  66298. */
  66299. BoundingBoxRenderer.prototype.rebuild = function () {
  66300. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66301. if (vb) {
  66302. vb._rebuild();
  66303. }
  66304. this._createIndexBuffer();
  66305. };
  66306. /**
  66307. * @hidden
  66308. */
  66309. BoundingBoxRenderer.prototype.reset = function () {
  66310. this.renderList.reset();
  66311. };
  66312. /**
  66313. * Render the bounding boxes of a specific rendering group
  66314. * @param renderingGroupId defines the rendering group to render
  66315. */
  66316. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  66317. if (this.renderList.length === 0) {
  66318. return;
  66319. }
  66320. this._prepareRessources();
  66321. if (!this._colorShader.isReady()) {
  66322. return;
  66323. }
  66324. var engine = this.scene.getEngine();
  66325. engine.setDepthWrite(false);
  66326. this._colorShader._preBind();
  66327. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66328. var boundingBox = this.renderList.data[boundingBoxIndex];
  66329. if (boundingBox._tag !== renderingGroupId) {
  66330. continue;
  66331. }
  66332. var min = boundingBox.minimum;
  66333. var max = boundingBox.maximum;
  66334. var diff = max.subtract(min);
  66335. var median = min.add(diff.scale(0.5));
  66336. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66337. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66338. .multiply(boundingBox.getWorldMatrix());
  66339. // VBOs
  66340. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66341. if (this.showBackLines) {
  66342. // Back
  66343. engine.setDepthFunctionToGreaterOrEqual();
  66344. this.scene.resetCachedMaterial();
  66345. this._colorShader.setColor4("color", this.backColor.toColor4());
  66346. this._colorShader.bind(worldMatrix);
  66347. // Draw order
  66348. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66349. }
  66350. // Front
  66351. engine.setDepthFunctionToLess();
  66352. this.scene.resetCachedMaterial();
  66353. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66354. this._colorShader.bind(worldMatrix);
  66355. // Draw order
  66356. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66357. }
  66358. this._colorShader.unbind();
  66359. engine.setDepthFunctionToLessOrEqual();
  66360. engine.setDepthWrite(true);
  66361. };
  66362. /**
  66363. * In case of occlusion queries, we can render the occlusion bounding box through this method
  66364. * @param mesh Define the mesh to render the occlusion bounding box for
  66365. */
  66366. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66367. this._prepareRessources();
  66368. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  66369. return;
  66370. }
  66371. var engine = this.scene.getEngine();
  66372. engine.setDepthWrite(false);
  66373. engine.setColorWrite(false);
  66374. this._colorShader._preBind();
  66375. var boundingBox = mesh._boundingInfo.boundingBox;
  66376. var min = boundingBox.minimum;
  66377. var max = boundingBox.maximum;
  66378. var diff = max.subtract(min);
  66379. var median = min.add(diff.scale(0.5));
  66380. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66381. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66382. .multiply(boundingBox.getWorldMatrix());
  66383. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66384. engine.setDepthFunctionToLess();
  66385. this.scene.resetCachedMaterial();
  66386. this._colorShader.bind(worldMatrix);
  66387. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66388. this._colorShader.unbind();
  66389. engine.setDepthFunctionToLessOrEqual();
  66390. engine.setDepthWrite(true);
  66391. engine.setColorWrite(true);
  66392. };
  66393. /**
  66394. * Dispose and release the resources attached to this renderer.
  66395. */
  66396. BoundingBoxRenderer.prototype.dispose = function () {
  66397. if (!this._colorShader) {
  66398. return;
  66399. }
  66400. this.renderList.dispose();
  66401. this._colorShader.dispose();
  66402. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66403. if (buffer) {
  66404. buffer.dispose();
  66405. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66406. }
  66407. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  66408. };
  66409. return BoundingBoxRenderer;
  66410. }());
  66411. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66412. })(BABYLON || (BABYLON = {}));
  66413. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66414. var BABYLON;
  66415. (function (BABYLON) {
  66416. BABYLON.Engine.prototype.createTransformFeedback = function () {
  66417. return this._gl.createTransformFeedback();
  66418. };
  66419. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  66420. this._gl.deleteTransformFeedback(value);
  66421. };
  66422. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  66423. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  66424. };
  66425. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  66426. if (usePoints === void 0) { usePoints = true; }
  66427. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  66428. };
  66429. BABYLON.Engine.prototype.endTransformFeedback = function () {
  66430. this._gl.endTransformFeedback();
  66431. };
  66432. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  66433. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  66434. };
  66435. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  66436. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  66437. };
  66438. })(BABYLON || (BABYLON = {}));
  66439. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  66440. var BABYLON;
  66441. (function (BABYLON) {
  66442. /**
  66443. * This represents a GPU particle system in Babylon
  66444. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  66445. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  66446. */
  66447. var GPUParticleSystem = /** @class */ (function (_super) {
  66448. __extends(GPUParticleSystem, _super);
  66449. /**
  66450. * Instantiates a GPU particle system.
  66451. * 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.
  66452. * @param name The name of the particle system
  66453. * @param options The options used to create the system
  66454. * @param scene The scene the particle system belongs to
  66455. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  66456. */
  66457. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  66458. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  66459. var _this = _super.call(this, name) || this;
  66460. /**
  66461. * The layer mask we are rendering the particles through.
  66462. */
  66463. _this.layerMask = 0x0FFFFFFF;
  66464. _this._accumulatedCount = 0;
  66465. _this._targetIndex = 0;
  66466. _this._currentRenderId = -1;
  66467. _this._started = false;
  66468. _this._stopped = false;
  66469. _this._timeDelta = 0;
  66470. _this._attributesStrideSize = 21;
  66471. _this._actualFrame = 0;
  66472. _this._rawTextureWidth = 256;
  66473. /**
  66474. * An event triggered when the system is disposed.
  66475. */
  66476. _this.onDisposeObservable = new BABYLON.Observable();
  66477. /**
  66478. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  66479. * to override the particles.
  66480. */
  66481. _this.forceDepthWrite = false;
  66482. _this._preWarmDone = false;
  66483. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66484. // Setup the default processing configuration to the scene.
  66485. _this._attachImageProcessingConfiguration(null);
  66486. _this._engine = _this._scene.getEngine();
  66487. if (!options.randomTextureSize) {
  66488. delete options.randomTextureSize;
  66489. }
  66490. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  66491. var optionsAsNumber = options;
  66492. if (isFinite(optionsAsNumber)) {
  66493. fullOptions.capacity = optionsAsNumber;
  66494. }
  66495. _this._capacity = fullOptions.capacity;
  66496. _this._activeCount = fullOptions.capacity;
  66497. _this._currentActiveCount = 0;
  66498. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  66499. _this._scene.particleSystems.push(_this);
  66500. _this._updateEffectOptions = {
  66501. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  66502. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  66503. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  66504. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  66505. uniformBuffersNames: [],
  66506. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  66507. defines: "",
  66508. fallbacks: null,
  66509. onCompiled: null,
  66510. onError: null,
  66511. indexParameters: null,
  66512. maxSimultaneousLights: 0,
  66513. transformFeedbackVaryings: []
  66514. };
  66515. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  66516. // Random data
  66517. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  66518. var d = [];
  66519. for (var i = 0; i < maxTextureSize; ++i) {
  66520. d.push(Math.random());
  66521. d.push(Math.random());
  66522. d.push(Math.random());
  66523. d.push(Math.random());
  66524. }
  66525. _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);
  66526. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66527. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66528. d = [];
  66529. for (var i = 0; i < maxTextureSize; ++i) {
  66530. d.push(Math.random());
  66531. d.push(Math.random());
  66532. d.push(Math.random());
  66533. d.push(Math.random());
  66534. }
  66535. _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);
  66536. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66537. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66538. _this._randomTextureSize = maxTextureSize;
  66539. return _this;
  66540. }
  66541. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  66542. /**
  66543. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  66544. */
  66545. get: function () {
  66546. if (!BABYLON.Engine.LastCreatedEngine) {
  66547. return false;
  66548. }
  66549. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  66550. },
  66551. enumerable: true,
  66552. configurable: true
  66553. });
  66554. /**
  66555. * Gets the maximum number of particles active at the same time.
  66556. * @returns The max number of active particles.
  66557. */
  66558. GPUParticleSystem.prototype.getCapacity = function () {
  66559. return this._capacity;
  66560. };
  66561. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  66562. /**
  66563. * Gets or set the number of active particles
  66564. */
  66565. get: function () {
  66566. return this._activeCount;
  66567. },
  66568. set: function (value) {
  66569. this._activeCount = Math.min(value, this._capacity);
  66570. },
  66571. enumerable: true,
  66572. configurable: true
  66573. });
  66574. /**
  66575. * Is this system ready to be used/rendered
  66576. * @return true if the system is ready
  66577. */
  66578. GPUParticleSystem.prototype.isReady = function () {
  66579. if (!this._updateEffect) {
  66580. this._recreateUpdateEffect();
  66581. this._recreateRenderEffect();
  66582. return false;
  66583. }
  66584. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  66585. return false;
  66586. }
  66587. return true;
  66588. };
  66589. /**
  66590. * Gets if the system has been started. (Note: this will still be true after stop is called)
  66591. * @returns True if it has been started, otherwise false.
  66592. */
  66593. GPUParticleSystem.prototype.isStarted = function () {
  66594. return this._started;
  66595. };
  66596. /**
  66597. * Starts the particle system and begins to emit
  66598. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  66599. */
  66600. GPUParticleSystem.prototype.start = function (delay) {
  66601. var _this = this;
  66602. if (delay === void 0) { delay = this.startDelay; }
  66603. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  66604. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  66605. }
  66606. if (delay) {
  66607. setTimeout(function () {
  66608. _this.start(0);
  66609. }, delay);
  66610. return;
  66611. }
  66612. this._started = true;
  66613. this._stopped = false;
  66614. this._preWarmDone = false;
  66615. // Animations
  66616. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  66617. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  66618. }
  66619. };
  66620. /**
  66621. * Stops the particle system.
  66622. */
  66623. GPUParticleSystem.prototype.stop = function () {
  66624. this._stopped = true;
  66625. };
  66626. /**
  66627. * Remove all active particles
  66628. */
  66629. GPUParticleSystem.prototype.reset = function () {
  66630. this._releaseBuffers();
  66631. this._releaseVAOs();
  66632. this._currentActiveCount = 0;
  66633. this._targetIndex = 0;
  66634. };
  66635. /**
  66636. * Returns the string "GPUParticleSystem"
  66637. * @returns a string containing the class name
  66638. */
  66639. GPUParticleSystem.prototype.getClassName = function () {
  66640. return "GPUParticleSystem";
  66641. };
  66642. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  66643. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  66644. this._releaseBuffers();
  66645. return this;
  66646. };
  66647. /**
  66648. * Adds a new color gradient
  66649. * @param gradient defines the gradient to use (between 0 and 1)
  66650. * @param color1 defines the color to affect to the specified gradient
  66651. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  66652. * @returns the current particle system
  66653. */
  66654. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  66655. if (!this._colorGradients) {
  66656. this._colorGradients = [];
  66657. }
  66658. var colorGradient = new BABYLON.ColorGradient();
  66659. colorGradient.gradient = gradient;
  66660. colorGradient.color1 = color1;
  66661. this._colorGradients.push(colorGradient);
  66662. this._colorGradients.sort(function (a, b) {
  66663. if (a.gradient < b.gradient) {
  66664. return -1;
  66665. }
  66666. else if (a.gradient > b.gradient) {
  66667. return 1;
  66668. }
  66669. return 0;
  66670. });
  66671. if (this._colorGradientsTexture) {
  66672. this._colorGradientsTexture.dispose();
  66673. this._colorGradientsTexture = null;
  66674. }
  66675. this._releaseBuffers();
  66676. return this;
  66677. };
  66678. /**
  66679. * Remove a specific color gradient
  66680. * @param gradient defines the gradient to remove
  66681. * @returns the current particle system
  66682. */
  66683. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  66684. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  66685. this._colorGradientsTexture = null;
  66686. return this;
  66687. };
  66688. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  66689. var valueGradient = new BABYLON.FactorGradient();
  66690. valueGradient.gradient = gradient;
  66691. valueGradient.factor1 = factor;
  66692. factorGradients.push(valueGradient);
  66693. factorGradients.sort(function (a, b) {
  66694. if (a.gradient < b.gradient) {
  66695. return -1;
  66696. }
  66697. else if (a.gradient > b.gradient) {
  66698. return 1;
  66699. }
  66700. return 0;
  66701. });
  66702. this._releaseBuffers();
  66703. };
  66704. /**
  66705. * Adds a new size gradient
  66706. * @param gradient defines the gradient to use (between 0 and 1)
  66707. * @param factor defines the size factor to affect to the specified gradient
  66708. * @returns the current particle system
  66709. */
  66710. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  66711. if (!this._sizeGradients) {
  66712. this._sizeGradients = [];
  66713. }
  66714. this._addFactorGradient(this._sizeGradients, gradient, factor);
  66715. if (this._sizeGradientsTexture) {
  66716. this._sizeGradientsTexture.dispose();
  66717. this._sizeGradientsTexture = null;
  66718. }
  66719. this._releaseBuffers();
  66720. return this;
  66721. };
  66722. /**
  66723. * Remove a specific size gradient
  66724. * @param gradient defines the gradient to remove
  66725. * @returns the current particle system
  66726. */
  66727. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  66728. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  66729. this._sizeGradientsTexture = null;
  66730. return this;
  66731. };
  66732. /**
  66733. * Adds a new angular speed gradient
  66734. * @param gradient defines the gradient to use (between 0 and 1)
  66735. * @param factor defines the angular speed to affect to the specified gradient
  66736. * @returns the current particle system
  66737. */
  66738. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  66739. if (!this._angularSpeedGradients) {
  66740. this._angularSpeedGradients = [];
  66741. }
  66742. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  66743. if (this._angularSpeedGradientsTexture) {
  66744. this._angularSpeedGradientsTexture.dispose();
  66745. this._angularSpeedGradientsTexture = null;
  66746. }
  66747. this._releaseBuffers();
  66748. return this;
  66749. };
  66750. /**
  66751. * Remove a specific angular speed gradient
  66752. * @param gradient defines the gradient to remove
  66753. * @returns the current particle system
  66754. */
  66755. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  66756. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  66757. this._angularSpeedGradientsTexture = null;
  66758. return this;
  66759. };
  66760. /**
  66761. * Adds a new velocity gradient
  66762. * @param gradient defines the gradient to use (between 0 and 1)
  66763. * @param factor defines the velocity to affect to the specified gradient
  66764. * @returns the current particle system
  66765. */
  66766. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  66767. if (!this._velocityGradients) {
  66768. this._velocityGradients = [];
  66769. }
  66770. this._addFactorGradient(this._velocityGradients, gradient, factor);
  66771. if (this._velocityGradientsTexture) {
  66772. this._velocityGradientsTexture.dispose();
  66773. this._velocityGradientsTexture = null;
  66774. }
  66775. this._releaseBuffers();
  66776. return this;
  66777. };
  66778. /**
  66779. * Remove a specific velocity gradient
  66780. * @param gradient defines the gradient to remove
  66781. * @returns the current particle system
  66782. */
  66783. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  66784. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  66785. this._velocityGradientsTexture = null;
  66786. return this;
  66787. };
  66788. /**
  66789. * Adds a new limit velocity gradient
  66790. * @param gradient defines the gradient to use (between 0 and 1)
  66791. * @param factor defines the limit velocity value to affect to the specified gradient
  66792. * @returns the current particle system
  66793. */
  66794. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  66795. if (!this._limitVelocityGradients) {
  66796. this._limitVelocityGradients = [];
  66797. }
  66798. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  66799. if (this._limitVelocityGradientsTexture) {
  66800. this._limitVelocityGradientsTexture.dispose();
  66801. this._limitVelocityGradientsTexture = null;
  66802. }
  66803. this._releaseBuffers();
  66804. return this;
  66805. };
  66806. /**
  66807. * Remove a specific limit velocity gradient
  66808. * @param gradient defines the gradient to remove
  66809. * @returns the current particle system
  66810. */
  66811. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  66812. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  66813. this._limitVelocityGradientsTexture = null;
  66814. return this;
  66815. };
  66816. /**
  66817. * Adds a new drag gradient
  66818. * @param gradient defines the gradient to use (between 0 and 1)
  66819. * @param factor defines the drag value to affect to the specified gradient
  66820. * @returns the current particle system
  66821. */
  66822. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  66823. if (!this._dragGradients) {
  66824. this._dragGradients = [];
  66825. }
  66826. this._addFactorGradient(this._dragGradients, gradient, factor);
  66827. if (this._dragGradientsTexture) {
  66828. this._dragGradientsTexture.dispose();
  66829. this._dragGradientsTexture = null;
  66830. }
  66831. this._releaseBuffers();
  66832. return this;
  66833. };
  66834. /**
  66835. * Remove a specific drag gradient
  66836. * @param gradient defines the gradient to remove
  66837. * @returns the current particle system
  66838. */
  66839. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  66840. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  66841. this._dragGradientsTexture = null;
  66842. return this;
  66843. };
  66844. /**
  66845. * Not supported by GPUParticleSystem
  66846. * @param gradient defines the gradient to use (between 0 and 1)
  66847. * @param factor defines the emit rate value to affect to the specified gradient
  66848. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66849. * @returns the current particle system
  66850. */
  66851. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  66852. // Do nothing as emit rate is not supported by GPUParticleSystem
  66853. return this;
  66854. };
  66855. /**
  66856. * Not supported by GPUParticleSystem
  66857. * @param gradient defines the gradient to remove
  66858. * @returns the current particle system
  66859. */
  66860. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  66861. // Do nothing as emit rate is not supported by GPUParticleSystem
  66862. return this;
  66863. };
  66864. /**
  66865. * Not supported by GPUParticleSystem
  66866. * @param gradient defines the gradient to use (between 0 and 1)
  66867. * @param factor defines the start size value to affect to the specified gradient
  66868. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66869. * @returns the current particle system
  66870. */
  66871. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  66872. // Do nothing as start size is not supported by GPUParticleSystem
  66873. return this;
  66874. };
  66875. /**
  66876. * Not supported by GPUParticleSystem
  66877. * @param gradient defines the gradient to remove
  66878. * @returns the current particle system
  66879. */
  66880. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  66881. // Do nothing as start size is not supported by GPUParticleSystem
  66882. return this;
  66883. };
  66884. /**
  66885. * Not supported by GPUParticleSystem
  66886. * @param gradient defines the gradient to use (between 0 and 1)
  66887. * @param min defines the color remap minimal range
  66888. * @param max defines the color remap maximal range
  66889. * @returns the current particle system
  66890. */
  66891. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  66892. // Do nothing as start size is not supported by GPUParticleSystem
  66893. return this;
  66894. };
  66895. /**
  66896. * Not supported by GPUParticleSystem
  66897. * @param gradient defines the gradient to remove
  66898. * @returns the current particle system
  66899. */
  66900. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  66901. // Do nothing as start size is not supported by GPUParticleSystem
  66902. return this;
  66903. };
  66904. /**
  66905. * Not supported by GPUParticleSystem
  66906. * @param gradient defines the gradient to use (between 0 and 1)
  66907. * @param min defines the alpha remap minimal range
  66908. * @param max defines the alpha remap maximal range
  66909. * @returns the current particle system
  66910. */
  66911. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  66912. // Do nothing as start size is not supported by GPUParticleSystem
  66913. return this;
  66914. };
  66915. /**
  66916. * Not supported by GPUParticleSystem
  66917. * @param gradient defines the gradient to remove
  66918. * @returns the current particle system
  66919. */
  66920. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  66921. // Do nothing as start size is not supported by GPUParticleSystem
  66922. return this;
  66923. };
  66924. /**
  66925. * Not supported by GPUParticleSystem
  66926. * @param gradient defines the gradient to use (between 0 and 1)
  66927. * @param color defines the color to affect to the specified gradient
  66928. * @returns the current particle system
  66929. */
  66930. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  66931. //Not supported by GPUParticleSystem
  66932. return this;
  66933. };
  66934. /**
  66935. * Not supported by GPUParticleSystem
  66936. * @param gradient defines the gradient to remove
  66937. * @returns the current particle system
  66938. */
  66939. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  66940. //Not supported by GPUParticleSystem
  66941. return this;
  66942. };
  66943. /**
  66944. * Not supported by GPUParticleSystem
  66945. * @returns the list of ramp gradients
  66946. */
  66947. GPUParticleSystem.prototype.getRampGradients = function () {
  66948. return null;
  66949. };
  66950. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  66951. /**
  66952. * Not supported by GPUParticleSystem
  66953. * Gets or sets a boolean indicating that ramp gradients must be used
  66954. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  66955. */
  66956. get: function () {
  66957. //Not supported by GPUParticleSystem
  66958. return false;
  66959. },
  66960. set: function (value) {
  66961. //Not supported by GPUParticleSystem
  66962. },
  66963. enumerable: true,
  66964. configurable: true
  66965. });
  66966. /**
  66967. * Not supported by GPUParticleSystem
  66968. * @param gradient defines the gradient to use (between 0 and 1)
  66969. * @param factor defines the life time factor to affect to the specified gradient
  66970. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66971. * @returns the current particle system
  66972. */
  66973. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  66974. //Not supported by GPUParticleSystem
  66975. return this;
  66976. };
  66977. /**
  66978. * Not supported by GPUParticleSystem
  66979. * @param gradient defines the gradient to remove
  66980. * @returns the current particle system
  66981. */
  66982. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  66983. //Not supported by GPUParticleSystem
  66984. return this;
  66985. };
  66986. GPUParticleSystem.prototype._reset = function () {
  66987. this._releaseBuffers();
  66988. };
  66989. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  66990. var updateVertexBuffers = {};
  66991. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  66992. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  66993. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  66994. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  66995. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  66996. var offset = 12;
  66997. if (!this._colorGradientsTexture) {
  66998. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  66999. offset += 4;
  67000. }
  67001. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  67002. offset += 3;
  67003. if (!this._isBillboardBased) {
  67004. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  67005. offset += 3;
  67006. }
  67007. if (this._angularSpeedGradientsTexture) {
  67008. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  67009. offset += 1;
  67010. }
  67011. else {
  67012. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  67013. offset += 2;
  67014. }
  67015. if (this._isAnimationSheetEnabled) {
  67016. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  67017. offset += 1;
  67018. if (this.spriteRandomStartCell) {
  67019. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  67020. offset += 1;
  67021. }
  67022. }
  67023. if (this.noiseTexture) {
  67024. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  67025. offset += 3;
  67026. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  67027. offset += 3;
  67028. }
  67029. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  67030. this._engine.bindArrayBuffer(null);
  67031. return vao;
  67032. };
  67033. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  67034. var renderVertexBuffers = {};
  67035. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  67036. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  67037. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  67038. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  67039. var offset = 12;
  67040. if (!this._colorGradientsTexture) {
  67041. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  67042. offset += 4;
  67043. }
  67044. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  67045. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  67046. }
  67047. offset += 3; // Direction
  67048. if (!this._isBillboardBased) {
  67049. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  67050. offset += 3;
  67051. }
  67052. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  67053. if (this._angularSpeedGradientsTexture) {
  67054. offset++;
  67055. }
  67056. else {
  67057. offset += 2;
  67058. }
  67059. if (this._isAnimationSheetEnabled) {
  67060. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  67061. offset += 1;
  67062. if (this.spriteRandomStartCell) {
  67063. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  67064. offset += 1;
  67065. }
  67066. }
  67067. if (this.noiseTexture) {
  67068. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  67069. offset += 3;
  67070. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  67071. offset += 3;
  67072. }
  67073. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  67074. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  67075. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  67076. this._engine.bindArrayBuffer(null);
  67077. return vao;
  67078. };
  67079. GPUParticleSystem.prototype._initialize = function (force) {
  67080. if (force === void 0) { force = false; }
  67081. if (this._buffer0 && !force) {
  67082. return;
  67083. }
  67084. var engine = this._scene.getEngine();
  67085. var data = new Array();
  67086. if (!this.isBillboardBased) {
  67087. this._attributesStrideSize += 3;
  67088. }
  67089. if (this._colorGradientsTexture) {
  67090. this._attributesStrideSize -= 4;
  67091. }
  67092. if (this._angularSpeedGradientsTexture) {
  67093. this._attributesStrideSize -= 1;
  67094. }
  67095. if (this._isAnimationSheetEnabled) {
  67096. this._attributesStrideSize += 1;
  67097. if (this.spriteRandomStartCell) {
  67098. this._attributesStrideSize += 1;
  67099. }
  67100. }
  67101. if (this.noiseTexture) {
  67102. this._attributesStrideSize += 6;
  67103. }
  67104. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  67105. // position
  67106. data.push(0.0);
  67107. data.push(0.0);
  67108. data.push(0.0);
  67109. // Age and life
  67110. data.push(0.0); // create the particle as a dead one to create a new one at start
  67111. data.push(0.0);
  67112. // Seed
  67113. data.push(Math.random());
  67114. data.push(Math.random());
  67115. data.push(Math.random());
  67116. data.push(Math.random());
  67117. // Size
  67118. data.push(0.0);
  67119. data.push(0.0);
  67120. data.push(0.0);
  67121. if (!this._colorGradientsTexture) {
  67122. // color
  67123. data.push(0.0);
  67124. data.push(0.0);
  67125. data.push(0.0);
  67126. data.push(0.0);
  67127. }
  67128. // direction
  67129. data.push(0.0);
  67130. data.push(0.0);
  67131. data.push(0.0);
  67132. if (!this.isBillboardBased) {
  67133. // initialDirection
  67134. data.push(0.0);
  67135. data.push(0.0);
  67136. data.push(0.0);
  67137. }
  67138. // angle
  67139. data.push(0.0);
  67140. if (!this._angularSpeedGradientsTexture) {
  67141. data.push(0.0);
  67142. }
  67143. if (this._isAnimationSheetEnabled) {
  67144. data.push(0.0);
  67145. if (this.spriteRandomStartCell) {
  67146. data.push(0.0);
  67147. }
  67148. }
  67149. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  67150. data.push(Math.random());
  67151. data.push(Math.random());
  67152. data.push(Math.random());
  67153. data.push(Math.random());
  67154. data.push(Math.random());
  67155. data.push(Math.random());
  67156. }
  67157. }
  67158. // Sprite data
  67159. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  67160. -0.5, 0.5, 0, 1,
  67161. -0.5, -0.5, 0, 0,
  67162. 0.5, -0.5, 1, 0]);
  67163. // Buffers
  67164. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67165. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67166. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  67167. // Update VAO
  67168. this._updateVAO = [];
  67169. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  67170. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  67171. // Render VAO
  67172. this._renderVAO = [];
  67173. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  67174. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  67175. // Links
  67176. this._sourceBuffer = this._buffer0;
  67177. this._targetBuffer = this._buffer1;
  67178. };
  67179. /** @hidden */
  67180. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  67181. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  67182. if (this._isBillboardBased) {
  67183. defines += "\n#define BILLBOARD";
  67184. }
  67185. if (this._colorGradientsTexture) {
  67186. defines += "\n#define COLORGRADIENTS";
  67187. }
  67188. if (this._sizeGradientsTexture) {
  67189. defines += "\n#define SIZEGRADIENTS";
  67190. }
  67191. if (this._angularSpeedGradientsTexture) {
  67192. defines += "\n#define ANGULARSPEEDGRADIENTS";
  67193. }
  67194. if (this._velocityGradientsTexture) {
  67195. defines += "\n#define VELOCITYGRADIENTS";
  67196. }
  67197. if (this._limitVelocityGradientsTexture) {
  67198. defines += "\n#define LIMITVELOCITYGRADIENTS";
  67199. }
  67200. if (this._dragGradientsTexture) {
  67201. defines += "\n#define DRAGGRADIENTS";
  67202. }
  67203. if (this.isAnimationSheetEnabled) {
  67204. defines += "\n#define ANIMATESHEET";
  67205. if (this.spriteRandomStartCell) {
  67206. defines += "\n#define ANIMATESHEETRANDOMSTART";
  67207. }
  67208. }
  67209. if (this.noiseTexture) {
  67210. defines += "\n#define NOISE";
  67211. }
  67212. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  67213. return;
  67214. }
  67215. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  67216. if (!this._colorGradientsTexture) {
  67217. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  67218. }
  67219. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  67220. if (!this._isBillboardBased) {
  67221. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  67222. }
  67223. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  67224. if (this.isAnimationSheetEnabled) {
  67225. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  67226. if (this.spriteRandomStartCell) {
  67227. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  67228. }
  67229. }
  67230. if (this.noiseTexture) {
  67231. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  67232. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  67233. }
  67234. this._updateEffectOptions.defines = defines;
  67235. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  67236. };
  67237. /** @hidden */
  67238. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  67239. var defines = "";
  67240. if (this._scene.clipPlane) {
  67241. defines = "\n#define CLIPPLANE";
  67242. }
  67243. if (this._scene.clipPlane2) {
  67244. defines = "\n#define CLIPPLANE2";
  67245. }
  67246. if (this._scene.clipPlane3) {
  67247. defines = "\n#define CLIPPLANE3";
  67248. }
  67249. if (this._scene.clipPlane4) {
  67250. defines = "\n#define CLIPPLANE4";
  67251. }
  67252. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  67253. defines = "\n#define BLENDMULTIPLYMODE";
  67254. }
  67255. if (this._isBillboardBased) {
  67256. defines += "\n#define BILLBOARD";
  67257. switch (this.billboardMode) {
  67258. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  67259. defines += "\n#define BILLBOARDY";
  67260. break;
  67261. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  67262. defines += "\n#define BILLBOARDSTRETCHED";
  67263. break;
  67264. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  67265. default:
  67266. break;
  67267. }
  67268. }
  67269. if (this._colorGradientsTexture) {
  67270. defines += "\n#define COLORGRADIENTS";
  67271. }
  67272. if (this.isAnimationSheetEnabled) {
  67273. defines += "\n#define ANIMATESHEET";
  67274. }
  67275. if (this._imageProcessingConfiguration) {
  67276. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  67277. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  67278. }
  67279. if (this._renderEffect && this._renderEffect.defines === defines) {
  67280. return;
  67281. }
  67282. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  67283. var samplers = ["textureSampler", "colorGradientSampler"];
  67284. if (BABYLON.ImageProcessingConfiguration) {
  67285. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  67286. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  67287. }
  67288. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  67289. };
  67290. /**
  67291. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  67292. * @param preWarm defines if we are in the pre-warmimg phase
  67293. */
  67294. GPUParticleSystem.prototype.animate = function (preWarm) {
  67295. if (preWarm === void 0) { preWarm = false; }
  67296. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  67297. this._actualFrame += this._timeDelta;
  67298. if (!this._stopped) {
  67299. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  67300. this.stop();
  67301. }
  67302. }
  67303. };
  67304. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  67305. var texture = this[textureName];
  67306. if (!factorGradients || !factorGradients.length || texture) {
  67307. return;
  67308. }
  67309. var data = new Float32Array(this._rawTextureWidth);
  67310. for (var x = 0; x < this._rawTextureWidth; x++) {
  67311. var ratio = x / this._rawTextureWidth;
  67312. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  67313. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  67314. });
  67315. }
  67316. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67317. };
  67318. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  67319. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  67320. };
  67321. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  67322. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  67323. };
  67324. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  67325. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  67326. };
  67327. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  67328. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  67329. };
  67330. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  67331. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  67332. };
  67333. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  67334. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  67335. return;
  67336. }
  67337. var data = new Uint8Array(this._rawTextureWidth * 4);
  67338. var tmpColor = BABYLON.Tmp.Color4[0];
  67339. for (var x = 0; x < this._rawTextureWidth; x++) {
  67340. var ratio = x / this._rawTextureWidth;
  67341. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  67342. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  67343. data[x * 4] = tmpColor.r * 255;
  67344. data[x * 4 + 1] = tmpColor.g * 255;
  67345. data[x * 4 + 2] = tmpColor.b * 255;
  67346. data[x * 4 + 3] = tmpColor.a * 255;
  67347. });
  67348. }
  67349. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67350. };
  67351. /**
  67352. * Renders the particle system in its current state
  67353. * @param preWarm defines if the system should only update the particles but not render them
  67354. * @returns the current number of particles
  67355. */
  67356. GPUParticleSystem.prototype.render = function (preWarm) {
  67357. if (preWarm === void 0) { preWarm = false; }
  67358. if (!this._started) {
  67359. return 0;
  67360. }
  67361. this._createColorGradientTexture();
  67362. this._createSizeGradientTexture();
  67363. this._createAngularSpeedGradientTexture();
  67364. this._createVelocityGradientTexture();
  67365. this._createLimitVelocityGradientTexture();
  67366. this._createDragGradientTexture();
  67367. this._recreateUpdateEffect();
  67368. this._recreateRenderEffect();
  67369. if (!this.isReady()) {
  67370. return 0;
  67371. }
  67372. if (!preWarm) {
  67373. if (!this._preWarmDone && this.preWarmCycles) {
  67374. for (var index = 0; index < this.preWarmCycles; index++) {
  67375. this.animate(true);
  67376. this.render(true);
  67377. }
  67378. this._preWarmDone = true;
  67379. }
  67380. if (this._currentRenderId === this._scene.getFrameId()) {
  67381. return 0;
  67382. }
  67383. this._currentRenderId = this._scene.getFrameId();
  67384. }
  67385. // Get everything ready to render
  67386. this._initialize();
  67387. this._accumulatedCount += this.emitRate * this._timeDelta;
  67388. if (this._accumulatedCount > 1) {
  67389. var intPart = this._accumulatedCount | 0;
  67390. this._accumulatedCount -= intPart;
  67391. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  67392. }
  67393. if (!this._currentActiveCount) {
  67394. return 0;
  67395. }
  67396. // Enable update effect
  67397. this._engine.enableEffect(this._updateEffect);
  67398. this._engine.setState(false);
  67399. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  67400. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  67401. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  67402. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  67403. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  67404. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  67405. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  67406. if (!this._colorGradientsTexture) {
  67407. this._updateEffect.setDirectColor4("color1", this.color1);
  67408. this._updateEffect.setDirectColor4("color2", this.color2);
  67409. }
  67410. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  67411. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  67412. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  67413. this._updateEffect.setVector3("gravity", this.gravity);
  67414. if (this._sizeGradientsTexture) {
  67415. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  67416. }
  67417. if (this._angularSpeedGradientsTexture) {
  67418. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  67419. }
  67420. if (this._velocityGradientsTexture) {
  67421. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  67422. }
  67423. if (this._limitVelocityGradientsTexture) {
  67424. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  67425. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  67426. }
  67427. if (this._dragGradientsTexture) {
  67428. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  67429. }
  67430. if (this.particleEmitterType) {
  67431. this.particleEmitterType.applyToShader(this._updateEffect);
  67432. }
  67433. if (this._isAnimationSheetEnabled) {
  67434. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  67435. }
  67436. if (this.noiseTexture) {
  67437. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  67438. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  67439. }
  67440. var emitterWM;
  67441. if (this.emitter.position) {
  67442. var emitterMesh = this.emitter;
  67443. emitterWM = emitterMesh.getWorldMatrix();
  67444. }
  67445. else {
  67446. var emitterPosition = this.emitter;
  67447. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  67448. }
  67449. this._updateEffect.setMatrix("emitterWM", emitterWM);
  67450. // Bind source VAO
  67451. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  67452. // Update
  67453. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  67454. this._engine.setRasterizerState(false);
  67455. this._engine.beginTransformFeedback(true);
  67456. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  67457. this._engine.endTransformFeedback();
  67458. this._engine.setRasterizerState(true);
  67459. this._engine.bindTransformFeedbackBuffer(null);
  67460. if (!preWarm) {
  67461. // Enable render effect
  67462. this._engine.enableEffect(this._renderEffect);
  67463. var viewMatrix = this._scene.getViewMatrix();
  67464. this._renderEffect.setMatrix("view", viewMatrix);
  67465. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  67466. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  67467. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  67468. if (this._colorGradientsTexture) {
  67469. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  67470. }
  67471. else {
  67472. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  67473. }
  67474. if (this._isAnimationSheetEnabled && this.particleTexture) {
  67475. var baseSize = this.particleTexture.getBaseSize();
  67476. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  67477. }
  67478. if (this._isBillboardBased) {
  67479. var camera = this._scene.activeCamera;
  67480. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  67481. }
  67482. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  67483. var invView = viewMatrix.clone();
  67484. invView.invert();
  67485. this._renderEffect.setMatrix("invView", invView);
  67486. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  67487. }
  67488. // image processing
  67489. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  67490. this._imageProcessingConfiguration.bind(this._renderEffect);
  67491. }
  67492. // Draw order
  67493. switch (this.blendMode) {
  67494. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  67495. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  67496. break;
  67497. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  67498. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  67499. break;
  67500. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  67501. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67502. break;
  67503. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  67504. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  67505. break;
  67506. }
  67507. if (this.forceDepthWrite) {
  67508. this._engine.setDepthWrite(true);
  67509. }
  67510. // Bind source VAO
  67511. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  67512. // Render
  67513. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  67514. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67515. }
  67516. // Switch VAOs
  67517. this._targetIndex++;
  67518. if (this._targetIndex === 2) {
  67519. this._targetIndex = 0;
  67520. }
  67521. // Switch buffers
  67522. var tmpBuffer = this._sourceBuffer;
  67523. this._sourceBuffer = this._targetBuffer;
  67524. this._targetBuffer = tmpBuffer;
  67525. return this._currentActiveCount;
  67526. };
  67527. /**
  67528. * Rebuilds the particle system
  67529. */
  67530. GPUParticleSystem.prototype.rebuild = function () {
  67531. this._initialize(true);
  67532. };
  67533. GPUParticleSystem.prototype._releaseBuffers = function () {
  67534. if (this._buffer0) {
  67535. this._buffer0.dispose();
  67536. this._buffer0 = null;
  67537. }
  67538. if (this._buffer1) {
  67539. this._buffer1.dispose();
  67540. this._buffer1 = null;
  67541. }
  67542. if (this._spriteBuffer) {
  67543. this._spriteBuffer.dispose();
  67544. this._spriteBuffer = null;
  67545. }
  67546. };
  67547. GPUParticleSystem.prototype._releaseVAOs = function () {
  67548. if (!this._updateVAO) {
  67549. return;
  67550. }
  67551. for (var index = 0; index < this._updateVAO.length; index++) {
  67552. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  67553. }
  67554. this._updateVAO = [];
  67555. for (var index = 0; index < this._renderVAO.length; index++) {
  67556. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  67557. }
  67558. this._renderVAO = [];
  67559. };
  67560. /**
  67561. * Disposes the particle system and free the associated resources
  67562. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  67563. */
  67564. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  67565. if (disposeTexture === void 0) { disposeTexture = true; }
  67566. var index = this._scene.particleSystems.indexOf(this);
  67567. if (index > -1) {
  67568. this._scene.particleSystems.splice(index, 1);
  67569. }
  67570. this._releaseBuffers();
  67571. this._releaseVAOs();
  67572. if (this._colorGradientsTexture) {
  67573. this._colorGradientsTexture.dispose();
  67574. this._colorGradientsTexture = null;
  67575. }
  67576. if (this._sizeGradientsTexture) {
  67577. this._sizeGradientsTexture.dispose();
  67578. this._sizeGradientsTexture = null;
  67579. }
  67580. if (this._angularSpeedGradientsTexture) {
  67581. this._angularSpeedGradientsTexture.dispose();
  67582. this._angularSpeedGradientsTexture = null;
  67583. }
  67584. if (this._velocityGradientsTexture) {
  67585. this._velocityGradientsTexture.dispose();
  67586. this._velocityGradientsTexture = null;
  67587. }
  67588. if (this._limitVelocityGradientsTexture) {
  67589. this._limitVelocityGradientsTexture.dispose();
  67590. this._limitVelocityGradientsTexture = null;
  67591. }
  67592. if (this._dragGradientsTexture) {
  67593. this._dragGradientsTexture.dispose();
  67594. this._dragGradientsTexture = null;
  67595. }
  67596. if (this._randomTexture) {
  67597. this._randomTexture.dispose();
  67598. this._randomTexture = null;
  67599. }
  67600. if (this._randomTexture2) {
  67601. this._randomTexture2.dispose();
  67602. this._randomTexture2 = null;
  67603. }
  67604. if (disposeTexture && this.particleTexture) {
  67605. this.particleTexture.dispose();
  67606. this.particleTexture = null;
  67607. }
  67608. if (disposeTexture && this.noiseTexture) {
  67609. this.noiseTexture.dispose();
  67610. this.noiseTexture = null;
  67611. }
  67612. // Callback
  67613. this.onDisposeObservable.notifyObservers(this);
  67614. this.onDisposeObservable.clear();
  67615. };
  67616. /**
  67617. * Clones the particle system.
  67618. * @param name The name of the cloned object
  67619. * @param newEmitter The new emitter to use
  67620. * @returns the cloned particle system
  67621. */
  67622. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  67623. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  67624. BABYLON.Tools.DeepCopy(this, result);
  67625. if (newEmitter === undefined) {
  67626. newEmitter = this.emitter;
  67627. }
  67628. result.emitter = newEmitter;
  67629. if (this.particleTexture) {
  67630. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  67631. }
  67632. return result;
  67633. };
  67634. /**
  67635. * Serializes the particle system to a JSON object.
  67636. * @returns the JSON object
  67637. */
  67638. GPUParticleSystem.prototype.serialize = function () {
  67639. var serializationObject = {};
  67640. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  67641. serializationObject.activeParticleCount = this.activeParticleCount;
  67642. return serializationObject;
  67643. };
  67644. /**
  67645. * Parses a JSON object to create a GPU particle system.
  67646. * @param parsedParticleSystem The JSON object to parse
  67647. * @param scene The scene to create the particle system in
  67648. * @param rootUrl The root url to use to load external dependencies like texture
  67649. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  67650. * @returns the parsed GPU particle system
  67651. */
  67652. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  67653. if (doNotStart === void 0) { doNotStart = false; }
  67654. var name = parsedParticleSystem.name;
  67655. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  67656. if (parsedParticleSystem.activeParticleCount) {
  67657. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  67658. }
  67659. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  67660. // Auto start
  67661. if (parsedParticleSystem.preventAutoStart) {
  67662. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  67663. }
  67664. if (!doNotStart && !particleSystem.preventAutoStart) {
  67665. particleSystem.start();
  67666. }
  67667. return particleSystem;
  67668. };
  67669. return GPUParticleSystem;
  67670. }(BABYLON.BaseParticleSystem));
  67671. BABYLON.GPUParticleSystem = GPUParticleSystem;
  67672. })(BABYLON || (BABYLON = {}));
  67673. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  67674. var BABYLON;
  67675. (function (BABYLON) {
  67676. /**
  67677. * Represents one particle of a solid particle system.
  67678. */
  67679. var SolidParticle = /** @class */ (function () {
  67680. /**
  67681. * Creates a Solid Particle object.
  67682. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  67683. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  67684. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  67685. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  67686. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  67687. * @param shapeId (integer) is the model shape identifier in the SPS.
  67688. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  67689. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  67690. */
  67691. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  67692. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  67693. /**
  67694. * particle global index
  67695. */
  67696. this.idx = 0;
  67697. /**
  67698. * The color of the particle
  67699. */
  67700. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67701. /**
  67702. * The world space position of the particle.
  67703. */
  67704. this.position = BABYLON.Vector3.Zero();
  67705. /**
  67706. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  67707. */
  67708. this.rotation = BABYLON.Vector3.Zero();
  67709. /**
  67710. * The scaling of the particle.
  67711. */
  67712. this.scaling = BABYLON.Vector3.One();
  67713. /**
  67714. * The uvs of the particle.
  67715. */
  67716. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  67717. /**
  67718. * The current speed of the particle.
  67719. */
  67720. this.velocity = BABYLON.Vector3.Zero();
  67721. /**
  67722. * The pivot point in the particle local space.
  67723. */
  67724. this.pivot = BABYLON.Vector3.Zero();
  67725. /**
  67726. * Must the particle be translated from its pivot point in its local space ?
  67727. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  67728. * Default : false
  67729. */
  67730. this.translateFromPivot = false;
  67731. /**
  67732. * Is the particle active or not ?
  67733. */
  67734. this.alive = true;
  67735. /**
  67736. * Is the particle visible or not ?
  67737. */
  67738. this.isVisible = true;
  67739. /**
  67740. * Index of this particle in the global "positions" array (Internal use)
  67741. * @hidden
  67742. */
  67743. this._pos = 0;
  67744. /**
  67745. * @hidden Index of this particle in the global "indices" array (Internal use)
  67746. */
  67747. this._ind = 0;
  67748. /**
  67749. * ModelShape id of this particle
  67750. */
  67751. this.shapeId = 0;
  67752. /**
  67753. * Index of the particle in its shape id (Internal use)
  67754. */
  67755. this.idxInShape = 0;
  67756. /**
  67757. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  67758. */
  67759. this._stillInvisible = false;
  67760. /**
  67761. * @hidden Last computed particle rotation matrix
  67762. */
  67763. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  67764. /**
  67765. * Parent particle Id, if any.
  67766. * Default null.
  67767. */
  67768. this.parentId = null;
  67769. /**
  67770. * @hidden Internal global position in the SPS.
  67771. */
  67772. this._globalPosition = BABYLON.Vector3.Zero();
  67773. this.idx = particleIndex;
  67774. this._pos = positionIndex;
  67775. this._ind = indiceIndex;
  67776. this._model = model;
  67777. this.shapeId = shapeId;
  67778. this.idxInShape = idxInShape;
  67779. this._sps = sps;
  67780. if (modelBoundingInfo) {
  67781. this._modelBoundingInfo = modelBoundingInfo;
  67782. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  67783. }
  67784. }
  67785. Object.defineProperty(SolidParticle.prototype, "scale", {
  67786. /**
  67787. * Legacy support, changed scale to scaling
  67788. */
  67789. get: function () {
  67790. return this.scaling;
  67791. },
  67792. /**
  67793. * Legacy support, changed scale to scaling
  67794. */
  67795. set: function (scale) {
  67796. this.scaling = scale;
  67797. },
  67798. enumerable: true,
  67799. configurable: true
  67800. });
  67801. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  67802. /**
  67803. * Legacy support, changed quaternion to rotationQuaternion
  67804. */
  67805. get: function () {
  67806. return this.rotationQuaternion;
  67807. },
  67808. /**
  67809. * Legacy support, changed quaternion to rotationQuaternion
  67810. */
  67811. set: function (q) {
  67812. this.rotationQuaternion = q;
  67813. },
  67814. enumerable: true,
  67815. configurable: true
  67816. });
  67817. /**
  67818. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  67819. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  67820. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  67821. * @returns true if it intersects
  67822. */
  67823. SolidParticle.prototype.intersectsMesh = function (target) {
  67824. if (!this._boundingInfo || !target._boundingInfo) {
  67825. return false;
  67826. }
  67827. if (this._sps._bSphereOnly) {
  67828. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  67829. }
  67830. return this._boundingInfo.intersects(target._boundingInfo, false);
  67831. };
  67832. /**
  67833. * get the rotation matrix of the particle
  67834. * @hidden
  67835. */
  67836. SolidParticle.prototype.getRotationMatrix = function (m) {
  67837. var quaternion;
  67838. if (this.rotationQuaternion) {
  67839. quaternion = this.rotationQuaternion;
  67840. }
  67841. else {
  67842. quaternion = BABYLON.Tmp.Quaternion[0];
  67843. var rotation = this.rotation;
  67844. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  67845. }
  67846. quaternion.toRotationMatrix(m);
  67847. };
  67848. return SolidParticle;
  67849. }());
  67850. BABYLON.SolidParticle = SolidParticle;
  67851. /**
  67852. * Represents the shape of the model used by one particle of a solid particle system.
  67853. * SPS internal tool, don't use it manually.
  67854. */
  67855. var ModelShape = /** @class */ (function () {
  67856. /**
  67857. * 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.
  67858. * SPS internal tool, don't use it manually.
  67859. * @hidden
  67860. */
  67861. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  67862. /**
  67863. * length of the shape in the model indices array (internal use)
  67864. * @hidden
  67865. */
  67866. this._indicesLength = 0;
  67867. this.shapeID = id;
  67868. this._shape = shape;
  67869. this._indicesLength = indicesLength;
  67870. this._shapeUV = shapeUV;
  67871. this._positionFunction = posFunction;
  67872. this._vertexFunction = vtxFunction;
  67873. }
  67874. return ModelShape;
  67875. }());
  67876. BABYLON.ModelShape = ModelShape;
  67877. /**
  67878. * Represents a Depth Sorted Particle in the solid particle system.
  67879. */
  67880. var DepthSortedParticle = /** @class */ (function () {
  67881. function DepthSortedParticle() {
  67882. /**
  67883. * Index of the particle in the "indices" array
  67884. */
  67885. this.ind = 0;
  67886. /**
  67887. * Length of the particle shape in the "indices" array
  67888. */
  67889. this.indicesLength = 0;
  67890. /**
  67891. * Squared distance from the particle to the camera
  67892. */
  67893. this.sqDistance = 0.0;
  67894. }
  67895. return DepthSortedParticle;
  67896. }());
  67897. BABYLON.DepthSortedParticle = DepthSortedParticle;
  67898. })(BABYLON || (BABYLON = {}));
  67899. //# sourceMappingURL=babylon.solidParticle.js.map
  67900. var BABYLON;
  67901. (function (BABYLON) {
  67902. var depthSortFunction = function (p1, p2) { return p2.sqDistance - p1.sqDistance; };
  67903. /**
  67904. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  67905. *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.
  67906. * The SPS is also a particle system. It provides some methods to manage the particles.
  67907. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  67908. *
  67909. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  67910. */
  67911. var SolidParticleSystem = /** @class */ (function () {
  67912. /**
  67913. * Creates a SPS (Solid Particle System) object.
  67914. * @param name (String) is the SPS name, this will be the underlying mesh name.
  67915. * @param scene (Scene) is the scene in which the SPS is added.
  67916. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  67917. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  67918. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  67919. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  67920. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  67921. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  67922. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  67923. */
  67924. function SolidParticleSystem(name, scene, options) {
  67925. /**
  67926. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  67927. * Example : var p = SPS.particles[i];
  67928. */
  67929. this.particles = new Array();
  67930. /**
  67931. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  67932. */
  67933. this.nbParticles = 0;
  67934. /**
  67935. * If the particles must ever face the camera (default false). Useful for planar particles.
  67936. */
  67937. this.billboard = false;
  67938. /**
  67939. * Recompute normals when adding a shape
  67940. */
  67941. this.recomputeNormals = true;
  67942. /**
  67943. * This a counter ofr your own usage. It's not set by any SPS functions.
  67944. */
  67945. this.counter = 0;
  67946. /**
  67947. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  67948. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  67949. */
  67950. this.vars = {};
  67951. /**
  67952. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  67953. * @hidden
  67954. */
  67955. this._bSphereOnly = false;
  67956. /**
  67957. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  67958. * @hidden
  67959. */
  67960. this._bSphereRadiusFactor = 1.0;
  67961. this._positions = new Array();
  67962. this._indices = new Array();
  67963. this._normals = new Array();
  67964. this._colors = new Array();
  67965. this._uvs = new Array();
  67966. this._index = 0; // indices index
  67967. this._updatable = true;
  67968. this._pickable = false;
  67969. this._isVisibilityBoxLocked = false;
  67970. this._alwaysVisible = false;
  67971. this._depthSort = false;
  67972. this._shapeCounter = 0;
  67973. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  67974. this._color = new BABYLON.Color4(0, 0, 0, 0);
  67975. this._computeParticleColor = true;
  67976. this._computeParticleTexture = true;
  67977. this._computeParticleRotation = true;
  67978. this._computeParticleVertex = false;
  67979. this._computeBoundingBox = false;
  67980. this._depthSortParticles = true;
  67981. this._mustUnrotateFixedNormals = false;
  67982. this._particlesIntersect = false;
  67983. this._needs32Bits = false;
  67984. this.name = name;
  67985. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67986. this._camera = scene.activeCamera;
  67987. this._pickable = options ? options.isPickable : false;
  67988. this._depthSort = options ? options.enableDepthSort : false;
  67989. this._particlesIntersect = options ? options.particleIntersection : false;
  67990. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  67991. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  67992. if (options && options.updatable !== undefined) {
  67993. this._updatable = options.updatable;
  67994. }
  67995. else {
  67996. this._updatable = true;
  67997. }
  67998. if (this._pickable) {
  67999. this.pickedParticles = [];
  68000. }
  68001. if (this._depthSort) {
  68002. this.depthSortedParticles = [];
  68003. }
  68004. }
  68005. /**
  68006. * Builds the SPS underlying mesh. Returns a standard Mesh.
  68007. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  68008. * @returns the created mesh
  68009. */
  68010. SolidParticleSystem.prototype.buildMesh = function () {
  68011. if (this.nbParticles === 0) {
  68012. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  68013. this.addShape(triangle, 1);
  68014. triangle.dispose();
  68015. }
  68016. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  68017. this._positions32 = new Float32Array(this._positions);
  68018. this._uvs32 = new Float32Array(this._uvs);
  68019. this._colors32 = new Float32Array(this._colors);
  68020. if (this.recomputeNormals) {
  68021. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  68022. }
  68023. this._normals32 = new Float32Array(this._normals);
  68024. this._fixedNormal32 = new Float32Array(this._normals);
  68025. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  68026. this._unrotateFixedNormals();
  68027. }
  68028. var vertexData = new BABYLON.VertexData();
  68029. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  68030. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  68031. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  68032. if (this._uvs32.length > 0) {
  68033. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  68034. }
  68035. if (this._colors32.length > 0) {
  68036. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  68037. }
  68038. var mesh = new BABYLON.Mesh(this.name, this._scene);
  68039. vertexData.applyToMesh(mesh, this._updatable);
  68040. this.mesh = mesh;
  68041. this.mesh.isPickable = this._pickable;
  68042. // free memory
  68043. if (!this._depthSort) {
  68044. this._indices = null;
  68045. }
  68046. this._positions = null;
  68047. this._normals = null;
  68048. this._uvs = null;
  68049. this._colors = null;
  68050. if (!this._updatable) {
  68051. this.particles.length = 0;
  68052. }
  68053. return mesh;
  68054. };
  68055. /**
  68056. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  68057. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  68058. * Thus the particles generated from `digest()` have their property `position` set yet.
  68059. * @param mesh ( Mesh ) is the mesh to be digested
  68060. * @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
  68061. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  68062. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  68063. * @returns the current SPS
  68064. */
  68065. SolidParticleSystem.prototype.digest = function (mesh, options) {
  68066. var size = (options && options.facetNb) || 1;
  68067. var number = (options && options.number) || 0;
  68068. var delta = (options && options.delta) || 0;
  68069. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68070. var meshInd = mesh.getIndices();
  68071. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68072. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68073. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68074. var f = 0; // facet counter
  68075. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  68076. // compute size from number
  68077. if (number) {
  68078. number = (number > totalFacets) ? totalFacets : number;
  68079. size = Math.round(totalFacets / number);
  68080. delta = 0;
  68081. }
  68082. else {
  68083. size = (size > totalFacets) ? totalFacets : size;
  68084. }
  68085. var facetPos = []; // submesh positions
  68086. var facetInd = []; // submesh indices
  68087. var facetUV = []; // submesh UV
  68088. var facetCol = []; // submesh colors
  68089. var barycenter = BABYLON.Vector3.Zero();
  68090. var sizeO = size;
  68091. while (f < totalFacets) {
  68092. size = sizeO + Math.floor((1 + delta) * Math.random());
  68093. if (f > totalFacets - size) {
  68094. size = totalFacets - f;
  68095. }
  68096. // reset temp arrays
  68097. facetPos.length = 0;
  68098. facetInd.length = 0;
  68099. facetUV.length = 0;
  68100. facetCol.length = 0;
  68101. // iterate over "size" facets
  68102. var fi = 0;
  68103. for (var j = f * 3; j < (f + size) * 3; j++) {
  68104. facetInd.push(fi);
  68105. var i = meshInd[j];
  68106. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  68107. if (meshUV) {
  68108. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  68109. }
  68110. if (meshCol) {
  68111. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  68112. }
  68113. fi++;
  68114. }
  68115. // create a model shape for each single particle
  68116. var idx = this.nbParticles;
  68117. var shape = this._posToShape(facetPos);
  68118. var shapeUV = this._uvsToShapeUV(facetUV);
  68119. // compute the barycenter of the shape
  68120. var v;
  68121. for (v = 0; v < shape.length; v++) {
  68122. barycenter.addInPlace(shape[v]);
  68123. }
  68124. barycenter.scaleInPlace(1 / shape.length);
  68125. // shift the shape from its barycenter to the origin
  68126. for (v = 0; v < shape.length; v++) {
  68127. shape[v].subtractInPlace(barycenter);
  68128. }
  68129. var bInfo;
  68130. if (this._particlesIntersect) {
  68131. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  68132. }
  68133. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  68134. // add the particle in the SPS
  68135. var currentPos = this._positions.length;
  68136. var currentInd = this._indices.length;
  68137. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  68138. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  68139. // initialize the particle position
  68140. this.particles[this.nbParticles].position.addInPlace(barycenter);
  68141. this._index += shape.length;
  68142. idx++;
  68143. this.nbParticles++;
  68144. this._shapeCounter++;
  68145. f += size;
  68146. }
  68147. return this;
  68148. };
  68149. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  68150. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  68151. var index = 0;
  68152. var idx = 0;
  68153. var tmpNormal = BABYLON.Tmp.Vector3[0];
  68154. var quaternion = BABYLON.Tmp.Quaternion[0];
  68155. var invertedRotMatrix = BABYLON.Tmp.Matrix[0];
  68156. for (var p = 0; p < this.particles.length; p++) {
  68157. var particle = this.particles[p];
  68158. var shape = particle._model._shape;
  68159. // computing the inverse of the rotation matrix from the quaternion
  68160. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  68161. if (particle.rotationQuaternion) {
  68162. particle.rotationQuaternion.conjugateToRef(quaternion);
  68163. }
  68164. else {
  68165. var rotation = particle.rotation;
  68166. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68167. quaternion.conjugateInPlace();
  68168. }
  68169. quaternion.toRotationMatrix(invertedRotMatrix);
  68170. for (var pt = 0; pt < shape.length; pt++) {
  68171. idx = index + pt * 3;
  68172. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  68173. tmpNormal.toArray(this._fixedNormal32, idx);
  68174. }
  68175. index = idx + 3;
  68176. }
  68177. };
  68178. //reset copy
  68179. SolidParticleSystem.prototype._resetCopy = function () {
  68180. var copy = this._copy;
  68181. copy.position.setAll(0);
  68182. copy.rotation.setAll(0);
  68183. copy.rotationQuaternion = null;
  68184. copy.scaling.setAll(1);
  68185. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  68186. copy.color = null;
  68187. copy.translateFromPivot = false;
  68188. };
  68189. // _meshBuilder : inserts the shape model in the global SPS mesh
  68190. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  68191. var i;
  68192. var u = 0;
  68193. var c = 0;
  68194. var n = 0;
  68195. this._resetCopy();
  68196. var copy = this._copy;
  68197. if (options && options.positionFunction) { // call to custom positionFunction
  68198. options.positionFunction(copy, idx, idxInShape);
  68199. this._mustUnrotateFixedNormals = true;
  68200. }
  68201. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68202. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68203. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68204. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68205. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68206. copy.getRotationMatrix(rotMatrix);
  68207. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  68208. if (copy.translateFromPivot) {
  68209. pivotBackTranslation.setAll(0.0);
  68210. }
  68211. else {
  68212. pivotBackTranslation.copyFrom(scaledPivot);
  68213. }
  68214. for (i = 0; i < shape.length; i++) {
  68215. tmpVertex.copyFrom(shape[i]);
  68216. if (options && options.vertexFunction) {
  68217. options.vertexFunction(copy, tmpVertex, i);
  68218. }
  68219. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68220. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68221. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  68222. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  68223. if (meshUV) {
  68224. var copyUvs = copy.uvs;
  68225. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  68226. u += 2;
  68227. }
  68228. if (copy.color) {
  68229. this._color = copy.color;
  68230. }
  68231. else {
  68232. var color = this._color;
  68233. if (meshCol && meshCol[c] !== undefined) {
  68234. color.r = meshCol[c];
  68235. color.g = meshCol[c + 1];
  68236. color.b = meshCol[c + 2];
  68237. color.a = meshCol[c + 3];
  68238. }
  68239. else {
  68240. color.r = 1.0;
  68241. color.g = 1.0;
  68242. color.b = 1.0;
  68243. color.a = 1.0;
  68244. }
  68245. }
  68246. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  68247. c += 4;
  68248. if (!this.recomputeNormals && meshNor) {
  68249. tmpVertex.x = meshNor[n];
  68250. tmpVertex.y = meshNor[n + 1];
  68251. tmpVertex.z = meshNor[n + 2];
  68252. BABYLON.Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  68253. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  68254. n += 3;
  68255. }
  68256. }
  68257. for (i = 0; i < meshInd.length; i++) {
  68258. var current_ind = p + meshInd[i];
  68259. indices.push(current_ind);
  68260. if (current_ind > 65535) {
  68261. this._needs32Bits = true;
  68262. }
  68263. }
  68264. if (this._pickable) {
  68265. var nbfaces = meshInd.length / 3;
  68266. for (i = 0; i < nbfaces; i++) {
  68267. this.pickedParticles.push({ idx: idx, faceId: i });
  68268. }
  68269. }
  68270. if (this._depthSort) {
  68271. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  68272. }
  68273. return copy;
  68274. };
  68275. // returns a shape array from positions array
  68276. SolidParticleSystem.prototype._posToShape = function (positions) {
  68277. var shape = [];
  68278. for (var i = 0; i < positions.length; i += 3) {
  68279. shape.push(BABYLON.Vector3.FromArray(positions, i));
  68280. }
  68281. return shape;
  68282. };
  68283. // returns a shapeUV array from a Vector4 uvs
  68284. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  68285. var shapeUV = [];
  68286. if (uvs) {
  68287. for (var i = 0; i < uvs.length; i++) {
  68288. shapeUV.push(uvs[i]);
  68289. }
  68290. }
  68291. return shapeUV;
  68292. };
  68293. // adds a new particle object in the particles array
  68294. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  68295. if (bInfo === void 0) { bInfo = null; }
  68296. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  68297. this.particles.push(sp);
  68298. return sp;
  68299. };
  68300. /**
  68301. * Adds some particles to the SPS from the model shape. Returns the shape id.
  68302. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  68303. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  68304. * @param nb (positive integer) the number of particles to be created from this model
  68305. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  68306. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  68307. * @returns the number of shapes in the system
  68308. */
  68309. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  68310. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68311. var meshInd = mesh.getIndices();
  68312. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68313. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68314. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68315. var bbInfo;
  68316. if (this._particlesIntersect) {
  68317. bbInfo = mesh.getBoundingInfo();
  68318. }
  68319. var shape = this._posToShape(meshPos);
  68320. var shapeUV = this._uvsToShapeUV(meshUV);
  68321. var posfunc = options ? options.positionFunction : null;
  68322. var vtxfunc = options ? options.vertexFunction : null;
  68323. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  68324. // particles
  68325. var sp;
  68326. var currentCopy;
  68327. var idx = this.nbParticles;
  68328. for (var i = 0; i < nb; i++) {
  68329. var currentPos = this._positions.length;
  68330. var currentInd = this._indices.length;
  68331. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  68332. if (this._updatable) {
  68333. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  68334. sp.position.copyFrom(currentCopy.position);
  68335. sp.rotation.copyFrom(currentCopy.rotation);
  68336. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  68337. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  68338. }
  68339. if (currentCopy.color && sp.color) {
  68340. sp.color.copyFrom(currentCopy.color);
  68341. }
  68342. sp.scaling.copyFrom(currentCopy.scaling);
  68343. sp.uvs.copyFrom(currentCopy.uvs);
  68344. }
  68345. this._index += shape.length;
  68346. idx++;
  68347. }
  68348. this.nbParticles += nb;
  68349. this._shapeCounter++;
  68350. return this._shapeCounter - 1;
  68351. };
  68352. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  68353. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  68354. this._resetCopy();
  68355. var copy = this._copy;
  68356. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  68357. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  68358. }
  68359. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68360. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68361. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68362. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68363. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68364. copy.getRotationMatrix(rotMatrix);
  68365. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  68366. if (copy.translateFromPivot) {
  68367. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  68368. }
  68369. else {
  68370. pivotBackTranslation.copyFrom(scaledPivot);
  68371. }
  68372. var shape = particle._model._shape;
  68373. for (var pt = 0; pt < shape.length; pt++) {
  68374. tmpVertex.copyFrom(shape[pt]);
  68375. if (particle._model._vertexFunction) {
  68376. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  68377. }
  68378. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68379. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68380. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  68381. }
  68382. particle.position.setAll(0.0);
  68383. particle.rotation.setAll(0.0);
  68384. particle.rotationQuaternion = null;
  68385. particle.scaling.setAll(1.0);
  68386. particle.uvs.setAll(0.0);
  68387. particle.pivot.setAll(0.0);
  68388. particle.translateFromPivot = false;
  68389. particle.parentId = null;
  68390. };
  68391. /**
  68392. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  68393. * @returns the SPS.
  68394. */
  68395. SolidParticleSystem.prototype.rebuildMesh = function () {
  68396. for (var p = 0; p < this.particles.length; p++) {
  68397. this._rebuildParticle(this.particles[p]);
  68398. }
  68399. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  68400. return this;
  68401. };
  68402. /**
  68403. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  68404. * This method calls `updateParticle()` for each particle of the SPS.
  68405. * For an animated SPS, it is usually called within the render loop.
  68406. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  68407. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  68408. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  68409. * @returns the SPS.
  68410. */
  68411. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  68412. if (start === void 0) { start = 0; }
  68413. if (end === void 0) { end = this.nbParticles - 1; }
  68414. if (update === void 0) { update = true; }
  68415. if (!this._updatable) {
  68416. return this;
  68417. }
  68418. // custom beforeUpdate
  68419. this.beforeUpdateParticles(start, end, update);
  68420. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68421. var invertedMatrix = BABYLON.Tmp.Matrix[1];
  68422. var mesh = this.mesh;
  68423. var colors32 = this._colors32;
  68424. var positions32 = this._positions32;
  68425. var normals32 = this._normals32;
  68426. var uvs32 = this._uvs32;
  68427. var indices32 = this._indices32;
  68428. var indices = this._indices;
  68429. var fixedNormal32 = this._fixedNormal32;
  68430. var tempVectors = BABYLON.Tmp.Vector3;
  68431. var camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  68432. var camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  68433. var camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  68434. var minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  68435. var maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  68436. var camInvertedPosition = tempVectors[10].setAll(0);
  68437. // cases when the World Matrix is to be computed first
  68438. if (this.billboard || this._depthSort) {
  68439. this.mesh.computeWorldMatrix(true);
  68440. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  68441. }
  68442. // if the particles will always face the camera
  68443. if (this.billboard) {
  68444. // compute the camera position and un-rotate it by the current mesh rotation
  68445. var tmpVertex = tempVectors[0];
  68446. this._camera.getDirectionToRef(BABYLON.Axis.Z, tmpVertex);
  68447. BABYLON.Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  68448. camAxisZ.normalize();
  68449. // same for camera up vector extracted from the cam view matrix
  68450. var view = this._camera.getViewMatrix(true);
  68451. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  68452. BABYLON.Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  68453. camAxisY.normalize();
  68454. camAxisX.normalize();
  68455. }
  68456. // if depthSort, compute the camera global position in the mesh local system
  68457. if (this._depthSort) {
  68458. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  68459. }
  68460. BABYLON.Matrix.IdentityToRef(rotMatrix);
  68461. var idx = 0; // current position index in the global array positions32
  68462. var index = 0; // position start index in the global array positions32 of the current particle
  68463. var colidx = 0; // current color index in the global array colors32
  68464. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  68465. var uvidx = 0; // current uv index in the global array uvs32
  68466. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  68467. var pt = 0; // current index in the particle model shape
  68468. if (this.mesh.isFacetDataEnabled) {
  68469. this._computeBoundingBox = true;
  68470. }
  68471. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  68472. if (this._computeBoundingBox) {
  68473. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  68474. var boundingInfo = this.mesh._boundingInfo;
  68475. if (boundingInfo) {
  68476. minimum.copyFrom(boundingInfo.minimum);
  68477. maximum.copyFrom(boundingInfo.maximum);
  68478. }
  68479. }
  68480. }
  68481. // particle loop
  68482. index = this.particles[start]._pos;
  68483. var vpos = (index / 3) | 0;
  68484. colorIndex = vpos * 4;
  68485. uvIndex = vpos * 2;
  68486. for (var p = start; p <= end; p++) {
  68487. var particle = this.particles[p];
  68488. // call to custom user function to update the particle properties
  68489. this.updateParticle(particle);
  68490. var shape = particle._model._shape;
  68491. var shapeUV = particle._model._shapeUV;
  68492. var particleRotationMatrix = particle._rotationMatrix;
  68493. var particlePosition = particle.position;
  68494. var particleRotation = particle.rotation;
  68495. var particleScaling = particle.scaling;
  68496. var particleGlobalPosition = particle._globalPosition;
  68497. // camera-particle distance for depth sorting
  68498. if (this._depthSort && this._depthSortParticles) {
  68499. var dsp = this.depthSortedParticles[p];
  68500. dsp.ind = particle._ind;
  68501. dsp.indicesLength = particle._model._indicesLength;
  68502. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(particle.position, camInvertedPosition);
  68503. }
  68504. // skip the computations for inactive or already invisible particles
  68505. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  68506. // increment indexes for the next particle
  68507. pt = shape.length;
  68508. index += pt * 3;
  68509. colorIndex += pt * 4;
  68510. uvIndex += pt * 2;
  68511. continue;
  68512. }
  68513. if (particle.isVisible) {
  68514. particle._stillInvisible = false; // un-mark permanent invisibility
  68515. var scaledPivot = tempVectors[12];
  68516. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  68517. // particle rotation matrix
  68518. if (this.billboard) {
  68519. particleRotation.x = 0.0;
  68520. particleRotation.y = 0.0;
  68521. }
  68522. if (this._computeParticleRotation || this.billboard) {
  68523. particle.getRotationMatrix(rotMatrix);
  68524. }
  68525. var particleHasParent = (particle.parentId !== null);
  68526. if (particleHasParent) {
  68527. var parent_1 = this.particles[particle.parentId];
  68528. var parentRotationMatrix = parent_1._rotationMatrix;
  68529. var parentGlobalPosition = parent_1._globalPosition;
  68530. var rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  68531. var rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  68532. var rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  68533. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  68534. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  68535. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  68536. if (this._computeParticleRotation || this.billboard) {
  68537. var rotMatrixValues = rotMatrix.m;
  68538. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  68539. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  68540. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  68541. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  68542. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  68543. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  68544. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  68545. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  68546. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  68547. }
  68548. }
  68549. else {
  68550. particleGlobalPosition.x = particlePosition.x;
  68551. particleGlobalPosition.y = particlePosition.y;
  68552. particleGlobalPosition.z = particlePosition.z;
  68553. if (this._computeParticleRotation || this.billboard) {
  68554. var rotMatrixValues = rotMatrix.m;
  68555. particleRotationMatrix[0] = rotMatrixValues[0];
  68556. particleRotationMatrix[1] = rotMatrixValues[1];
  68557. particleRotationMatrix[2] = rotMatrixValues[2];
  68558. particleRotationMatrix[3] = rotMatrixValues[4];
  68559. particleRotationMatrix[4] = rotMatrixValues[5];
  68560. particleRotationMatrix[5] = rotMatrixValues[6];
  68561. particleRotationMatrix[6] = rotMatrixValues[8];
  68562. particleRotationMatrix[7] = rotMatrixValues[9];
  68563. particleRotationMatrix[8] = rotMatrixValues[10];
  68564. }
  68565. }
  68566. var pivotBackTranslation = tempVectors[11];
  68567. if (particle.translateFromPivot) {
  68568. pivotBackTranslation.setAll(0.0);
  68569. }
  68570. else {
  68571. pivotBackTranslation.copyFrom(scaledPivot);
  68572. }
  68573. // particle vertex loop
  68574. for (pt = 0; pt < shape.length; pt++) {
  68575. idx = index + pt * 3;
  68576. colidx = colorIndex + pt * 4;
  68577. uvidx = uvIndex + pt * 2;
  68578. var tmpVertex = tempVectors[0];
  68579. tmpVertex.copyFrom(shape[pt]);
  68580. if (this._computeParticleVertex) {
  68581. this.updateParticleVertex(particle, tmpVertex, pt);
  68582. }
  68583. // positions
  68584. var vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  68585. var vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  68586. var vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  68587. var rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  68588. var rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  68589. var rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  68590. rotatedX += pivotBackTranslation.x;
  68591. rotatedY += pivotBackTranslation.y;
  68592. rotatedZ += pivotBackTranslation.z;
  68593. var px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68594. var py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68595. var pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68596. if (this._computeBoundingBox) {
  68597. minimum.minimizeInPlaceFromFloats(px, py, pz);
  68598. maximum.maximizeInPlaceFromFloats(px, py, pz);
  68599. }
  68600. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  68601. if (!this._computeParticleVertex) {
  68602. var normalx = fixedNormal32[idx];
  68603. var normaly = fixedNormal32[idx + 1];
  68604. var normalz = fixedNormal32[idx + 2];
  68605. var rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  68606. var rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  68607. var rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  68608. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  68609. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  68610. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  68611. }
  68612. if (this._computeParticleColor && particle.color) {
  68613. var color = particle.color;
  68614. var colors32_1 = this._colors32;
  68615. colors32_1[colidx] = color.r;
  68616. colors32_1[colidx + 1] = color.g;
  68617. colors32_1[colidx + 2] = color.b;
  68618. colors32_1[colidx + 3] = color.a;
  68619. }
  68620. if (this._computeParticleTexture) {
  68621. var uvs = particle.uvs;
  68622. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68623. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68624. }
  68625. }
  68626. }
  68627. // particle just set invisible : scaled to zero and positioned at the origin
  68628. else {
  68629. particle._stillInvisible = true; // mark the particle as invisible
  68630. for (pt = 0; pt < shape.length; pt++) {
  68631. idx = index + pt * 3;
  68632. colidx = colorIndex + pt * 4;
  68633. uvidx = uvIndex + pt * 2;
  68634. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  68635. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  68636. if (this._computeParticleColor && particle.color) {
  68637. var color = particle.color;
  68638. colors32[colidx] = color.r;
  68639. colors32[colidx + 1] = color.g;
  68640. colors32[colidx + 2] = color.b;
  68641. colors32[colidx + 3] = color.a;
  68642. }
  68643. if (this._computeParticleTexture) {
  68644. var uvs = particle.uvs;
  68645. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68646. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68647. }
  68648. }
  68649. }
  68650. // if the particle intersections must be computed : update the bbInfo
  68651. if (this._particlesIntersect) {
  68652. var bInfo = particle._boundingInfo;
  68653. var bBox = bInfo.boundingBox;
  68654. var bSphere = bInfo.boundingSphere;
  68655. var modelBoundingInfo = particle._modelBoundingInfo;
  68656. if (!this._bSphereOnly) {
  68657. // place, scale and rotate the particle bbox within the SPS local system, then update it
  68658. var modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  68659. var tempMin = tempVectors[1];
  68660. var tempMax = tempVectors[2];
  68661. tempMin.setAll(Number.MAX_VALUE);
  68662. tempMax.setAll(-Number.MAX_VALUE);
  68663. for (var b = 0; b < 8; b++) {
  68664. var scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  68665. var scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  68666. var scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  68667. var rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  68668. var rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  68669. var rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  68670. var x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68671. var y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68672. var z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68673. tempMin.minimizeInPlaceFromFloats(x, y, z);
  68674. tempMax.maximizeInPlaceFromFloats(x, y, z);
  68675. }
  68676. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  68677. }
  68678. // place and scale the particle bouding sphere in the SPS local system, then update it
  68679. var minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  68680. var maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  68681. var bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5);
  68682. var halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  68683. var bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  68684. var bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  68685. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  68686. }
  68687. // increment indexes for the next particle
  68688. index = idx + 3;
  68689. colorIndex = colidx + 4;
  68690. uvIndex = uvidx + 2;
  68691. }
  68692. // if the VBO must be updated
  68693. if (update) {
  68694. if (this._computeParticleColor) {
  68695. mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors32, false, false);
  68696. }
  68697. if (this._computeParticleTexture) {
  68698. mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs32, false, false);
  68699. }
  68700. mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions32, false, false);
  68701. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  68702. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  68703. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  68704. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  68705. BABYLON.VertexData.ComputeNormals(positions32, indices32, normals32, params);
  68706. for (var i = 0; i < normals32.length; i++) {
  68707. fixedNormal32[i] = normals32[i];
  68708. }
  68709. }
  68710. if (!mesh.areNormalsFrozen) {
  68711. mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals32, false, false);
  68712. }
  68713. }
  68714. if (this._depthSort && this._depthSortParticles) {
  68715. var depthSortedParticles = this.depthSortedParticles;
  68716. depthSortedParticles.sort(depthSortFunction);
  68717. var dspl = depthSortedParticles.length;
  68718. var sid = 0;
  68719. for (var sorted = 0; sorted < dspl; sorted++) {
  68720. var lind = depthSortedParticles[sorted].indicesLength;
  68721. var sind = depthSortedParticles[sorted].ind;
  68722. for (var i = 0; i < lind; i++) {
  68723. indices32[sid] = indices[sind + i];
  68724. sid++;
  68725. }
  68726. }
  68727. mesh.updateIndices(indices32);
  68728. }
  68729. }
  68730. if (this._computeBoundingBox) {
  68731. if (mesh._boundingInfo) {
  68732. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  68733. }
  68734. else {
  68735. mesh._boundingInfo = new BABYLON.BoundingInfo(minimum, maximum, mesh._worldMatrix);
  68736. }
  68737. }
  68738. this.afterUpdateParticles(start, end, update);
  68739. return this;
  68740. };
  68741. /**
  68742. * Disposes the SPS.
  68743. */
  68744. SolidParticleSystem.prototype.dispose = function () {
  68745. this.mesh.dispose();
  68746. this.vars = null;
  68747. // drop references to internal big arrays for the GC
  68748. this._positions = null;
  68749. this._indices = null;
  68750. this._normals = null;
  68751. this._uvs = null;
  68752. this._colors = null;
  68753. this._indices32 = null;
  68754. this._positions32 = null;
  68755. this._normals32 = null;
  68756. this._fixedNormal32 = null;
  68757. this._uvs32 = null;
  68758. this._colors32 = null;
  68759. this.pickedParticles = null;
  68760. };
  68761. /**
  68762. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  68763. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68764. * @returns the SPS.
  68765. */
  68766. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  68767. if (!this._isVisibilityBoxLocked) {
  68768. this.mesh.refreshBoundingInfo();
  68769. }
  68770. return this;
  68771. };
  68772. /**
  68773. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  68774. * @param size the size (float) of the visibility box
  68775. * note : this doesn't lock the SPS mesh bounding box.
  68776. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68777. */
  68778. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  68779. var vis = size / 2;
  68780. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  68781. };
  68782. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  68783. /**
  68784. * Gets whether the SPS as always visible or not
  68785. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68786. */
  68787. get: function () {
  68788. return this._alwaysVisible;
  68789. },
  68790. /**
  68791. * Sets the SPS as always visible or not
  68792. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68793. */
  68794. set: function (val) {
  68795. this._alwaysVisible = val;
  68796. this.mesh.alwaysSelectAsActiveMesh = val;
  68797. },
  68798. enumerable: true,
  68799. configurable: true
  68800. });
  68801. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  68802. /**
  68803. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68804. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68805. */
  68806. get: function () {
  68807. return this._isVisibilityBoxLocked;
  68808. },
  68809. /**
  68810. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68811. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68812. */
  68813. set: function (val) {
  68814. this._isVisibilityBoxLocked = val;
  68815. var boundingInfo = this.mesh.getBoundingInfo();
  68816. boundingInfo.isLocked = val;
  68817. },
  68818. enumerable: true,
  68819. configurable: true
  68820. });
  68821. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  68822. /**
  68823. * Gets if `setParticles()` computes the particle rotations or not.
  68824. * Default value : true. The SPS is faster when it's set to false.
  68825. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68826. */
  68827. get: function () {
  68828. return this._computeParticleRotation;
  68829. },
  68830. /**
  68831. * Tells to `setParticles()` to compute the particle rotations or not.
  68832. * Default value : true. The SPS is faster when it's set to false.
  68833. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68834. */
  68835. set: function (val) {
  68836. this._computeParticleRotation = val;
  68837. },
  68838. enumerable: true,
  68839. configurable: true
  68840. });
  68841. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  68842. /**
  68843. * Gets if `setParticles()` computes the particle colors or not.
  68844. * Default value : true. The SPS is faster when it's set to false.
  68845. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68846. */
  68847. get: function () {
  68848. return this._computeParticleColor;
  68849. },
  68850. /**
  68851. * Tells to `setParticles()` to compute the particle colors or not.
  68852. * Default value : true. The SPS is faster when it's set to false.
  68853. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68854. */
  68855. set: function (val) {
  68856. this._computeParticleColor = val;
  68857. },
  68858. enumerable: true,
  68859. configurable: true
  68860. });
  68861. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  68862. /**
  68863. * Gets if `setParticles()` computes the particle textures or not.
  68864. * Default value : true. The SPS is faster when it's set to false.
  68865. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  68866. */
  68867. get: function () {
  68868. return this._computeParticleTexture;
  68869. },
  68870. set: function (val) {
  68871. this._computeParticleTexture = val;
  68872. },
  68873. enumerable: true,
  68874. configurable: true
  68875. });
  68876. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  68877. /**
  68878. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  68879. * Default value : false. The SPS is faster when it's set to false.
  68880. * Note : the particle custom vertex positions aren't stored values.
  68881. */
  68882. get: function () {
  68883. return this._computeParticleVertex;
  68884. },
  68885. /**
  68886. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  68887. * Default value : false. The SPS is faster when it's set to false.
  68888. * Note : the particle custom vertex positions aren't stored values.
  68889. */
  68890. set: function (val) {
  68891. this._computeParticleVertex = val;
  68892. },
  68893. enumerable: true,
  68894. configurable: true
  68895. });
  68896. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  68897. /**
  68898. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  68899. */
  68900. get: function () {
  68901. return this._computeBoundingBox;
  68902. },
  68903. /**
  68904. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  68905. */
  68906. set: function (val) {
  68907. this._computeBoundingBox = val;
  68908. },
  68909. enumerable: true,
  68910. configurable: true
  68911. });
  68912. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  68913. /**
  68914. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  68915. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68916. * Default : `true`
  68917. */
  68918. get: function () {
  68919. return this._depthSortParticles;
  68920. },
  68921. /**
  68922. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  68923. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  68924. * Default : `true`
  68925. */
  68926. set: function (val) {
  68927. this._depthSortParticles = val;
  68928. },
  68929. enumerable: true,
  68930. configurable: true
  68931. });
  68932. // =======================================================================
  68933. // Particle behavior logic
  68934. // these following methods may be overwritten by the user to fit his needs
  68935. /**
  68936. * This function does nothing. It may be overwritten to set all the particle first values.
  68937. * The SPS doesn't call this function, you may have to call it by your own.
  68938. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68939. */
  68940. SolidParticleSystem.prototype.initParticles = function () {
  68941. };
  68942. /**
  68943. * This function does nothing. It may be overwritten to recycle a particle.
  68944. * The SPS doesn't call this function, you may have to call it by your own.
  68945. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68946. * @param particle The particle to recycle
  68947. * @returns the recycled particle
  68948. */
  68949. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  68950. return particle;
  68951. };
  68952. /**
  68953. * Updates a particle : this function should be overwritten by the user.
  68954. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  68955. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  68956. * @example : just set a particle position or velocity and recycle conditions
  68957. * @param particle The particle to update
  68958. * @returns the updated particle
  68959. */
  68960. SolidParticleSystem.prototype.updateParticle = function (particle) {
  68961. return particle;
  68962. };
  68963. /**
  68964. * Updates a vertex of a particle : it can be overwritten by the user.
  68965. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  68966. * @param particle the current particle
  68967. * @param vertex the current index of the current particle
  68968. * @param pt the index of the current vertex in the particle shape
  68969. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  68970. * @example : just set a vertex particle position
  68971. * @returns the updated vertex
  68972. */
  68973. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  68974. return vertex;
  68975. };
  68976. /**
  68977. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  68978. * This does nothing and may be overwritten by the user.
  68979. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68980. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68981. * @param update the boolean update value actually passed to setParticles()
  68982. */
  68983. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  68984. };
  68985. /**
  68986. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  68987. * This will be passed three parameters.
  68988. * This does nothing and may be overwritten by the user.
  68989. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68990. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  68991. * @param update the boolean update value actually passed to setParticles()
  68992. */
  68993. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  68994. };
  68995. return SolidParticleSystem;
  68996. }());
  68997. BABYLON.SolidParticleSystem = SolidParticleSystem;
  68998. })(BABYLON || (BABYLON = {}));
  68999. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  69000. var BABYLON;
  69001. (function (BABYLON) {
  69002. /**
  69003. * Class containing static functions to help procedurally build meshes
  69004. */
  69005. var MeshBuilder = /** @class */ (function () {
  69006. function MeshBuilder() {
  69007. }
  69008. MeshBuilder.updateSideOrientation = function (orientation) {
  69009. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  69010. return BABYLON.Mesh.DOUBLESIDE;
  69011. }
  69012. if (orientation === undefined || orientation === null) {
  69013. return BABYLON.Mesh.FRONTSIDE;
  69014. }
  69015. return orientation;
  69016. };
  69017. /**
  69018. * Creates a box mesh
  69019. * * The parameter `size` sets the size (float) of each box side (default 1)
  69020. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  69021. * * 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)
  69022. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69023. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69024. * * 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
  69025. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69026. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  69027. * @param name defines the name of the mesh
  69028. * @param options defines the options used to create the mesh
  69029. * @param scene defines the hosting scene
  69030. * @returns the box mesh
  69031. */
  69032. MeshBuilder.CreateBox = function (name, options, scene) {
  69033. if (scene === void 0) { scene = null; }
  69034. var box = new BABYLON.Mesh(name, scene);
  69035. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69036. box._originalBuilderSideOrientation = options.sideOrientation;
  69037. var vertexData = BABYLON.VertexData.CreateBox(options);
  69038. vertexData.applyToMesh(box, options.updatable);
  69039. return box;
  69040. };
  69041. /**
  69042. * Creates a sphere mesh
  69043. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  69044. * * 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 of `diameter`)
  69045. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  69046. * * 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
  69047. * * 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)
  69048. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69049. * * 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
  69050. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69051. * @param name defines the name of the mesh
  69052. * @param options defines the options used to create the mesh
  69053. * @param scene defines the hosting scene
  69054. * @returns the sphere mesh
  69055. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  69056. */
  69057. MeshBuilder.CreateSphere = function (name, options, scene) {
  69058. var sphere = new BABYLON.Mesh(name, scene);
  69059. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69060. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69061. var vertexData = BABYLON.VertexData.CreateSphere(options);
  69062. vertexData.applyToMesh(sphere, options.updatable);
  69063. return sphere;
  69064. };
  69065. /**
  69066. * Creates a plane polygonal mesh. By default, this is a disc
  69067. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  69068. * * 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
  69069. * * 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
  69070. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69071. * * 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
  69072. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69073. * @param name defines the name of the mesh
  69074. * @param options defines the options used to create the mesh
  69075. * @param scene defines the hosting scene
  69076. * @returns the plane polygonal mesh
  69077. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  69078. */
  69079. MeshBuilder.CreateDisc = function (name, options, scene) {
  69080. if (scene === void 0) { scene = null; }
  69081. var disc = new BABYLON.Mesh(name, scene);
  69082. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69083. disc._originalBuilderSideOrientation = options.sideOrientation;
  69084. var vertexData = BABYLON.VertexData.CreateDisc(options);
  69085. vertexData.applyToMesh(disc, options.updatable);
  69086. return disc;
  69087. };
  69088. /**
  69089. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  69090. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  69091. * * 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 of `radius`)
  69092. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  69093. * * 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
  69094. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69095. * * 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
  69096. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69097. * @param name defines the name of the mesh
  69098. * @param options defines the options used to create the mesh
  69099. * @param scene defines the hosting scene
  69100. * @returns the icosahedron mesh
  69101. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  69102. */
  69103. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69104. var sphere = new BABYLON.Mesh(name, scene);
  69105. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69106. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69107. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  69108. vertexData.applyToMesh(sphere, options.updatable);
  69109. return sphere;
  69110. };
  69111. /**
  69112. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69113. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  69114. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  69115. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  69116. * * 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
  69117. * * 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
  69118. * * 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
  69119. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69120. * * 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
  69121. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69122. * * 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
  69123. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  69124. * * 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
  69125. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  69126. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69127. * @param name defines the name of the mesh
  69128. * @param options defines the options used to create the mesh
  69129. * @param scene defines the hosting scene
  69130. * @returns the ribbon mesh
  69131. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  69132. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69133. */
  69134. MeshBuilder.CreateRibbon = function (name, options, scene) {
  69135. if (scene === void 0) { scene = null; }
  69136. var pathArray = options.pathArray;
  69137. var closeArray = options.closeArray;
  69138. var closePath = options.closePath;
  69139. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69140. var instance = options.instance;
  69141. var updatable = options.updatable;
  69142. if (instance) { // existing ribbon instance update
  69143. // positionFunction : ribbon case
  69144. // only pathArray and sideOrientation parameters are taken into account for positions update
  69145. var minimum_1 = BABYLON.Tmp.Vector3[0].setAll(Number.MAX_VALUE);
  69146. var maximum_1 = BABYLON.Tmp.Vector3[1].setAll(-Number.MAX_VALUE);
  69147. var positionFunction = function (positions) {
  69148. var minlg = pathArray[0].length;
  69149. var mesh = instance;
  69150. var i = 0;
  69151. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  69152. for (var si = 1; si <= ns; ++si) {
  69153. for (var p = 0; p < pathArray.length; ++p) {
  69154. var path = pathArray[p];
  69155. var l = path.length;
  69156. minlg = (minlg < l) ? minlg : l;
  69157. for (var j = 0; j < minlg; ++j) {
  69158. var pathPoint = path[j];
  69159. positions[i] = pathPoint.x;
  69160. positions[i + 1] = pathPoint.y;
  69161. positions[i + 2] = pathPoint.z;
  69162. minimum_1.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69163. maximum_1.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69164. i += 3;
  69165. }
  69166. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  69167. var pathPoint = path[0];
  69168. positions[i] = pathPoint.x;
  69169. positions[i + 1] = pathPoint.y;
  69170. positions[i + 2] = pathPoint.z;
  69171. i += 3;
  69172. }
  69173. }
  69174. }
  69175. };
  69176. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69177. positionFunction(positions);
  69178. if (instance._boundingInfo) {
  69179. instance._boundingInfo.reConstruct(minimum_1, maximum_1, instance._worldMatrix);
  69180. }
  69181. else {
  69182. instance._boundingInfo = new BABYLON.BoundingInfo(minimum_1, maximum_1, instance._worldMatrix);
  69183. }
  69184. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69185. if (options.colors) {
  69186. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69187. for (var c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {
  69188. var color = options.colors[c];
  69189. colors[colorIndex] = color.r;
  69190. colors[colorIndex + 1] = color.g;
  69191. colors[colorIndex + 2] = color.b;
  69192. colors[colorIndex + 3] = color.a;
  69193. }
  69194. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  69195. }
  69196. if (options.uvs) {
  69197. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69198. for (var i = 0; i < options.uvs.length; i++) {
  69199. uvs[i * 2] = options.uvs[i].x;
  69200. uvs[i * 2 + 1] = options.uvs[i].y;
  69201. }
  69202. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  69203. }
  69204. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  69205. var indices = instance.getIndices();
  69206. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69207. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  69208. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  69209. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  69210. var indexFirst = 0;
  69211. var indexLast = 0;
  69212. for (var p = 0; p < pathArray.length; p++) {
  69213. indexFirst = instance._creationDataStorage.idx[p] * 3;
  69214. if (p + 1 < pathArray.length) {
  69215. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  69216. }
  69217. else {
  69218. indexLast = normals.length - 3;
  69219. }
  69220. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  69221. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  69222. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  69223. normals[indexLast] = normals[indexFirst];
  69224. normals[indexLast + 1] = normals[indexFirst + 1];
  69225. normals[indexLast + 2] = normals[indexFirst + 2];
  69226. }
  69227. }
  69228. if (!(instance.areNormalsFrozen)) {
  69229. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  69230. }
  69231. }
  69232. return instance;
  69233. }
  69234. else { // new ribbon creation
  69235. var ribbon = new BABYLON.Mesh(name, scene);
  69236. ribbon._originalBuilderSideOrientation = sideOrientation;
  69237. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  69238. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  69239. if (closePath) {
  69240. ribbon._creationDataStorage.idx = vertexData._idx;
  69241. }
  69242. ribbon._creationDataStorage.closePath = closePath;
  69243. ribbon._creationDataStorage.closeArray = closeArray;
  69244. vertexData.applyToMesh(ribbon, updatable);
  69245. return ribbon;
  69246. }
  69247. };
  69248. /**
  69249. * Creates a cylinder or a cone mesh
  69250. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  69251. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  69252. * * 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.
  69253. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  69254. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  69255. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  69256. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  69257. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  69258. * * 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).
  69259. * * 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
  69260. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  69261. * * 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
  69262. * * 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.
  69263. * * If `enclose` is false, a ring surface is one element.
  69264. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  69265. * * 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
  69266. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69267. * * 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
  69268. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69269. * @param name defines the name of the mesh
  69270. * @param options defines the options used to create the mesh
  69271. * @param scene defines the hosting scene
  69272. * @returns the cylinder mesh
  69273. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  69274. */
  69275. MeshBuilder.CreateCylinder = function (name, options, scene) {
  69276. var cylinder = new BABYLON.Mesh(name, scene);
  69277. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69278. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  69279. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  69280. vertexData.applyToMesh(cylinder, options.updatable);
  69281. return cylinder;
  69282. };
  69283. /**
  69284. * Creates a torus mesh
  69285. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  69286. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  69287. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  69288. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69289. * * 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
  69290. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69291. * @param name defines the name of the mesh
  69292. * @param options defines the options used to create the mesh
  69293. * @param scene defines the hosting scene
  69294. * @returns the torus mesh
  69295. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  69296. */
  69297. MeshBuilder.CreateTorus = function (name, options, scene) {
  69298. var torus = new BABYLON.Mesh(name, scene);
  69299. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69300. torus._originalBuilderSideOrientation = options.sideOrientation;
  69301. var vertexData = BABYLON.VertexData.CreateTorus(options);
  69302. vertexData.applyToMesh(torus, options.updatable);
  69303. return torus;
  69304. };
  69305. /**
  69306. * Creates a torus knot mesh
  69307. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  69308. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  69309. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  69310. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  69311. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69312. * * 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
  69313. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69314. * @param name defines the name of the mesh
  69315. * @param options defines the options used to create the mesh
  69316. * @param scene defines the hosting scene
  69317. * @returns the torus knot mesh
  69318. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  69319. */
  69320. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  69321. var torusKnot = new BABYLON.Mesh(name, scene);
  69322. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69323. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  69324. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  69325. vertexData.applyToMesh(torusKnot, options.updatable);
  69326. return torusKnot;
  69327. };
  69328. /**
  69329. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  69330. * * 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
  69331. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  69332. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  69333. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  69334. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  69335. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  69336. * * 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
  69337. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  69338. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69339. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  69340. * @param name defines the name of the new line system
  69341. * @param options defines the options used to create the line system
  69342. * @param scene defines the hosting scene
  69343. * @returns a new line system mesh
  69344. */
  69345. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  69346. var instance = options.instance;
  69347. var lines = options.lines;
  69348. var colors = options.colors;
  69349. if (instance) { // lines update
  69350. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69351. var vertexColor;
  69352. var lineColors;
  69353. if (colors) {
  69354. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69355. }
  69356. var i = 0;
  69357. var c = 0;
  69358. for (var l = 0; l < lines.length; l++) {
  69359. var points = lines[l];
  69360. for (var p = 0; p < points.length; p++) {
  69361. positions[i] = points[p].x;
  69362. positions[i + 1] = points[p].y;
  69363. positions[i + 2] = points[p].z;
  69364. if (colors && vertexColor) {
  69365. lineColors = colors[l];
  69366. vertexColor[c] = lineColors[p].r;
  69367. vertexColor[c + 1] = lineColors[p].g;
  69368. vertexColor[c + 2] = lineColors[p].b;
  69369. vertexColor[c + 3] = lineColors[p].a;
  69370. c += 4;
  69371. }
  69372. i += 3;
  69373. }
  69374. }
  69375. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69376. if (colors && vertexColor) {
  69377. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  69378. }
  69379. return instance;
  69380. }
  69381. // line system creation
  69382. var useVertexColor = (colors) ? true : false;
  69383. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  69384. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  69385. vertexData.applyToMesh(lineSystem, options.updatable);
  69386. return lineSystem;
  69387. };
  69388. /**
  69389. * Creates a line mesh
  69390. * 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
  69391. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69392. * * The parameter `points` is an array successive Vector3
  69393. * * 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
  69394. * * The optional parameter `colors` is an array of successive Color4, one per line point
  69395. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  69396. * * When updating an instance, remember that only point positions can change, not the number of points
  69397. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69398. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  69399. * @param name defines the name of the new line system
  69400. * @param options defines the options used to create the line system
  69401. * @param scene defines the hosting scene
  69402. * @returns a new line mesh
  69403. */
  69404. MeshBuilder.CreateLines = function (name, options, scene) {
  69405. if (scene === void 0) { scene = null; }
  69406. var colors = (options.colors) ? [options.colors] : null;
  69407. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  69408. return lines;
  69409. };
  69410. /**
  69411. * Creates a dashed line mesh
  69412. * * 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
  69413. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69414. * * The parameter `points` is an array successive Vector3
  69415. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  69416. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  69417. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  69418. * * 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
  69419. * * When updating an instance, remember that only point positions can change, not the number of points
  69420. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69421. * @param name defines the name of the mesh
  69422. * @param options defines the options used to create the mesh
  69423. * @param scene defines the hosting scene
  69424. * @returns the dashed line mesh
  69425. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  69426. */
  69427. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  69428. if (scene === void 0) { scene = null; }
  69429. var points = options.points;
  69430. var instance = options.instance;
  69431. var gapSize = options.gapSize || 1;
  69432. var dashSize = options.dashSize || 3;
  69433. if (instance) { // dashed lines update
  69434. var positionFunction = function (positions) {
  69435. var curvect = BABYLON.Vector3.Zero();
  69436. var nbSeg = positions.length / 6;
  69437. var lg = 0;
  69438. var nb = 0;
  69439. var shft = 0;
  69440. var dashshft = 0;
  69441. var curshft = 0;
  69442. var p = 0;
  69443. var i = 0;
  69444. var j = 0;
  69445. for (i = 0; i < points.length - 1; i++) {
  69446. points[i + 1].subtractToRef(points[i], curvect);
  69447. lg += curvect.length();
  69448. }
  69449. shft = lg / nbSeg;
  69450. var dashSize = instance._creationDataStorage.dashSize;
  69451. var gapSize = instance._creationDataStorage.gapSize;
  69452. dashshft = dashSize * shft / (dashSize + gapSize);
  69453. for (i = 0; i < points.length - 1; i++) {
  69454. points[i + 1].subtractToRef(points[i], curvect);
  69455. nb = Math.floor(curvect.length() / shft);
  69456. curvect.normalize();
  69457. j = 0;
  69458. while (j < nb && p < positions.length) {
  69459. curshft = shft * j;
  69460. positions[p] = points[i].x + curshft * curvect.x;
  69461. positions[p + 1] = points[i].y + curshft * curvect.y;
  69462. positions[p + 2] = points[i].z + curshft * curvect.z;
  69463. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  69464. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  69465. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  69466. p += 6;
  69467. j++;
  69468. }
  69469. }
  69470. while (p < positions.length) {
  69471. positions[p] = points[i].x;
  69472. positions[p + 1] = points[i].y;
  69473. positions[p + 2] = points[i].z;
  69474. p += 3;
  69475. }
  69476. };
  69477. instance.updateMeshPositions(positionFunction, false);
  69478. return instance;
  69479. }
  69480. // dashed lines creation
  69481. var dashedLines = new BABYLON.LinesMesh(name, scene);
  69482. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  69483. vertexData.applyToMesh(dashedLines, options.updatable);
  69484. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  69485. dashedLines._creationDataStorage.dashSize = dashSize;
  69486. dashedLines._creationDataStorage.gapSize = gapSize;
  69487. return dashedLines;
  69488. };
  69489. /**
  69490. * 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.
  69491. * * 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.
  69492. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69493. * * 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.
  69494. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  69495. * * 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
  69496. * * 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
  69497. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  69498. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69499. * * 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
  69500. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  69501. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69502. * @param name defines the name of the mesh
  69503. * @param options defines the options used to create the mesh
  69504. * @param scene defines the hosting scene
  69505. * @returns the extruded shape mesh
  69506. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69507. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69508. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69509. */
  69510. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  69511. if (scene === void 0) { scene = null; }
  69512. var path = options.path;
  69513. var shape = options.shape;
  69514. var scale = options.scale || 1;
  69515. var rotation = options.rotation || 0;
  69516. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69517. var updatable = options.updatable;
  69518. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69519. var instance = options.instance || null;
  69520. var invertUV = options.invertUV || false;
  69521. 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);
  69522. };
  69523. /**
  69524. * Creates an custom extruded shape mesh.
  69525. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  69526. * * 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.
  69527. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69528. * * 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
  69529. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  69530. * * 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
  69531. * * It must returns a float value that will be the scale value applied to the shape on each path point
  69532. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  69533. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  69534. * * 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
  69535. * * 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
  69536. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  69537. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69538. * * 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
  69539. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69540. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69541. * @param name defines the name of the mesh
  69542. * @param options defines the options used to create the mesh
  69543. * @param scene defines the hosting scene
  69544. * @returns the custom extruded shape mesh
  69545. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  69546. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69547. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69548. */
  69549. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  69550. var path = options.path;
  69551. var shape = options.shape;
  69552. var scaleFunction = options.scaleFunction || (function () { return 1; });
  69553. var rotationFunction = options.rotationFunction || (function () { return 0; });
  69554. var ribbonCloseArray = options.ribbonCloseArray || false;
  69555. var ribbonClosePath = options.ribbonClosePath || false;
  69556. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69557. var updatable = options.updatable;
  69558. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69559. var instance = options.instance;
  69560. var invertUV = options.invertUV || false;
  69561. 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);
  69562. };
  69563. /**
  69564. * Creates lathe mesh.
  69565. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  69566. * * 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
  69567. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  69568. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  69569. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  69570. * * 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
  69571. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  69572. * * 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
  69573. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69574. * * 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
  69575. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69576. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69577. * @param name defines the name of the mesh
  69578. * @param options defines the options used to create the mesh
  69579. * @param scene defines the hosting scene
  69580. * @returns the lathe mesh
  69581. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  69582. */
  69583. MeshBuilder.CreateLathe = function (name, options, scene) {
  69584. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  69585. var closed = (options.closed === undefined) ? true : options.closed;
  69586. var shape = options.shape;
  69587. var radius = options.radius || 1;
  69588. var tessellation = options.tessellation || 64;
  69589. var clip = options.clip || 0;
  69590. var updatable = options.updatable;
  69591. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69592. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69593. var pi2 = Math.PI * 2;
  69594. var paths = new Array();
  69595. var invertUV = options.invertUV || false;
  69596. var i = 0;
  69597. var p = 0;
  69598. var step = pi2 / tessellation * arc;
  69599. var rotated;
  69600. var path = new Array();
  69601. for (i = 0; i <= tessellation - clip; i++) {
  69602. var path = [];
  69603. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  69604. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  69605. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  69606. }
  69607. for (p = 0; p < shape.length; p++) {
  69608. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  69609. path.push(rotated);
  69610. }
  69611. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  69612. 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));
  69613. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  69614. }
  69615. paths.push(path);
  69616. }
  69617. // lathe ribbon
  69618. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69619. return lathe;
  69620. };
  69621. /**
  69622. * Creates a plane mesh
  69623. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  69624. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  69625. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  69626. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69627. * * 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
  69628. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69629. * @param name defines the name of the mesh
  69630. * @param options defines the options used to create the mesh
  69631. * @param scene defines the hosting scene
  69632. * @returns the plane mesh
  69633. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69634. */
  69635. MeshBuilder.CreatePlane = function (name, options, scene) {
  69636. var plane = new BABYLON.Mesh(name, scene);
  69637. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69638. plane._originalBuilderSideOrientation = options.sideOrientation;
  69639. var vertexData = BABYLON.VertexData.CreatePlane(options);
  69640. vertexData.applyToMesh(plane, options.updatable);
  69641. if (options.sourcePlane) {
  69642. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  69643. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  69644. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  69645. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  69646. plane.rotate(vectorProduct, product);
  69647. }
  69648. }
  69649. return plane;
  69650. };
  69651. /**
  69652. * Creates a ground mesh
  69653. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  69654. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  69655. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69656. * @param name defines the name of the mesh
  69657. * @param options defines the options used to create the mesh
  69658. * @param scene defines the hosting scene
  69659. * @returns the ground mesh
  69660. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69661. */
  69662. MeshBuilder.CreateGround = function (name, options, scene) {
  69663. var ground = new BABYLON.GroundMesh(name, scene);
  69664. ground._setReady(false);
  69665. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  69666. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  69667. ground._width = options.width || 1;
  69668. ground._height = options.height || 1;
  69669. ground._maxX = ground._width / 2;
  69670. ground._maxZ = ground._height / 2;
  69671. ground._minX = -ground._maxX;
  69672. ground._minZ = -ground._maxZ;
  69673. var vertexData = BABYLON.VertexData.CreateGround(options);
  69674. vertexData.applyToMesh(ground, options.updatable);
  69675. ground._setReady(true);
  69676. return ground;
  69677. };
  69678. /**
  69679. * Creates a tiled ground mesh
  69680. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  69681. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  69682. * * 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
  69683. * * 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
  69684. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69685. * @param name defines the name of the mesh
  69686. * @param options defines the options used to create the mesh
  69687. * @param scene defines the hosting scene
  69688. * @returns the tiled ground mesh
  69689. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  69690. */
  69691. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  69692. var tiledGround = new BABYLON.Mesh(name, scene);
  69693. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  69694. vertexData.applyToMesh(tiledGround, options.updatable);
  69695. return tiledGround;
  69696. };
  69697. /**
  69698. * Creates a ground mesh from a height map
  69699. * * The parameter `url` sets the URL of the height map image resource.
  69700. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  69701. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  69702. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  69703. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  69704. * * 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.
  69705. * * 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).
  69706. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  69707. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69708. * @param name defines the name of the mesh
  69709. * @param url defines the url to the height map
  69710. * @param options defines the options used to create the mesh
  69711. * @param scene defines the hosting scene
  69712. * @returns the ground mesh
  69713. * @see http://doc.babylonjs.com/babylon101/height_map
  69714. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  69715. */
  69716. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  69717. var width = options.width || 10.0;
  69718. var height = options.height || 10.0;
  69719. var subdivisions = options.subdivisions || 1 | 0;
  69720. var minHeight = options.minHeight || 0.0;
  69721. var maxHeight = options.maxHeight || 1.0;
  69722. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  69723. var alphaFilter = options.alphaFilter || 0.0;
  69724. var updatable = options.updatable;
  69725. var onReady = options.onReady;
  69726. var ground = new BABYLON.GroundMesh(name, scene);
  69727. ground._subdivisionsX = subdivisions;
  69728. ground._subdivisionsY = subdivisions;
  69729. ground._width = width;
  69730. ground._height = height;
  69731. ground._maxX = ground._width / 2.0;
  69732. ground._maxZ = ground._height / 2.0;
  69733. ground._minX = -ground._maxX;
  69734. ground._minZ = -ground._maxZ;
  69735. ground._setReady(false);
  69736. var onload = function (img) {
  69737. // Getting height map data
  69738. var canvas = document.createElement("canvas");
  69739. var context = canvas.getContext("2d");
  69740. if (!context) {
  69741. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  69742. }
  69743. if (scene.isDisposed) {
  69744. return;
  69745. }
  69746. var bufferWidth = img.width;
  69747. var bufferHeight = img.height;
  69748. canvas.width = bufferWidth;
  69749. canvas.height = bufferHeight;
  69750. context.drawImage(img, 0, 0);
  69751. // Create VertexData from map data
  69752. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  69753. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  69754. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  69755. width: width, height: height,
  69756. subdivisions: subdivisions,
  69757. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  69758. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  69759. alphaFilter: alphaFilter
  69760. });
  69761. vertexData.applyToMesh(ground, updatable);
  69762. //execute ready callback, if set
  69763. if (onReady) {
  69764. onReady(ground);
  69765. }
  69766. ground._setReady(true);
  69767. };
  69768. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  69769. return ground;
  69770. };
  69771. /**
  69772. * Creates a polygon mesh
  69773. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  69774. * * 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
  69775. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69776. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69777. * * 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)
  69778. * * Remember you can only change the shape positions, not their number when updating a polygon
  69779. * @param name defines the name of the mesh
  69780. * @param options defines the options used to create the mesh
  69781. * @param scene defines the hosting scene
  69782. * @returns the polygon mesh
  69783. */
  69784. MeshBuilder.CreatePolygon = function (name, options, scene) {
  69785. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69786. var shape = options.shape;
  69787. var holes = options.holes || [];
  69788. var depth = options.depth || 0;
  69789. var contours = [];
  69790. var hole = [];
  69791. for (var i = 0; i < shape.length; i++) {
  69792. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  69793. }
  69794. var epsilon = 0.00000001;
  69795. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  69796. contours.pop();
  69797. }
  69798. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  69799. for (var hNb = 0; hNb < holes.length; hNb++) {
  69800. hole = [];
  69801. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  69802. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  69803. }
  69804. polygonTriangulation.addHole(hole);
  69805. }
  69806. var polygon = polygonTriangulation.build(options.updatable, depth);
  69807. polygon._originalBuilderSideOrientation = options.sideOrientation;
  69808. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  69809. vertexData.applyToMesh(polygon, options.updatable);
  69810. return polygon;
  69811. };
  69812. /**
  69813. * Creates an extruded polygon mesh, with depth in the Y direction.
  69814. * * 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)
  69815. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69816. * @param name defines the name of the mesh
  69817. * @param options defines the options used to create the mesh
  69818. * @param scene defines the hosting scene
  69819. * @returns the polygon mesh
  69820. */
  69821. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  69822. return MeshBuilder.CreatePolygon(name, options, scene);
  69823. };
  69824. /**
  69825. * Creates a tube mesh.
  69826. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69827. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  69828. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  69829. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  69830. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  69831. * * 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)
  69832. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  69833. * * 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
  69834. * * 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
  69835. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69836. * * 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
  69837. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69838. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69839. * @param name defines the name of the mesh
  69840. * @param options defines the options used to create the mesh
  69841. * @param scene defines the hosting scene
  69842. * @returns the tube mesh
  69843. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69844. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  69845. */
  69846. MeshBuilder.CreateTube = function (name, options, scene) {
  69847. var path = options.path;
  69848. var instance = options.instance;
  69849. var radius = 1.0;
  69850. if (options.radius !== undefined) {
  69851. radius = options.radius;
  69852. }
  69853. else if (instance) {
  69854. radius = instance._creationDataStorage.radius;
  69855. }
  69856. var tessellation = options.tessellation || 64 | 0;
  69857. var radiusFunction = options.radiusFunction || null;
  69858. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69859. var invertUV = options.invertUV || false;
  69860. var updatable = options.updatable;
  69861. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69862. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  69863. // tube geometry
  69864. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  69865. var tangents = path3D.getTangents();
  69866. var normals = path3D.getNormals();
  69867. var distances = path3D.getDistances();
  69868. var pi2 = Math.PI * 2;
  69869. var step = pi2 / tessellation * arc;
  69870. var returnRadius = function () { return radius; };
  69871. var radiusFunctionFinal = radiusFunction || returnRadius;
  69872. var circlePath;
  69873. var rad;
  69874. var normal;
  69875. var rotated;
  69876. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69877. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69878. for (var i = 0; i < path.length; i++) {
  69879. rad = radiusFunctionFinal(i, distances[i]); // current radius
  69880. circlePath = Array(); // current circle array
  69881. normal = normals[i]; // current normal
  69882. for (var t = 0; t < tessellation; t++) {
  69883. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  69884. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  69885. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  69886. rotated.scaleInPlace(rad).addInPlace(path[i]);
  69887. circlePath[t] = rotated;
  69888. }
  69889. circlePaths[index] = circlePath;
  69890. index++;
  69891. }
  69892. // cap
  69893. var capPath = function (nbPoints, pathIndex) {
  69894. var pointCap = Array();
  69895. for (var i = 0; i < nbPoints; i++) {
  69896. pointCap.push(path[pathIndex]);
  69897. }
  69898. return pointCap;
  69899. };
  69900. switch (cap) {
  69901. case BABYLON.Mesh.NO_CAP:
  69902. break;
  69903. case BABYLON.Mesh.CAP_START:
  69904. circlePaths[0] = capPath(tessellation, 0);
  69905. circlePaths[1] = circlePaths[2].slice(0);
  69906. break;
  69907. case BABYLON.Mesh.CAP_END:
  69908. circlePaths[index] = circlePaths[index - 1].slice(0);
  69909. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69910. break;
  69911. case BABYLON.Mesh.CAP_ALL:
  69912. circlePaths[0] = capPath(tessellation, 0);
  69913. circlePaths[1] = circlePaths[2].slice(0);
  69914. circlePaths[index] = circlePaths[index - 1].slice(0);
  69915. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  69916. break;
  69917. default:
  69918. break;
  69919. }
  69920. return circlePaths;
  69921. };
  69922. var path3D;
  69923. var pathArray;
  69924. if (instance) { // tube update
  69925. var storage = instance._creationDataStorage;
  69926. var arc = options.arc || storage.arc;
  69927. path3D = storage.path3D.update(path);
  69928. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  69929. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  69930. // Update mode, no need to recreate the storage.
  69931. storage.path3D = path3D;
  69932. storage.pathArray = pathArray;
  69933. storage.arc = arc;
  69934. storage.radius = radius;
  69935. return instance;
  69936. }
  69937. // tube creation
  69938. path3D = new BABYLON.Path3D(path);
  69939. var newPathArray = new Array();
  69940. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69941. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  69942. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69943. tube._creationDataStorage.pathArray = pathArray;
  69944. tube._creationDataStorage.path3D = path3D;
  69945. tube._creationDataStorage.tessellation = tessellation;
  69946. tube._creationDataStorage.cap = cap;
  69947. tube._creationDataStorage.arc = options.arc;
  69948. tube._creationDataStorage.radius = radius;
  69949. return tube;
  69950. };
  69951. /**
  69952. * Creates a polyhedron mesh
  69953. * * 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
  69954. * * The parameter `size` (positive float, default 1) sets the polygon size
  69955. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  69956. * * 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`
  69957. * * 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
  69958. * * 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)`)
  69959. * * 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
  69960. * * 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
  69961. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69962. * * 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
  69963. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69964. * @param name defines the name of the mesh
  69965. * @param options defines the options used to create the mesh
  69966. * @param scene defines the hosting scene
  69967. * @returns the polyhedron mesh
  69968. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  69969. */
  69970. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  69971. var polyhedron = new BABYLON.Mesh(name, scene);
  69972. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69973. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  69974. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  69975. vertexData.applyToMesh(polyhedron, options.updatable);
  69976. return polyhedron;
  69977. };
  69978. /**
  69979. * Creates a decal mesh.
  69980. * 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
  69981. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  69982. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  69983. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  69984. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  69985. * @param name defines the name of the mesh
  69986. * @param sourceMesh defines the mesh where the decal must be applied
  69987. * @param options defines the options used to create the mesh
  69988. * @param scene defines the hosting scene
  69989. * @returns the decal mesh
  69990. * @see http://doc.babylonjs.com/how_to/decals
  69991. */
  69992. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  69993. var indices = sourceMesh.getIndices();
  69994. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69995. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69996. var position = options.position || BABYLON.Vector3.Zero();
  69997. var normal = options.normal || BABYLON.Vector3.Up();
  69998. var size = options.size || BABYLON.Vector3.One();
  69999. var angle = options.angle || 0;
  70000. // Getting correct rotation
  70001. if (!normal) {
  70002. var target = new BABYLON.Vector3(0, 0, 1);
  70003. var camera = sourceMesh.getScene().activeCamera;
  70004. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  70005. normal = camera.globalPosition.subtract(cameraWorldTarget);
  70006. }
  70007. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  70008. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  70009. var pitch = Math.atan2(normal.y, len);
  70010. // Matrix
  70011. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  70012. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  70013. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  70014. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  70015. var vertexData = new BABYLON.VertexData();
  70016. vertexData.indices = [];
  70017. vertexData.positions = [];
  70018. vertexData.normals = [];
  70019. vertexData.uvs = [];
  70020. var currentVertexDataIndex = 0;
  70021. var extractDecalVector3 = function (indexId) {
  70022. var result = new BABYLON.PositionNormalVertex();
  70023. if (!indices || !positions || !normals) {
  70024. return result;
  70025. }
  70026. var vertexId = indices[indexId];
  70027. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  70028. // Send vector to decal local world
  70029. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  70030. // Get normal
  70031. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  70032. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  70033. return result;
  70034. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  70035. var clip = function (vertices, axis) {
  70036. if (vertices.length === 0) {
  70037. return vertices;
  70038. }
  70039. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  70040. var clipVertices = function (v0, v1) {
  70041. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  70042. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  70043. };
  70044. var result = new Array();
  70045. for (var index = 0; index < vertices.length; index += 3) {
  70046. var v1Out;
  70047. var v2Out;
  70048. var v3Out;
  70049. var total = 0;
  70050. var nV1 = null;
  70051. var nV2 = null;
  70052. var nV3 = null;
  70053. var nV4 = null;
  70054. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  70055. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  70056. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  70057. v1Out = d1 > 0;
  70058. v2Out = d2 > 0;
  70059. v3Out = d3 > 0;
  70060. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  70061. switch (total) {
  70062. case 0:
  70063. result.push(vertices[index]);
  70064. result.push(vertices[index + 1]);
  70065. result.push(vertices[index + 2]);
  70066. break;
  70067. case 1:
  70068. if (v1Out) {
  70069. nV1 = vertices[index + 1];
  70070. nV2 = vertices[index + 2];
  70071. nV3 = clipVertices(vertices[index], nV1);
  70072. nV4 = clipVertices(vertices[index], nV2);
  70073. }
  70074. if (v2Out) {
  70075. nV1 = vertices[index];
  70076. nV2 = vertices[index + 2];
  70077. nV3 = clipVertices(vertices[index + 1], nV1);
  70078. nV4 = clipVertices(vertices[index + 1], nV2);
  70079. result.push(nV3);
  70080. result.push(nV2.clone());
  70081. result.push(nV1.clone());
  70082. result.push(nV2.clone());
  70083. result.push(nV3.clone());
  70084. result.push(nV4);
  70085. break;
  70086. }
  70087. if (v3Out) {
  70088. nV1 = vertices[index];
  70089. nV2 = vertices[index + 1];
  70090. nV3 = clipVertices(vertices[index + 2], nV1);
  70091. nV4 = clipVertices(vertices[index + 2], nV2);
  70092. }
  70093. if (nV1 && nV2 && nV3 && nV4) {
  70094. result.push(nV1.clone());
  70095. result.push(nV2.clone());
  70096. result.push(nV3);
  70097. result.push(nV4);
  70098. result.push(nV3.clone());
  70099. result.push(nV2.clone());
  70100. }
  70101. break;
  70102. case 2:
  70103. if (!v1Out) {
  70104. nV1 = vertices[index].clone();
  70105. nV2 = clipVertices(nV1, vertices[index + 1]);
  70106. nV3 = clipVertices(nV1, vertices[index + 2]);
  70107. result.push(nV1);
  70108. result.push(nV2);
  70109. result.push(nV3);
  70110. }
  70111. if (!v2Out) {
  70112. nV1 = vertices[index + 1].clone();
  70113. nV2 = clipVertices(nV1, vertices[index + 2]);
  70114. nV3 = clipVertices(nV1, vertices[index]);
  70115. result.push(nV1);
  70116. result.push(nV2);
  70117. result.push(nV3);
  70118. }
  70119. if (!v3Out) {
  70120. nV1 = vertices[index + 2].clone();
  70121. nV2 = clipVertices(nV1, vertices[index]);
  70122. nV3 = clipVertices(nV1, vertices[index + 1]);
  70123. result.push(nV1);
  70124. result.push(nV2);
  70125. result.push(nV3);
  70126. }
  70127. break;
  70128. case 3:
  70129. break;
  70130. }
  70131. }
  70132. return result;
  70133. };
  70134. for (var index = 0; index < indices.length; index += 3) {
  70135. var faceVertices = new Array();
  70136. faceVertices.push(extractDecalVector3(index));
  70137. faceVertices.push(extractDecalVector3(index + 1));
  70138. faceVertices.push(extractDecalVector3(index + 2));
  70139. // Clip
  70140. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  70141. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  70142. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  70143. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  70144. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  70145. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  70146. if (faceVertices.length === 0) {
  70147. continue;
  70148. }
  70149. // Add UVs and get back to world
  70150. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  70151. var vertex = faceVertices[vIndex];
  70152. //TODO check for Int32Array | Uint32Array | Uint16Array
  70153. vertexData.indices.push(currentVertexDataIndex);
  70154. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  70155. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  70156. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  70157. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  70158. currentVertexDataIndex++;
  70159. }
  70160. }
  70161. // Return mesh
  70162. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  70163. vertexData.applyToMesh(decal);
  70164. decal.position = position.clone();
  70165. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  70166. return decal;
  70167. };
  70168. // Privates
  70169. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  70170. // extrusion geometry
  70171. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  70172. var tangents = path3D.getTangents();
  70173. var normals = path3D.getNormals();
  70174. var binormals = path3D.getBinormals();
  70175. var distances = path3D.getDistances();
  70176. var angle = 0;
  70177. var returnScale = function () { return scale !== null ? scale : 1; };
  70178. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  70179. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  70180. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  70181. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70182. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70183. for (var i = 0; i < curve.length; i++) {
  70184. var shapePath = new Array();
  70185. var angleStep = rotate(i, distances[i]);
  70186. var scaleRatio = scl(i, distances[i]);
  70187. for (var p = 0; p < shape.length; p++) {
  70188. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  70189. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  70190. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  70191. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  70192. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  70193. shapePath[p] = rotated;
  70194. }
  70195. shapePaths[index] = shapePath;
  70196. angle += angleStep;
  70197. index++;
  70198. }
  70199. // cap
  70200. var capPath = function (shapePath) {
  70201. var pointCap = Array();
  70202. var barycenter = BABYLON.Vector3.Zero();
  70203. var i;
  70204. for (i = 0; i < shapePath.length; i++) {
  70205. barycenter.addInPlace(shapePath[i]);
  70206. }
  70207. barycenter.scaleInPlace(1.0 / shapePath.length);
  70208. for (i = 0; i < shapePath.length; i++) {
  70209. pointCap.push(barycenter);
  70210. }
  70211. return pointCap;
  70212. };
  70213. switch (cap) {
  70214. case BABYLON.Mesh.NO_CAP:
  70215. break;
  70216. case BABYLON.Mesh.CAP_START:
  70217. shapePaths[0] = capPath(shapePaths[2]);
  70218. shapePaths[1] = shapePaths[2];
  70219. break;
  70220. case BABYLON.Mesh.CAP_END:
  70221. shapePaths[index] = shapePaths[index - 1];
  70222. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70223. break;
  70224. case BABYLON.Mesh.CAP_ALL:
  70225. shapePaths[0] = capPath(shapePaths[2]);
  70226. shapePaths[1] = shapePaths[2];
  70227. shapePaths[index] = shapePaths[index - 1];
  70228. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70229. break;
  70230. default:
  70231. break;
  70232. }
  70233. return shapePaths;
  70234. };
  70235. var path3D;
  70236. var pathArray;
  70237. if (instance) { // instance update
  70238. var storage = instance._creationDataStorage;
  70239. path3D = storage.path3D.update(curve);
  70240. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  70241. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  70242. return instance;
  70243. }
  70244. // extruded shape creation
  70245. path3D = new BABYLON.Path3D(curve);
  70246. var newShapePaths = new Array();
  70247. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70248. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  70249. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  70250. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  70251. extrudedGeneric._creationDataStorage.path3D = path3D;
  70252. extrudedGeneric._creationDataStorage.cap = cap;
  70253. return extrudedGeneric;
  70254. };
  70255. return MeshBuilder;
  70256. }());
  70257. BABYLON.MeshBuilder = MeshBuilder;
  70258. })(BABYLON || (BABYLON = {}));
  70259. //# sourceMappingURL=babylon.meshBuilder.js.map
  70260. var BABYLON;
  70261. (function (BABYLON) {
  70262. /**
  70263. * Draco compression (https://google.github.io/draco/)
  70264. *
  70265. * This class wraps the Draco module.
  70266. *
  70267. * **Encoder**
  70268. *
  70269. * The encoder is not currently implemented.
  70270. *
  70271. * **Decoder**
  70272. *
  70273. * 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.
  70274. *
  70275. * To update the configuration, use the following code:
  70276. * ```javascript
  70277. * BABYLON.DracoCompression.Configuration = {
  70278. * decoder: {
  70279. * wasmUrl: "<url to the WebAssembly library>",
  70280. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  70281. * fallbackUrl: "<url to the fallback JavaScript library>",
  70282. * }
  70283. * };
  70284. * ```
  70285. *
  70286. * 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.
  70287. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  70288. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  70289. *
  70290. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  70291. * ```javascript
  70292. * var dracoCompression = new BABYLON.DracoCompression();
  70293. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  70294. * [BABYLON.VertexBuffer.PositionKind]: 0
  70295. * });
  70296. * ```
  70297. *
  70298. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  70299. */
  70300. var DracoCompression = /** @class */ (function () {
  70301. /**
  70302. * Constructor
  70303. */
  70304. function DracoCompression() {
  70305. }
  70306. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  70307. /**
  70308. * Returns true if the decoder is available.
  70309. */
  70310. get: function () {
  70311. if (typeof DracoDecoderModule !== "undefined") {
  70312. return true;
  70313. }
  70314. var decoder = DracoCompression.Configuration.decoder;
  70315. if (decoder) {
  70316. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70317. return true;
  70318. }
  70319. if (decoder.fallbackUrl) {
  70320. return true;
  70321. }
  70322. }
  70323. return false;
  70324. },
  70325. enumerable: true,
  70326. configurable: true
  70327. });
  70328. /**
  70329. * Stop all async operations and release resources.
  70330. */
  70331. DracoCompression.prototype.dispose = function () {
  70332. };
  70333. /**
  70334. * Decode Draco compressed mesh data to vertex data.
  70335. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  70336. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  70337. * @returns A promise that resolves with the decoded vertex data
  70338. */
  70339. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  70340. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  70341. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  70342. var module = wrappedModule.module;
  70343. var vertexData = new BABYLON.VertexData();
  70344. var buffer = new module.DecoderBuffer();
  70345. buffer.Init(dataView, dataView.byteLength);
  70346. var decoder = new module.Decoder();
  70347. var geometry;
  70348. var status;
  70349. try {
  70350. var type = decoder.GetEncodedGeometryType(buffer);
  70351. switch (type) {
  70352. case module.TRIANGULAR_MESH:
  70353. geometry = new module.Mesh();
  70354. status = decoder.DecodeBufferToMesh(buffer, geometry);
  70355. break;
  70356. case module.POINT_CLOUD:
  70357. geometry = new module.PointCloud();
  70358. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  70359. break;
  70360. default:
  70361. throw new Error("Invalid geometry type " + type);
  70362. }
  70363. if (!status.ok() || !geometry.ptr) {
  70364. throw new Error(status.error_msg());
  70365. }
  70366. var numPoints = geometry.num_points();
  70367. if (type === module.TRIANGULAR_MESH) {
  70368. var numFaces = geometry.num_faces();
  70369. var faceIndices = new module.DracoInt32Array();
  70370. try {
  70371. var indices = new Uint32Array(numFaces * 3);
  70372. for (var i = 0; i < numFaces; i++) {
  70373. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  70374. var offset = i * 3;
  70375. indices[offset + 0] = faceIndices.GetValue(0);
  70376. indices[offset + 1] = faceIndices.GetValue(1);
  70377. indices[offset + 2] = faceIndices.GetValue(2);
  70378. }
  70379. vertexData.indices = indices;
  70380. }
  70381. finally {
  70382. module.destroy(faceIndices);
  70383. }
  70384. }
  70385. for (var kind in attributes) {
  70386. var uniqueId = attributes[kind];
  70387. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  70388. var dracoData = new module.DracoFloat32Array();
  70389. try {
  70390. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  70391. var babylonData = new Float32Array(numPoints * attribute.num_components());
  70392. for (var i = 0; i < babylonData.length; i++) {
  70393. babylonData[i] = dracoData.GetValue(i);
  70394. }
  70395. vertexData.set(babylonData, kind);
  70396. }
  70397. finally {
  70398. module.destroy(dracoData);
  70399. }
  70400. }
  70401. }
  70402. finally {
  70403. if (geometry) {
  70404. module.destroy(geometry);
  70405. }
  70406. module.destroy(decoder);
  70407. module.destroy(buffer);
  70408. }
  70409. return vertexData;
  70410. });
  70411. };
  70412. DracoCompression._GetDecoderModule = function () {
  70413. if (!DracoCompression._DecoderModulePromise) {
  70414. var promise = null;
  70415. var config_1 = {};
  70416. if (typeof DracoDecoderModule !== "undefined") {
  70417. promise = Promise.resolve();
  70418. }
  70419. else {
  70420. var decoder = DracoCompression.Configuration.decoder;
  70421. if (decoder) {
  70422. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70423. promise = Promise.all([
  70424. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  70425. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  70426. config_1.wasmBinary = data;
  70427. })
  70428. ]);
  70429. }
  70430. else if (decoder.fallbackUrl) {
  70431. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  70432. }
  70433. }
  70434. }
  70435. if (!promise) {
  70436. throw new Error("Draco decoder module is not available");
  70437. }
  70438. DracoCompression._DecoderModulePromise = promise.then(function () {
  70439. return new Promise(function (resolve) {
  70440. config_1.onModuleLoaded = function (decoderModule) {
  70441. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  70442. resolve({ module: decoderModule });
  70443. };
  70444. DracoDecoderModule(config_1);
  70445. });
  70446. });
  70447. }
  70448. return DracoCompression._DecoderModulePromise;
  70449. };
  70450. DracoCompression._LoadScriptAsync = function (url) {
  70451. return new Promise(function (resolve, reject) {
  70452. BABYLON.Tools.LoadScript(url, function () {
  70453. resolve();
  70454. }, function (message) {
  70455. reject(new Error(message));
  70456. });
  70457. });
  70458. };
  70459. DracoCompression._LoadFileAsync = function (url) {
  70460. return new Promise(function (resolve, reject) {
  70461. BABYLON.Tools.LoadFile(url, function (data) {
  70462. resolve(data);
  70463. }, undefined, undefined, true, function (request, exception) {
  70464. reject(exception);
  70465. });
  70466. });
  70467. };
  70468. /**
  70469. * The configuration. Defaults to the following urls:
  70470. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  70471. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  70472. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70473. */
  70474. DracoCompression.Configuration = {
  70475. decoder: {
  70476. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  70477. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  70478. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70479. }
  70480. };
  70481. return DracoCompression;
  70482. }());
  70483. BABYLON.DracoCompression = DracoCompression;
  70484. })(BABYLON || (BABYLON = {}));
  70485. //# sourceMappingURL=babylon.dracoCompression.js.map
  70486. var BABYLON;
  70487. (function (BABYLON) {
  70488. // Sets the default audio engine to Babylon.js
  70489. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  70490. /**
  70491. * This represents the default audio engine used in babylon.
  70492. * It is responsible to play, synchronize and analyse sounds throughout the application.
  70493. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70494. */
  70495. var AudioEngine = /** @class */ (function () {
  70496. /**
  70497. * Instantiates a new audio engine.
  70498. *
  70499. * There should be only one per page as some browsers restrict the number
  70500. * of audio contexts you can create.
  70501. * @param hostElement defines the host element where to display the mute icon if necessary
  70502. */
  70503. function AudioEngine(hostElement) {
  70504. if (hostElement === void 0) { hostElement = null; }
  70505. var _this = this;
  70506. this._audioContext = null;
  70507. this._audioContextInitialized = false;
  70508. this._muteButton = null;
  70509. /**
  70510. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  70511. */
  70512. this.canUseWebAudio = false;
  70513. /**
  70514. * Defines if Babylon should emit a warning if WebAudio is not supported.
  70515. * @ignoreNaming
  70516. */
  70517. this.WarnedWebAudioUnsupported = false;
  70518. /**
  70519. * Gets whether or not mp3 are supported by your browser.
  70520. */
  70521. this.isMP3supported = false;
  70522. /**
  70523. * Gets whether or not ogg are supported by your browser.
  70524. */
  70525. this.isOGGsupported = false;
  70526. /**
  70527. * Gets whether audio has been unlocked on the device.
  70528. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  70529. * a user interaction has happened.
  70530. */
  70531. this.unlocked = true;
  70532. /**
  70533. * Defines if the audio engine relies on a custom unlocked button.
  70534. * In this case, the embedded button will not be displayed.
  70535. */
  70536. this.useCustomUnlockedButton = false;
  70537. /**
  70538. * Event raised when audio has been unlocked on the browser.
  70539. */
  70540. this.onAudioUnlockedObservable = new BABYLON.Observable();
  70541. /**
  70542. * Event raised when audio has been locked on the browser.
  70543. */
  70544. this.onAudioLockedObservable = new BABYLON.Observable();
  70545. this._tryToRun = false;
  70546. this._onResize = function () {
  70547. _this._moveButtonToTopLeft();
  70548. };
  70549. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  70550. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  70551. this.canUseWebAudio = true;
  70552. }
  70553. var audioElem = document.createElement('audio');
  70554. this._hostElement = hostElement;
  70555. try {
  70556. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  70557. this.isMP3supported = true;
  70558. }
  70559. }
  70560. catch (e) {
  70561. // protect error during capability check.
  70562. }
  70563. try {
  70564. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  70565. this.isOGGsupported = true;
  70566. }
  70567. }
  70568. catch (e) {
  70569. // protect error during capability check.
  70570. }
  70571. }
  70572. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  70573. /**
  70574. * Gets the current AudioContext if available.
  70575. */
  70576. get: function () {
  70577. if (!this._audioContextInitialized) {
  70578. this._initializeAudioContext();
  70579. }
  70580. else {
  70581. if (!this.unlocked && !this._muteButton) {
  70582. this._displayMuteButton();
  70583. }
  70584. }
  70585. return this._audioContext;
  70586. },
  70587. enumerable: true,
  70588. configurable: true
  70589. });
  70590. /**
  70591. * Flags the audio engine in Locked state.
  70592. * This happens due to new browser policies preventing audio to autoplay.
  70593. */
  70594. AudioEngine.prototype.lock = function () {
  70595. this._triggerSuspendedState();
  70596. };
  70597. /**
  70598. * Unlocks the audio engine once a user action has been done on the dom.
  70599. * This is helpful to resume play once browser policies have been satisfied.
  70600. */
  70601. AudioEngine.prototype.unlock = function () {
  70602. this._triggerRunningState();
  70603. };
  70604. AudioEngine.prototype._resumeAudioContext = function () {
  70605. var result;
  70606. if (this._audioContext.resume) {
  70607. result = this._audioContext.resume();
  70608. }
  70609. return result || Promise.resolve();
  70610. };
  70611. AudioEngine.prototype._initializeAudioContext = function () {
  70612. try {
  70613. if (this.canUseWebAudio) {
  70614. this._audioContext = new AudioContext();
  70615. // create a global volume gain node
  70616. this.masterGain = this._audioContext.createGain();
  70617. this.masterGain.gain.value = 1;
  70618. this.masterGain.connect(this._audioContext.destination);
  70619. this._audioContextInitialized = true;
  70620. if (this._audioContext.state === "running") {
  70621. // Do not wait for the promise to unlock.
  70622. this._triggerRunningState();
  70623. }
  70624. }
  70625. }
  70626. catch (e) {
  70627. this.canUseWebAudio = false;
  70628. BABYLON.Tools.Error("Web Audio: " + e.message);
  70629. }
  70630. };
  70631. AudioEngine.prototype._triggerRunningState = function () {
  70632. var _this = this;
  70633. if (this._tryToRun) {
  70634. return;
  70635. }
  70636. this._tryToRun = true;
  70637. this._resumeAudioContext()
  70638. .then(function () {
  70639. _this._tryToRun = false;
  70640. if (_this._muteButton) {
  70641. _this._hideMuteButton();
  70642. }
  70643. }).catch(function () {
  70644. _this._tryToRun = false;
  70645. _this.unlocked = false;
  70646. });
  70647. // Notify users that the audio stack is unlocked/unmuted
  70648. this.unlocked = true;
  70649. this.onAudioUnlockedObservable.notifyObservers(this);
  70650. };
  70651. AudioEngine.prototype._triggerSuspendedState = function () {
  70652. this.unlocked = false;
  70653. this.onAudioLockedObservable.notifyObservers(this);
  70654. this._displayMuteButton();
  70655. };
  70656. AudioEngine.prototype._displayMuteButton = function () {
  70657. var _this = this;
  70658. if (this.useCustomUnlockedButton) {
  70659. return;
  70660. }
  70661. this._muteButton = document.createElement("BUTTON");
  70662. this._muteButton.className = "babylonUnmuteIcon";
  70663. this._muteButton.id = "babylonUnmuteIconBtn";
  70664. this._muteButton.title = "Unmute";
  70665. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; 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: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  70666. var style = document.createElement('style');
  70667. style.appendChild(document.createTextNode(css));
  70668. document.getElementsByTagName('head')[0].appendChild(style);
  70669. document.body.appendChild(this._muteButton);
  70670. this._moveButtonToTopLeft();
  70671. this._muteButton.addEventListener('touchend', function () {
  70672. _this._triggerRunningState();
  70673. }, true);
  70674. this._muteButton.addEventListener('click', function () {
  70675. _this._triggerRunningState();
  70676. }, true);
  70677. window.addEventListener("resize", this._onResize);
  70678. };
  70679. AudioEngine.prototype._moveButtonToTopLeft = function () {
  70680. if (this._hostElement && this._muteButton) {
  70681. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  70682. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  70683. }
  70684. };
  70685. AudioEngine.prototype._hideMuteButton = function () {
  70686. if (this._muteButton) {
  70687. document.body.removeChild(this._muteButton);
  70688. this._muteButton = null;
  70689. }
  70690. };
  70691. /**
  70692. * Destroy and release the resources associated with the audio ccontext.
  70693. */
  70694. AudioEngine.prototype.dispose = function () {
  70695. if (this.canUseWebAudio && this._audioContextInitialized) {
  70696. if (this._connectedAnalyser && this._audioContext) {
  70697. this._connectedAnalyser.stopDebugCanvas();
  70698. this._connectedAnalyser.dispose();
  70699. this.masterGain.disconnect();
  70700. this.masterGain.connect(this._audioContext.destination);
  70701. this._connectedAnalyser = null;
  70702. }
  70703. this.masterGain.gain.value = 1;
  70704. }
  70705. this.WarnedWebAudioUnsupported = false;
  70706. this._hideMuteButton();
  70707. window.removeEventListener("resize", this._onResize);
  70708. this.onAudioUnlockedObservable.clear();
  70709. this.onAudioLockedObservable.clear();
  70710. };
  70711. /**
  70712. * Gets the global volume sets on the master gain.
  70713. * @returns the global volume if set or -1 otherwise
  70714. */
  70715. AudioEngine.prototype.getGlobalVolume = function () {
  70716. if (this.canUseWebAudio && this._audioContextInitialized) {
  70717. return this.masterGain.gain.value;
  70718. }
  70719. else {
  70720. return -1;
  70721. }
  70722. };
  70723. /**
  70724. * Sets the global volume of your experience (sets on the master gain).
  70725. * @param newVolume Defines the new global volume of the application
  70726. */
  70727. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  70728. if (this.canUseWebAudio && this._audioContextInitialized) {
  70729. this.masterGain.gain.value = newVolume;
  70730. }
  70731. };
  70732. /**
  70733. * Connect the audio engine to an audio analyser allowing some amazing
  70734. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70735. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70736. * @param analyser The analyser to connect to the engine
  70737. */
  70738. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  70739. if (this._connectedAnalyser) {
  70740. this._connectedAnalyser.stopDebugCanvas();
  70741. }
  70742. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  70743. this._connectedAnalyser = analyser;
  70744. this.masterGain.disconnect();
  70745. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  70746. }
  70747. };
  70748. return AudioEngine;
  70749. }());
  70750. BABYLON.AudioEngine = AudioEngine;
  70751. })(BABYLON || (BABYLON = {}));
  70752. //# sourceMappingURL=babylon.audioEngine.js.map
  70753. var BABYLON;
  70754. (function (BABYLON) {
  70755. /**
  70756. * Defines a sound that can be played in the application.
  70757. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  70758. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70759. */
  70760. var Sound = /** @class */ (function () {
  70761. /**
  70762. * Create a sound and attach it to a scene
  70763. * @param name Name of your sound
  70764. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  70765. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  70766. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  70767. */
  70768. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  70769. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  70770. var _this = this;
  70771. /**
  70772. * Does the sound autoplay once loaded.
  70773. */
  70774. this.autoplay = false;
  70775. /**
  70776. * Does the sound loop after it finishes playing once.
  70777. */
  70778. this.loop = false;
  70779. /**
  70780. * Does the sound use a custom attenuation curve to simulate the falloff
  70781. * happening when the source gets further away from the camera.
  70782. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70783. */
  70784. this.useCustomAttenuation = false;
  70785. /**
  70786. * Is this sound currently played.
  70787. */
  70788. this.isPlaying = false;
  70789. /**
  70790. * Is this sound currently paused.
  70791. */
  70792. this.isPaused = false;
  70793. /**
  70794. * Does this sound enables spatial sound.
  70795. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70796. */
  70797. this.spatialSound = false;
  70798. /**
  70799. * Define the reference distance the sound should be heard perfectly.
  70800. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70801. */
  70802. this.refDistance = 1;
  70803. /**
  70804. * Define the roll off factor of spatial sounds.
  70805. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70806. */
  70807. this.rolloffFactor = 1;
  70808. /**
  70809. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  70810. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70811. */
  70812. this.maxDistance = 100;
  70813. /**
  70814. * Define the distance attenuation model the sound will follow.
  70815. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70816. */
  70817. this.distanceModel = "linear";
  70818. /**
  70819. * Observable event when the current playing sound finishes.
  70820. */
  70821. this.onEndedObservable = new BABYLON.Observable();
  70822. this._panningModel = "equalpower";
  70823. this._playbackRate = 1;
  70824. this._streaming = false;
  70825. this._startTime = 0;
  70826. this._startOffset = 0;
  70827. this._position = BABYLON.Vector3.Zero();
  70828. /** @hidden */
  70829. this._positionInEmitterSpace = false;
  70830. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  70831. this._volume = 1;
  70832. this._isReadyToPlay = false;
  70833. this._isDirectional = false;
  70834. // Used if you'd like to create a directional sound.
  70835. // If not set, the sound will be omnidirectional
  70836. this._coneInnerAngle = 360;
  70837. this._coneOuterAngle = 360;
  70838. this._coneOuterGain = 0;
  70839. this._isOutputConnected = false;
  70840. this._urlType = "Unknown";
  70841. this.name = name;
  70842. this._scene = scene;
  70843. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70844. if (!compo) {
  70845. compo = new BABYLON.AudioSceneComponent(scene);
  70846. scene._addComponent(compo);
  70847. }
  70848. this._readyToPlayCallback = readyToPlayCallback;
  70849. // Default custom attenuation function is a linear attenuation
  70850. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  70851. if (currentDistance < maxDistance) {
  70852. return currentVolume * (1 - currentDistance / maxDistance);
  70853. }
  70854. else {
  70855. return 0;
  70856. }
  70857. };
  70858. if (options) {
  70859. this.autoplay = options.autoplay || false;
  70860. this.loop = options.loop || false;
  70861. // if volume === 0, we need another way to check this option
  70862. if (options.volume !== undefined) {
  70863. this._volume = options.volume;
  70864. }
  70865. this.spatialSound = options.spatialSound || false;
  70866. this.maxDistance = options.maxDistance || 100;
  70867. this.useCustomAttenuation = options.useCustomAttenuation || false;
  70868. this.rolloffFactor = options.rolloffFactor || 1;
  70869. this.refDistance = options.refDistance || 1;
  70870. this.distanceModel = options.distanceModel || "linear";
  70871. this._playbackRate = options.playbackRate || 1;
  70872. this._streaming = options.streaming || false;
  70873. }
  70874. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70875. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  70876. this._soundGain.gain.value = this._volume;
  70877. this._inputAudioNode = this._soundGain;
  70878. this._outputAudioNode = this._soundGain;
  70879. if (this.spatialSound) {
  70880. this._createSpatialParameters();
  70881. }
  70882. this._scene.mainSoundTrack.AddSound(this);
  70883. var validParameter = true;
  70884. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  70885. if (urlOrArrayBuffer) {
  70886. try {
  70887. if (typeof (urlOrArrayBuffer) === "string") {
  70888. this._urlType = "String";
  70889. }
  70890. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  70891. this._urlType = "ArrayBuffer";
  70892. }
  70893. else if (urlOrArrayBuffer instanceof MediaStream) {
  70894. this._urlType = "MediaStream";
  70895. }
  70896. else if (Array.isArray(urlOrArrayBuffer)) {
  70897. this._urlType = "Array";
  70898. }
  70899. var urls = [];
  70900. var codecSupportedFound = false;
  70901. switch (this._urlType) {
  70902. case "MediaStream":
  70903. this._streaming = true;
  70904. this._isReadyToPlay = true;
  70905. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  70906. if (this.autoplay) {
  70907. this.play();
  70908. }
  70909. if (this._readyToPlayCallback) {
  70910. this._readyToPlayCallback();
  70911. }
  70912. break;
  70913. case "ArrayBuffer":
  70914. if (urlOrArrayBuffer.byteLength > 0) {
  70915. codecSupportedFound = true;
  70916. this._soundLoaded(urlOrArrayBuffer);
  70917. }
  70918. break;
  70919. case "String":
  70920. urls.push(urlOrArrayBuffer);
  70921. case "Array":
  70922. if (urls.length === 0) {
  70923. urls = urlOrArrayBuffer;
  70924. }
  70925. // If we found a supported format, we load it immediately and stop the loop
  70926. for (var i = 0; i < urls.length; i++) {
  70927. var url = urls[i];
  70928. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  70929. codecSupportedFound = true;
  70930. }
  70931. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  70932. codecSupportedFound = true;
  70933. }
  70934. if (url.indexOf(".wav", url.length - 4) !== -1) {
  70935. codecSupportedFound = true;
  70936. }
  70937. if (url.indexOf("blob:") !== -1) {
  70938. codecSupportedFound = true;
  70939. }
  70940. if (codecSupportedFound) {
  70941. // Loading sound using XHR2
  70942. if (!this._streaming) {
  70943. this._scene._loadFile(url, function (data) {
  70944. _this._soundLoaded(data);
  70945. }, undefined, true, true, function (exception) {
  70946. if (exception) {
  70947. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  70948. }
  70949. BABYLON.Tools.Error("Sound creation aborted.");
  70950. _this._scene.mainSoundTrack.RemoveSound(_this);
  70951. });
  70952. }
  70953. // Streaming sound using HTML5 Audio tag
  70954. else {
  70955. this._htmlAudioElement = new Audio(url);
  70956. this._htmlAudioElement.controls = false;
  70957. this._htmlAudioElement.loop = this.loop;
  70958. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  70959. this._htmlAudioElement.preload = "auto";
  70960. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  70961. _this._isReadyToPlay = true;
  70962. if (_this.autoplay) {
  70963. _this.play();
  70964. }
  70965. if (_this._readyToPlayCallback) {
  70966. _this._readyToPlayCallback();
  70967. }
  70968. });
  70969. document.body.appendChild(this._htmlAudioElement);
  70970. this._htmlAudioElement.load();
  70971. }
  70972. break;
  70973. }
  70974. }
  70975. break;
  70976. default:
  70977. validParameter = false;
  70978. break;
  70979. }
  70980. if (!validParameter) {
  70981. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  70982. }
  70983. else {
  70984. if (!codecSupportedFound) {
  70985. this._isReadyToPlay = true;
  70986. // Simulating a ready to play event to avoid breaking code path
  70987. if (this._readyToPlayCallback) {
  70988. window.setTimeout(function () {
  70989. if (_this._readyToPlayCallback) {
  70990. _this._readyToPlayCallback();
  70991. }
  70992. }, 1000);
  70993. }
  70994. }
  70995. }
  70996. }
  70997. catch (ex) {
  70998. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  70999. this._scene.mainSoundTrack.RemoveSound(this);
  71000. }
  71001. }
  71002. }
  71003. else {
  71004. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  71005. this._scene.mainSoundTrack.AddSound(this);
  71006. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  71007. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  71008. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  71009. }
  71010. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  71011. if (this._readyToPlayCallback) {
  71012. window.setTimeout(function () {
  71013. if (_this._readyToPlayCallback) {
  71014. _this._readyToPlayCallback();
  71015. }
  71016. }, 1000);
  71017. }
  71018. }
  71019. }
  71020. /**
  71021. * Release the sound and its associated resources
  71022. */
  71023. Sound.prototype.dispose = function () {
  71024. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71025. if (this.isPlaying) {
  71026. this.stop();
  71027. }
  71028. this._isReadyToPlay = false;
  71029. if (this.soundTrackId === -1) {
  71030. this._scene.mainSoundTrack.RemoveSound(this);
  71031. }
  71032. else if (this._scene.soundTracks) {
  71033. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  71034. }
  71035. if (this._soundGain) {
  71036. this._soundGain.disconnect();
  71037. this._soundGain = null;
  71038. }
  71039. if (this._soundPanner) {
  71040. this._soundPanner.disconnect();
  71041. this._soundPanner = null;
  71042. }
  71043. if (this._soundSource) {
  71044. this._soundSource.disconnect();
  71045. this._soundSource = null;
  71046. }
  71047. this._audioBuffer = null;
  71048. if (this._htmlAudioElement) {
  71049. this._htmlAudioElement.pause();
  71050. this._htmlAudioElement.src = "";
  71051. document.body.removeChild(this._htmlAudioElement);
  71052. }
  71053. if (this._streamingSource) {
  71054. this._streamingSource.disconnect();
  71055. }
  71056. if (this._connectedMesh && this._registerFunc) {
  71057. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71058. this._connectedMesh = null;
  71059. }
  71060. }
  71061. };
  71062. /**
  71063. * Gets if the sounds is ready to be played or not.
  71064. * @returns true if ready, otherwise false
  71065. */
  71066. Sound.prototype.isReady = function () {
  71067. return this._isReadyToPlay;
  71068. };
  71069. Sound.prototype._soundLoaded = function (audioData) {
  71070. var _this = this;
  71071. if (!BABYLON.Engine.audioEngine.audioContext) {
  71072. return;
  71073. }
  71074. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  71075. _this._audioBuffer = buffer;
  71076. _this._isReadyToPlay = true;
  71077. if (_this.autoplay) {
  71078. _this.play();
  71079. }
  71080. if (_this._readyToPlayCallback) {
  71081. _this._readyToPlayCallback();
  71082. }
  71083. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  71084. };
  71085. /**
  71086. * Sets the data of the sound from an audiobuffer
  71087. * @param audioBuffer The audioBuffer containing the data
  71088. */
  71089. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  71090. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71091. this._audioBuffer = audioBuffer;
  71092. this._isReadyToPlay = true;
  71093. }
  71094. };
  71095. /**
  71096. * Updates the current sounds options such as maxdistance, loop...
  71097. * @param options A JSON object containing values named as the object properties
  71098. */
  71099. Sound.prototype.updateOptions = function (options) {
  71100. if (options) {
  71101. this.loop = options.loop || this.loop;
  71102. this.maxDistance = options.maxDistance || this.maxDistance;
  71103. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  71104. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  71105. this.refDistance = options.refDistance || this.refDistance;
  71106. this.distanceModel = options.distanceModel || this.distanceModel;
  71107. this._playbackRate = options.playbackRate || this._playbackRate;
  71108. this._updateSpatialParameters();
  71109. if (this.isPlaying) {
  71110. if (this._streaming && this._htmlAudioElement) {
  71111. this._htmlAudioElement.playbackRate = this._playbackRate;
  71112. }
  71113. else {
  71114. if (this._soundSource) {
  71115. this._soundSource.playbackRate.value = this._playbackRate;
  71116. }
  71117. }
  71118. }
  71119. }
  71120. };
  71121. Sound.prototype._createSpatialParameters = function () {
  71122. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71123. if (this._scene.headphone) {
  71124. this._panningModel = "HRTF";
  71125. }
  71126. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  71127. this._updateSpatialParameters();
  71128. this._soundPanner.connect(this._outputAudioNode);
  71129. this._inputAudioNode = this._soundPanner;
  71130. }
  71131. };
  71132. Sound.prototype._updateSpatialParameters = function () {
  71133. if (this.spatialSound && this._soundPanner) {
  71134. if (this.useCustomAttenuation) {
  71135. // Tricks to disable in a way embedded Web Audio attenuation
  71136. this._soundPanner.distanceModel = "linear";
  71137. this._soundPanner.maxDistance = Number.MAX_VALUE;
  71138. this._soundPanner.refDistance = 1;
  71139. this._soundPanner.rolloffFactor = 1;
  71140. this._soundPanner.panningModel = this._panningModel;
  71141. }
  71142. else {
  71143. this._soundPanner.distanceModel = this.distanceModel;
  71144. this._soundPanner.maxDistance = this.maxDistance;
  71145. this._soundPanner.refDistance = this.refDistance;
  71146. this._soundPanner.rolloffFactor = this.rolloffFactor;
  71147. this._soundPanner.panningModel = this._panningModel;
  71148. }
  71149. }
  71150. };
  71151. /**
  71152. * Switch the panning model to HRTF:
  71153. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71154. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71155. */
  71156. Sound.prototype.switchPanningModelToHRTF = function () {
  71157. this._panningModel = "HRTF";
  71158. this._switchPanningModel();
  71159. };
  71160. /**
  71161. * Switch the panning model to Equal Power:
  71162. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71163. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71164. */
  71165. Sound.prototype.switchPanningModelToEqualPower = function () {
  71166. this._panningModel = "equalpower";
  71167. this._switchPanningModel();
  71168. };
  71169. Sound.prototype._switchPanningModel = function () {
  71170. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71171. this._soundPanner.panningModel = this._panningModel;
  71172. }
  71173. };
  71174. /**
  71175. * Connect this sound to a sound track audio node like gain...
  71176. * @param soundTrackAudioNode the sound track audio node to connect to
  71177. */
  71178. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  71179. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71180. if (this._isOutputConnected) {
  71181. this._outputAudioNode.disconnect();
  71182. }
  71183. this._outputAudioNode.connect(soundTrackAudioNode);
  71184. this._isOutputConnected = true;
  71185. }
  71186. };
  71187. /**
  71188. * Transform this sound into a directional source
  71189. * @param coneInnerAngle Size of the inner cone in degree
  71190. * @param coneOuterAngle Size of the outer cone in degree
  71191. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  71192. */
  71193. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  71194. if (coneOuterAngle < coneInnerAngle) {
  71195. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  71196. return;
  71197. }
  71198. this._coneInnerAngle = coneInnerAngle;
  71199. this._coneOuterAngle = coneOuterAngle;
  71200. this._coneOuterGain = coneOuterGain;
  71201. this._isDirectional = true;
  71202. if (this.isPlaying && this.loop) {
  71203. this.stop();
  71204. this.play();
  71205. }
  71206. };
  71207. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  71208. /**
  71209. * Gets or sets the inner angle for the directional cone.
  71210. */
  71211. get: function () {
  71212. return this._coneInnerAngle;
  71213. },
  71214. /**
  71215. * Gets or sets the inner angle for the directional cone.
  71216. */
  71217. set: function (value) {
  71218. if (value != this._coneInnerAngle) {
  71219. if (this._coneOuterAngle < value) {
  71220. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71221. return;
  71222. }
  71223. this._coneInnerAngle = value;
  71224. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71225. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71226. }
  71227. }
  71228. },
  71229. enumerable: true,
  71230. configurable: true
  71231. });
  71232. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  71233. /**
  71234. * Gets or sets the outer angle for the directional cone.
  71235. */
  71236. get: function () {
  71237. return this._coneOuterAngle;
  71238. },
  71239. /**
  71240. * Gets or sets the outer angle for the directional cone.
  71241. */
  71242. set: function (value) {
  71243. if (value != this._coneOuterAngle) {
  71244. if (value < this._coneInnerAngle) {
  71245. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71246. return;
  71247. }
  71248. this._coneOuterAngle = value;
  71249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71250. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71251. }
  71252. }
  71253. },
  71254. enumerable: true,
  71255. configurable: true
  71256. });
  71257. /**
  71258. * Sets the position of the emitter if spatial sound is enabled
  71259. * @param newPosition Defines the new posisiton
  71260. */
  71261. Sound.prototype.setPosition = function (newPosition) {
  71262. this._position = newPosition;
  71263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71264. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71265. }
  71266. };
  71267. /**
  71268. * Sets the local direction of the emitter if spatial sound is enabled
  71269. * @param newLocalDirection Defines the new local direction
  71270. */
  71271. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  71272. this._localDirection = newLocalDirection;
  71273. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  71274. this._updateDirection();
  71275. }
  71276. };
  71277. Sound.prototype._updateDirection = function () {
  71278. if (!this._connectedMesh || !this._soundPanner) {
  71279. return;
  71280. }
  71281. var mat = this._connectedMesh.getWorldMatrix();
  71282. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  71283. direction.normalize();
  71284. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  71285. };
  71286. /** @hidden */
  71287. Sound.prototype.updateDistanceFromListener = function () {
  71288. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  71289. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  71290. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  71291. }
  71292. };
  71293. /**
  71294. * Sets a new custom attenuation function for the sound.
  71295. * @param callback Defines the function used for the attenuation
  71296. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71297. */
  71298. Sound.prototype.setAttenuationFunction = function (callback) {
  71299. this._customAttenuationFunction = callback;
  71300. };
  71301. /**
  71302. * Play the sound
  71303. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  71304. * @param offset (optional) Start the sound setting it at a specific time
  71305. */
  71306. Sound.prototype.play = function (time, offset) {
  71307. var _this = this;
  71308. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  71309. try {
  71310. if (this._startOffset < 0) {
  71311. time = -this._startOffset;
  71312. this._startOffset = 0;
  71313. }
  71314. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71315. if (!this._soundSource || !this._streamingSource) {
  71316. if (this.spatialSound && this._soundPanner) {
  71317. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71318. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71319. }
  71320. if (this._isDirectional) {
  71321. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71322. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71323. this._soundPanner.coneOuterGain = this._coneOuterGain;
  71324. if (this._connectedMesh) {
  71325. this._updateDirection();
  71326. }
  71327. else {
  71328. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  71329. }
  71330. }
  71331. }
  71332. }
  71333. if (this._streaming) {
  71334. if (!this._streamingSource) {
  71335. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  71336. this._htmlAudioElement.onended = function () { _this._onended(); };
  71337. this._htmlAudioElement.playbackRate = this._playbackRate;
  71338. }
  71339. this._streamingSource.disconnect();
  71340. this._streamingSource.connect(this._inputAudioNode);
  71341. if (this._htmlAudioElement) {
  71342. // required to manage properly the new suspended default state of Chrome
  71343. // When the option 'streaming: true' is used, we need first to wait for
  71344. // the audio engine to be unlocked by a user gesture before trying to play
  71345. // an HTML Audio elememt
  71346. var tryToPlay = function () {
  71347. if (BABYLON.Engine.audioEngine.unlocked) {
  71348. var playPromise = _this._htmlAudioElement.play();
  71349. // In browsers that don’t yet support this functionality,
  71350. // playPromise won’t be defined.
  71351. if (playPromise !== undefined) {
  71352. playPromise.catch(function (error) {
  71353. // Automatic playback failed.
  71354. // Waiting for the audio engine to be unlocked by user click on unmute
  71355. BABYLON.Engine.audioEngine.lock();
  71356. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71357. });
  71358. }
  71359. }
  71360. else {
  71361. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71362. }
  71363. };
  71364. tryToPlay();
  71365. }
  71366. }
  71367. else {
  71368. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  71369. this._soundSource.buffer = this._audioBuffer;
  71370. this._soundSource.connect(this._inputAudioNode);
  71371. this._soundSource.loop = this.loop;
  71372. this._soundSource.playbackRate.value = this._playbackRate;
  71373. this._soundSource.onended = function () { _this._onended(); };
  71374. if (this._soundSource.buffer) {
  71375. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  71376. }
  71377. }
  71378. this._startTime = startTime;
  71379. this.isPlaying = true;
  71380. this.isPaused = false;
  71381. }
  71382. catch (ex) {
  71383. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  71384. }
  71385. }
  71386. };
  71387. Sound.prototype._onended = function () {
  71388. this.isPlaying = false;
  71389. if (this.onended) {
  71390. this.onended();
  71391. }
  71392. this.onEndedObservable.notifyObservers(this);
  71393. };
  71394. /**
  71395. * Stop the sound
  71396. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  71397. */
  71398. Sound.prototype.stop = function (time) {
  71399. if (this.isPlaying) {
  71400. if (this._streaming) {
  71401. if (this._htmlAudioElement) {
  71402. this._htmlAudioElement.pause();
  71403. // Test needed for Firefox or it will generate an Invalid State Error
  71404. if (this._htmlAudioElement.currentTime > 0) {
  71405. this._htmlAudioElement.currentTime = 0;
  71406. }
  71407. }
  71408. else {
  71409. this._streamingSource.disconnect();
  71410. }
  71411. }
  71412. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  71413. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71414. this._soundSource.stop(stopTime);
  71415. this._soundSource.onended = function () { };
  71416. if (!this.isPaused) {
  71417. this._startOffset = 0;
  71418. }
  71419. }
  71420. this.isPlaying = false;
  71421. }
  71422. };
  71423. /**
  71424. * Put the sound in pause
  71425. */
  71426. Sound.prototype.pause = function () {
  71427. if (this.isPlaying) {
  71428. this.isPaused = true;
  71429. if (this._streaming) {
  71430. if (this._htmlAudioElement) {
  71431. this._htmlAudioElement.pause();
  71432. }
  71433. else {
  71434. this._streamingSource.disconnect();
  71435. }
  71436. }
  71437. else if (BABYLON.Engine.audioEngine.audioContext) {
  71438. this.stop(0);
  71439. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  71440. }
  71441. }
  71442. };
  71443. /**
  71444. * Sets a dedicated volume for this sounds
  71445. * @param newVolume Define the new volume of the sound
  71446. * @param time Define in how long the sound should be at this value
  71447. */
  71448. Sound.prototype.setVolume = function (newVolume, time) {
  71449. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  71450. if (time && BABYLON.Engine.audioEngine.audioContext) {
  71451. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  71452. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  71453. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  71454. }
  71455. else {
  71456. this._soundGain.gain.value = newVolume;
  71457. }
  71458. }
  71459. this._volume = newVolume;
  71460. };
  71461. /**
  71462. * Set the sound play back rate
  71463. * @param newPlaybackRate Define the playback rate the sound should be played at
  71464. */
  71465. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  71466. this._playbackRate = newPlaybackRate;
  71467. if (this.isPlaying) {
  71468. if (this._streaming && this._htmlAudioElement) {
  71469. this._htmlAudioElement.playbackRate = this._playbackRate;
  71470. }
  71471. else if (this._soundSource) {
  71472. this._soundSource.playbackRate.value = this._playbackRate;
  71473. }
  71474. }
  71475. };
  71476. /**
  71477. * Gets the volume of the sound.
  71478. * @returns the volume of the sound
  71479. */
  71480. Sound.prototype.getVolume = function () {
  71481. return this._volume;
  71482. };
  71483. /**
  71484. * Attach the sound to a dedicated mesh
  71485. * @param meshToConnectTo The mesh to connect the sound with
  71486. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71487. */
  71488. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  71489. var _this = this;
  71490. if (this._connectedMesh && this._registerFunc) {
  71491. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71492. this._registerFunc = null;
  71493. }
  71494. this._connectedMesh = meshToConnectTo;
  71495. if (!this.spatialSound) {
  71496. this.spatialSound = true;
  71497. this._createSpatialParameters();
  71498. if (this.isPlaying && this.loop) {
  71499. this.stop();
  71500. this.play();
  71501. }
  71502. }
  71503. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  71504. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  71505. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  71506. };
  71507. /**
  71508. * Detach the sound from the previously attached mesh
  71509. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71510. */
  71511. Sound.prototype.detachFromMesh = function () {
  71512. if (this._connectedMesh && this._registerFunc) {
  71513. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71514. this._registerFunc = null;
  71515. this._connectedMesh = null;
  71516. }
  71517. };
  71518. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  71519. if (!node.getBoundingInfo) {
  71520. return;
  71521. }
  71522. var mesh = node;
  71523. if (this._positionInEmitterSpace) {
  71524. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  71525. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  71526. }
  71527. else {
  71528. var boundingInfo = mesh.getBoundingInfo();
  71529. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  71530. }
  71531. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  71532. this._updateDirection();
  71533. }
  71534. };
  71535. /**
  71536. * Clone the current sound in the scene.
  71537. * @returns the new sound clone
  71538. */
  71539. Sound.prototype.clone = function () {
  71540. var _this = this;
  71541. if (!this._streaming) {
  71542. var setBufferAndRun = function () {
  71543. if (_this._isReadyToPlay) {
  71544. clonedSound._audioBuffer = _this.getAudioBuffer();
  71545. clonedSound._isReadyToPlay = true;
  71546. if (clonedSound.autoplay) {
  71547. clonedSound.play();
  71548. }
  71549. }
  71550. else {
  71551. window.setTimeout(setBufferAndRun, 300);
  71552. }
  71553. };
  71554. var currentOptions = {
  71555. autoplay: this.autoplay, loop: this.loop,
  71556. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  71557. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  71558. refDistance: this.refDistance, distanceModel: this.distanceModel
  71559. };
  71560. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  71561. if (this.useCustomAttenuation) {
  71562. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  71563. }
  71564. clonedSound.setPosition(this._position);
  71565. clonedSound.setPlaybackRate(this._playbackRate);
  71566. setBufferAndRun();
  71567. return clonedSound;
  71568. }
  71569. // Can't clone a streaming sound
  71570. else {
  71571. return null;
  71572. }
  71573. };
  71574. /**
  71575. * Gets the current underlying audio buffer containing the data
  71576. * @returns the audio buffer
  71577. */
  71578. Sound.prototype.getAudioBuffer = function () {
  71579. return this._audioBuffer;
  71580. };
  71581. /**
  71582. * Serializes the Sound in a JSON representation
  71583. * @returns the JSON representation of the sound
  71584. */
  71585. Sound.prototype.serialize = function () {
  71586. var serializationObject = {
  71587. name: this.name,
  71588. url: this.name,
  71589. autoplay: this.autoplay,
  71590. loop: this.loop,
  71591. volume: this._volume,
  71592. spatialSound: this.spatialSound,
  71593. maxDistance: this.maxDistance,
  71594. rolloffFactor: this.rolloffFactor,
  71595. refDistance: this.refDistance,
  71596. distanceModel: this.distanceModel,
  71597. playbackRate: this._playbackRate,
  71598. panningModel: this._panningModel,
  71599. soundTrackId: this.soundTrackId
  71600. };
  71601. if (this.spatialSound) {
  71602. if (this._connectedMesh) {
  71603. serializationObject.connectedMeshId = this._connectedMesh.id;
  71604. }
  71605. serializationObject.position = this._position.asArray();
  71606. serializationObject.refDistance = this.refDistance;
  71607. serializationObject.distanceModel = this.distanceModel;
  71608. serializationObject.isDirectional = this._isDirectional;
  71609. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  71610. serializationObject.coneInnerAngle = this._coneInnerAngle;
  71611. serializationObject.coneOuterAngle = this._coneOuterAngle;
  71612. serializationObject.coneOuterGain = this._coneOuterGain;
  71613. }
  71614. return serializationObject;
  71615. };
  71616. /**
  71617. * Parse a JSON representation of a sound to innstantiate in a given scene
  71618. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  71619. * @param scene Define the scene the new parsed sound should be created in
  71620. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  71621. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  71622. * @returns the newly parsed sound
  71623. */
  71624. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  71625. var soundName = parsedSound.name;
  71626. var soundUrl;
  71627. if (parsedSound.url) {
  71628. soundUrl = rootUrl + parsedSound.url;
  71629. }
  71630. else {
  71631. soundUrl = rootUrl + soundName;
  71632. }
  71633. var options = {
  71634. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  71635. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  71636. rolloffFactor: parsedSound.rolloffFactor,
  71637. refDistance: parsedSound.refDistance,
  71638. distanceModel: parsedSound.distanceModel,
  71639. playbackRate: parsedSound.playbackRate
  71640. };
  71641. var newSound;
  71642. if (!sourceSound) {
  71643. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  71644. scene._addPendingData(newSound);
  71645. }
  71646. else {
  71647. var setBufferAndRun = function () {
  71648. if (sourceSound._isReadyToPlay) {
  71649. newSound._audioBuffer = sourceSound.getAudioBuffer();
  71650. newSound._isReadyToPlay = true;
  71651. if (newSound.autoplay) {
  71652. newSound.play();
  71653. }
  71654. }
  71655. else {
  71656. window.setTimeout(setBufferAndRun, 300);
  71657. }
  71658. };
  71659. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  71660. setBufferAndRun();
  71661. }
  71662. if (parsedSound.position) {
  71663. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  71664. newSound.setPosition(soundPosition);
  71665. }
  71666. if (parsedSound.isDirectional) {
  71667. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  71668. if (parsedSound.localDirectionToMesh) {
  71669. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  71670. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  71671. }
  71672. }
  71673. if (parsedSound.connectedMeshId) {
  71674. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  71675. if (connectedMesh) {
  71676. newSound.attachToMesh(connectedMesh);
  71677. }
  71678. }
  71679. return newSound;
  71680. };
  71681. return Sound;
  71682. }());
  71683. BABYLON.Sound = Sound;
  71684. })(BABYLON || (BABYLON = {}));
  71685. //# sourceMappingURL=babylon.sound.js.map
  71686. var BABYLON;
  71687. (function (BABYLON) {
  71688. /**
  71689. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  71690. * It will be also used in a future release to apply effects on a specific track.
  71691. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71692. */
  71693. var SoundTrack = /** @class */ (function () {
  71694. /**
  71695. * Creates a new sound track.
  71696. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71697. * @param scene Define the scene the sound track belongs to
  71698. * @param options
  71699. */
  71700. function SoundTrack(scene, options) {
  71701. if (options === void 0) { options = {}; }
  71702. /**
  71703. * The unique identifier of the sound track in the scene.
  71704. */
  71705. this.id = -1;
  71706. this._isMainTrack = false;
  71707. this._isInitialized = false;
  71708. this._scene = scene;
  71709. this.soundCollection = new Array();
  71710. this._options = options;
  71711. if (!this._isMainTrack && this._scene.soundTracks) {
  71712. this._scene.soundTracks.push(this);
  71713. this.id = this._scene.soundTracks.length - 1;
  71714. }
  71715. }
  71716. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  71717. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71718. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  71719. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  71720. if (this._options) {
  71721. if (this._options.volume) {
  71722. this._outputAudioNode.gain.value = this._options.volume;
  71723. }
  71724. if (this._options.mainTrack) {
  71725. this._isMainTrack = this._options.mainTrack;
  71726. }
  71727. }
  71728. this._isInitialized = true;
  71729. }
  71730. };
  71731. /**
  71732. * Release the sound track and its associated resources
  71733. */
  71734. SoundTrack.prototype.dispose = function () {
  71735. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  71736. if (this._connectedAnalyser) {
  71737. this._connectedAnalyser.stopDebugCanvas();
  71738. }
  71739. while (this.soundCollection.length) {
  71740. this.soundCollection[0].dispose();
  71741. }
  71742. if (this._outputAudioNode) {
  71743. this._outputAudioNode.disconnect();
  71744. }
  71745. this._outputAudioNode = null;
  71746. }
  71747. };
  71748. /**
  71749. * Adds a sound to this sound track
  71750. * @param sound define the cound to add
  71751. * @ignoreNaming
  71752. */
  71753. SoundTrack.prototype.AddSound = function (sound) {
  71754. if (!this._isInitialized) {
  71755. this._initializeSoundTrackAudioGraph();
  71756. }
  71757. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71758. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  71759. }
  71760. if (sound.soundTrackId) {
  71761. if (sound.soundTrackId === -1) {
  71762. this._scene.mainSoundTrack.RemoveSound(sound);
  71763. }
  71764. else if (this._scene.soundTracks) {
  71765. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  71766. }
  71767. }
  71768. this.soundCollection.push(sound);
  71769. sound.soundTrackId = this.id;
  71770. };
  71771. /**
  71772. * Removes a sound to this sound track
  71773. * @param sound define the cound to remove
  71774. * @ignoreNaming
  71775. */
  71776. SoundTrack.prototype.RemoveSound = function (sound) {
  71777. var index = this.soundCollection.indexOf(sound);
  71778. if (index !== -1) {
  71779. this.soundCollection.splice(index, 1);
  71780. }
  71781. };
  71782. /**
  71783. * Set a global volume for the full sound track.
  71784. * @param newVolume Define the new volume of the sound track
  71785. */
  71786. SoundTrack.prototype.setVolume = function (newVolume) {
  71787. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71788. this._outputAudioNode.gain.value = newVolume;
  71789. }
  71790. };
  71791. /**
  71792. * Switch the panning model to HRTF:
  71793. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71794. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71795. */
  71796. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  71797. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71798. for (var i = 0; i < this.soundCollection.length; i++) {
  71799. this.soundCollection[i].switchPanningModelToHRTF();
  71800. }
  71801. }
  71802. };
  71803. /**
  71804. * Switch the panning model to Equal Power:
  71805. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71806. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71807. */
  71808. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  71809. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71810. for (var i = 0; i < this.soundCollection.length; i++) {
  71811. this.soundCollection[i].switchPanningModelToEqualPower();
  71812. }
  71813. }
  71814. };
  71815. /**
  71816. * Connect the sound track to an audio analyser allowing some amazing
  71817. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  71818. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  71819. * @param analyser The analyser to connect to the engine
  71820. */
  71821. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  71822. if (this._connectedAnalyser) {
  71823. this._connectedAnalyser.stopDebugCanvas();
  71824. }
  71825. this._connectedAnalyser = analyser;
  71826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71827. this._outputAudioNode.disconnect();
  71828. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  71829. }
  71830. };
  71831. return SoundTrack;
  71832. }());
  71833. BABYLON.SoundTrack = SoundTrack;
  71834. })(BABYLON || (BABYLON = {}));
  71835. //# sourceMappingURL=babylon.soundtrack.js.map
  71836. var BABYLON;
  71837. (function (BABYLON) {
  71838. /**
  71839. * Class used to work with sound analyzer using fast fourier transform (FFT)
  71840. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71841. */
  71842. var Analyser = /** @class */ (function () {
  71843. /**
  71844. * Creates a new analyser
  71845. * @param scene defines hosting scene
  71846. */
  71847. function Analyser(scene) {
  71848. /**
  71849. * Gets or sets the smoothing
  71850. * @ignorenaming
  71851. */
  71852. this.SMOOTHING = 0.75;
  71853. /**
  71854. * Gets or sets the FFT table size
  71855. * @ignorenaming
  71856. */
  71857. this.FFT_SIZE = 512;
  71858. /**
  71859. * Gets or sets the bar graph amplitude
  71860. * @ignorenaming
  71861. */
  71862. this.BARGRAPHAMPLITUDE = 256;
  71863. /**
  71864. * Gets or sets the position of the debug canvas
  71865. * @ignorenaming
  71866. */
  71867. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  71868. /**
  71869. * Gets or sets the debug canvas size
  71870. * @ignorenaming
  71871. */
  71872. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  71873. this._scene = scene;
  71874. this._audioEngine = BABYLON.Engine.audioEngine;
  71875. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  71876. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  71877. this._webAudioAnalyser.minDecibels = -140;
  71878. this._webAudioAnalyser.maxDecibels = 0;
  71879. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71880. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71881. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  71882. }
  71883. }
  71884. /**
  71885. * Get the number of data values you will have to play with for the visualization
  71886. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  71887. * @returns a number
  71888. */
  71889. Analyser.prototype.getFrequencyBinCount = function () {
  71890. if (this._audioEngine.canUseWebAudio) {
  71891. return this._webAudioAnalyser.frequencyBinCount;
  71892. }
  71893. else {
  71894. return 0;
  71895. }
  71896. };
  71897. /**
  71898. * Gets the current frequency data as a byte array
  71899. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71900. * @returns a Uint8Array
  71901. */
  71902. Analyser.prototype.getByteFrequencyData = function () {
  71903. if (this._audioEngine.canUseWebAudio) {
  71904. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71905. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71906. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  71907. }
  71908. return this._byteFreqs;
  71909. };
  71910. /**
  71911. * Gets the current waveform as a byte array
  71912. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  71913. * @returns a Uint8Array
  71914. */
  71915. Analyser.prototype.getByteTimeDomainData = function () {
  71916. if (this._audioEngine.canUseWebAudio) {
  71917. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71918. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71919. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  71920. }
  71921. return this._byteTime;
  71922. };
  71923. /**
  71924. * Gets the current frequency data as a float array
  71925. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71926. * @returns a Float32Array
  71927. */
  71928. Analyser.prototype.getFloatFrequencyData = function () {
  71929. if (this._audioEngine.canUseWebAudio) {
  71930. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  71931. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  71932. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  71933. }
  71934. return this._floatFreqs;
  71935. };
  71936. /**
  71937. * Renders the debug canvas
  71938. */
  71939. Analyser.prototype.drawDebugCanvas = function () {
  71940. var _this = this;
  71941. if (this._audioEngine.canUseWebAudio) {
  71942. if (!this._debugCanvas) {
  71943. this._debugCanvas = document.createElement("canvas");
  71944. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  71945. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  71946. this._debugCanvas.style.position = "absolute";
  71947. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  71948. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  71949. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  71950. document.body.appendChild(this._debugCanvas);
  71951. this._registerFunc = function () {
  71952. _this.drawDebugCanvas();
  71953. };
  71954. this._scene.registerBeforeRender(this._registerFunc);
  71955. }
  71956. if (this._registerFunc && this._debugCanvasContext) {
  71957. var workingArray = this.getByteFrequencyData();
  71958. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  71959. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  71960. // Draw the frequency domain chart.
  71961. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  71962. var value = workingArray[i];
  71963. var percent = value / this.BARGRAPHAMPLITUDE;
  71964. var height = this.DEBUGCANVASSIZE.height * percent;
  71965. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  71966. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  71967. var hue = i / this.getFrequencyBinCount() * 360;
  71968. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  71969. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  71970. }
  71971. }
  71972. }
  71973. };
  71974. /**
  71975. * Stops rendering the debug canvas and removes it
  71976. */
  71977. Analyser.prototype.stopDebugCanvas = function () {
  71978. if (this._debugCanvas) {
  71979. if (this._registerFunc) {
  71980. this._scene.unregisterBeforeRender(this._registerFunc);
  71981. this._registerFunc = null;
  71982. }
  71983. document.body.removeChild(this._debugCanvas);
  71984. this._debugCanvas = null;
  71985. this._debugCanvasContext = null;
  71986. }
  71987. };
  71988. /**
  71989. * Connects two audio nodes
  71990. * @param inputAudioNode defines first node to connect
  71991. * @param outputAudioNode defines second node to connect
  71992. */
  71993. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  71994. if (this._audioEngine.canUseWebAudio) {
  71995. inputAudioNode.connect(this._webAudioAnalyser);
  71996. this._webAudioAnalyser.connect(outputAudioNode);
  71997. }
  71998. };
  71999. /**
  72000. * Releases all associated resources
  72001. */
  72002. Analyser.prototype.dispose = function () {
  72003. if (this._audioEngine.canUseWebAudio) {
  72004. this._webAudioAnalyser.disconnect();
  72005. }
  72006. };
  72007. return Analyser;
  72008. }());
  72009. BABYLON.Analyser = Analyser;
  72010. })(BABYLON || (BABYLON = {}));
  72011. //# sourceMappingURL=babylon.analyser.js.map
  72012. var BABYLON;
  72013. (function (BABYLON) {
  72014. /**
  72015. * Wraps one or more Sound objects and selects one with random weight for playback.
  72016. */
  72017. var WeightedSound = /** @class */ (function () {
  72018. /**
  72019. * Creates a new WeightedSound from the list of sounds given.
  72020. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  72021. * @param sounds Array of Sounds that will be selected from.
  72022. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  72023. */
  72024. function WeightedSound(loop, sounds, weights) {
  72025. var _this = this;
  72026. /** When true a Sound will be selected and played when the current playing Sound completes. */
  72027. this.loop = false;
  72028. this._coneInnerAngle = 360;
  72029. this._coneOuterAngle = 360;
  72030. this._volume = 1;
  72031. /** A Sound is currently playing. */
  72032. this.isPlaying = false;
  72033. /** A Sound is currently paused. */
  72034. this.isPaused = false;
  72035. this._sounds = [];
  72036. this._weights = [];
  72037. if (sounds.length !== weights.length) {
  72038. throw new Error('Sounds length does not equal weights length');
  72039. }
  72040. this.loop = loop;
  72041. this._weights = weights;
  72042. // Normalize the weights
  72043. var weightSum = 0;
  72044. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  72045. var weight = weights_1[_i];
  72046. weightSum += weight;
  72047. }
  72048. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  72049. for (var i = 0; i < this._weights.length; i++) {
  72050. this._weights[i] *= invWeightSum;
  72051. }
  72052. this._sounds = sounds;
  72053. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  72054. var sound = _b[_a];
  72055. sound.onEndedObservable.add(function () { _this._onended(); });
  72056. }
  72057. }
  72058. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  72059. /**
  72060. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  72061. */
  72062. get: function () {
  72063. return this._coneInnerAngle;
  72064. },
  72065. /**
  72066. * The size of cone in degress for a directional sound in which there will be no attenuation.
  72067. */
  72068. set: function (value) {
  72069. if (value !== this._coneInnerAngle) {
  72070. if (this._coneOuterAngle < value) {
  72071. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72072. return;
  72073. }
  72074. this._coneInnerAngle = value;
  72075. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72076. var sound = _a[_i];
  72077. sound.directionalConeInnerAngle = value;
  72078. }
  72079. }
  72080. },
  72081. enumerable: true,
  72082. configurable: true
  72083. });
  72084. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  72085. /**
  72086. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72087. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72088. */
  72089. get: function () {
  72090. return this._coneOuterAngle;
  72091. },
  72092. /**
  72093. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72094. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72095. */
  72096. set: function (value) {
  72097. if (value !== this._coneOuterAngle) {
  72098. if (value < this._coneInnerAngle) {
  72099. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72100. return;
  72101. }
  72102. this._coneOuterAngle = value;
  72103. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72104. var sound = _a[_i];
  72105. sound.directionalConeOuterAngle = value;
  72106. }
  72107. }
  72108. },
  72109. enumerable: true,
  72110. configurable: true
  72111. });
  72112. Object.defineProperty(WeightedSound.prototype, "volume", {
  72113. /**
  72114. * Playback volume.
  72115. */
  72116. get: function () {
  72117. return this._volume;
  72118. },
  72119. /**
  72120. * Playback volume.
  72121. */
  72122. set: function (value) {
  72123. if (value !== this._volume) {
  72124. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72125. var sound = _a[_i];
  72126. sound.setVolume(value);
  72127. }
  72128. }
  72129. },
  72130. enumerable: true,
  72131. configurable: true
  72132. });
  72133. WeightedSound.prototype._onended = function () {
  72134. if (this._currentIndex !== undefined) {
  72135. this._sounds[this._currentIndex].autoplay = false;
  72136. }
  72137. if (this.loop && this.isPlaying) {
  72138. this.play();
  72139. }
  72140. else {
  72141. this.isPlaying = false;
  72142. }
  72143. };
  72144. /**
  72145. * Suspend playback
  72146. */
  72147. WeightedSound.prototype.pause = function () {
  72148. this.isPaused = true;
  72149. if (this._currentIndex !== undefined) {
  72150. this._sounds[this._currentIndex].pause();
  72151. }
  72152. };
  72153. /**
  72154. * Stop playback
  72155. */
  72156. WeightedSound.prototype.stop = function () {
  72157. this.isPlaying = false;
  72158. if (this._currentIndex !== undefined) {
  72159. this._sounds[this._currentIndex].stop();
  72160. }
  72161. };
  72162. /**
  72163. * Start playback.
  72164. * @param startOffset Position the clip head at a specific time in seconds.
  72165. */
  72166. WeightedSound.prototype.play = function (startOffset) {
  72167. if (!this.isPaused) {
  72168. this.stop();
  72169. var randomValue = Math.random();
  72170. var total = 0;
  72171. for (var i = 0; i < this._weights.length; i++) {
  72172. total += this._weights[i];
  72173. if (randomValue <= total) {
  72174. this._currentIndex = i;
  72175. break;
  72176. }
  72177. }
  72178. }
  72179. var sound = this._sounds[this._currentIndex];
  72180. if (sound.isReady()) {
  72181. sound.play(0, this.isPaused ? undefined : startOffset);
  72182. }
  72183. else {
  72184. sound.autoplay = true;
  72185. }
  72186. this.isPlaying = true;
  72187. this.isPaused = false;
  72188. };
  72189. return WeightedSound;
  72190. }());
  72191. BABYLON.WeightedSound = WeightedSound;
  72192. })(BABYLON || (BABYLON = {}));
  72193. //# sourceMappingURL=babylon.weightedsound.js.map
  72194. var BABYLON;
  72195. (function (BABYLON) {
  72196. // Adds the parser to the scene parsers.
  72197. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  72198. // TODO: add sound
  72199. var loadedSounds = [];
  72200. var loadedSound;
  72201. container.sounds = container.sounds || [];
  72202. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72203. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72204. var parsedSound = parsedData.sounds[index];
  72205. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72206. if (!parsedSound.url) {
  72207. parsedSound.url = parsedSound.name;
  72208. }
  72209. if (!loadedSounds[parsedSound.url]) {
  72210. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72211. loadedSounds[parsedSound.url] = loadedSound;
  72212. container.sounds.push(loadedSound);
  72213. }
  72214. else {
  72215. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72216. }
  72217. }
  72218. else {
  72219. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72220. }
  72221. }
  72222. }
  72223. loadedSounds = [];
  72224. });
  72225. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  72226. get: function () {
  72227. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72228. if (!compo) {
  72229. compo = new AudioSceneComponent(this);
  72230. this._addComponent(compo);
  72231. }
  72232. if (!this._mainSoundTrack) {
  72233. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  72234. }
  72235. return this._mainSoundTrack;
  72236. },
  72237. enumerable: true,
  72238. configurable: true
  72239. });
  72240. BABYLON.Scene.prototype.getSoundByName = function (name) {
  72241. var index;
  72242. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  72243. if (this.mainSoundTrack.soundCollection[index].name === name) {
  72244. return this.mainSoundTrack.soundCollection[index];
  72245. }
  72246. }
  72247. if (this.soundTracks) {
  72248. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  72249. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  72250. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  72251. return this.soundTracks[sdIndex].soundCollection[index];
  72252. }
  72253. }
  72254. }
  72255. }
  72256. return null;
  72257. };
  72258. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  72259. get: function () {
  72260. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72261. if (!compo) {
  72262. compo = new AudioSceneComponent(this);
  72263. this._addComponent(compo);
  72264. }
  72265. return compo.audioEnabled;
  72266. },
  72267. set: function (value) {
  72268. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72269. if (!compo) {
  72270. compo = new AudioSceneComponent(this);
  72271. this._addComponent(compo);
  72272. }
  72273. if (value) {
  72274. compo.enableAudio();
  72275. }
  72276. else {
  72277. compo.disableAudio();
  72278. }
  72279. },
  72280. enumerable: true,
  72281. configurable: true
  72282. });
  72283. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  72284. get: function () {
  72285. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72286. if (!compo) {
  72287. compo = new AudioSceneComponent(this);
  72288. this._addComponent(compo);
  72289. }
  72290. return compo.headphone;
  72291. },
  72292. set: function (value) {
  72293. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72294. if (!compo) {
  72295. compo = new AudioSceneComponent(this);
  72296. this._addComponent(compo);
  72297. }
  72298. if (value) {
  72299. compo.switchAudioModeForHeadphones();
  72300. }
  72301. else {
  72302. compo.switchAudioModeForNormalSpeakers();
  72303. }
  72304. },
  72305. enumerable: true,
  72306. configurable: true
  72307. });
  72308. /**
  72309. * Defines the sound scene component responsible to manage any sounds
  72310. * in a given scene.
  72311. */
  72312. var AudioSceneComponent = /** @class */ (function () {
  72313. /**
  72314. * Creates a new instance of the component for the given scene
  72315. * @param scene Defines the scene to register the component in
  72316. */
  72317. function AudioSceneComponent(scene) {
  72318. /**
  72319. * The component name helpfull to identify the component in the list of scene components.
  72320. */
  72321. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  72322. this._audioEnabled = true;
  72323. this._headphone = false;
  72324. this.scene = scene;
  72325. scene.soundTracks = new Array();
  72326. scene.sounds = new Array();
  72327. }
  72328. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  72329. /**
  72330. * Gets whether audio is enabled or not.
  72331. * Please use related enable/disable method to switch state.
  72332. */
  72333. get: function () {
  72334. return this._audioEnabled;
  72335. },
  72336. enumerable: true,
  72337. configurable: true
  72338. });
  72339. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  72340. /**
  72341. * Gets whether audio is outputing to headphone or not.
  72342. * Please use the according Switch methods to change output.
  72343. */
  72344. get: function () {
  72345. return this._headphone;
  72346. },
  72347. enumerable: true,
  72348. configurable: true
  72349. });
  72350. /**
  72351. * Registers the component in a given scene
  72352. */
  72353. AudioSceneComponent.prototype.register = function () {
  72354. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  72355. };
  72356. /**
  72357. * Rebuilds the elements related to this component in case of
  72358. * context lost for instance.
  72359. */
  72360. AudioSceneComponent.prototype.rebuild = function () {
  72361. // Nothing to do here. (Not rendering related)
  72362. };
  72363. /**
  72364. * Serializes the component data to the specified json object
  72365. * @param serializationObject The object to serialize to
  72366. */
  72367. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  72368. serializationObject.sounds = [];
  72369. if (this.scene.soundTracks) {
  72370. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  72371. var soundtrack = this.scene.soundTracks[index];
  72372. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72373. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72374. }
  72375. }
  72376. }
  72377. };
  72378. /**
  72379. * Adds all the element from the container to the scene
  72380. * @param container the container holding the elements
  72381. */
  72382. AudioSceneComponent.prototype.addFromContainer = function (container) {
  72383. var _this = this;
  72384. if (!container.sounds) {
  72385. return;
  72386. }
  72387. container.sounds.forEach(function (sound) {
  72388. sound.play();
  72389. sound.autoplay = true;
  72390. _this.scene.mainSoundTrack.AddSound(sound);
  72391. });
  72392. };
  72393. /**
  72394. * Removes all the elements in the container from the scene
  72395. * @param container contains the elements to remove
  72396. */
  72397. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  72398. var _this = this;
  72399. if (!container.sounds) {
  72400. return;
  72401. }
  72402. container.sounds.forEach(function (sound) {
  72403. sound.stop();
  72404. sound.autoplay = false;
  72405. _this.scene.mainSoundTrack.RemoveSound(sound);
  72406. });
  72407. };
  72408. /**
  72409. * Disposes the component and the associated ressources.
  72410. */
  72411. AudioSceneComponent.prototype.dispose = function () {
  72412. var scene = this.scene;
  72413. if (scene._mainSoundTrack) {
  72414. scene.mainSoundTrack.dispose();
  72415. }
  72416. if (scene.soundTracks) {
  72417. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  72418. scene.soundTracks[scIndex].dispose();
  72419. }
  72420. }
  72421. };
  72422. /**
  72423. * Disables audio in the associated scene.
  72424. */
  72425. AudioSceneComponent.prototype.disableAudio = function () {
  72426. var scene = this.scene;
  72427. this._audioEnabled = false;
  72428. var i;
  72429. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72430. scene.mainSoundTrack.soundCollection[i].pause();
  72431. }
  72432. if (scene.soundTracks) {
  72433. for (i = 0; i < scene.soundTracks.length; i++) {
  72434. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72435. scene.soundTracks[i].soundCollection[j].pause();
  72436. }
  72437. }
  72438. }
  72439. };
  72440. /**
  72441. * Enables audio in the associated scene.
  72442. */
  72443. AudioSceneComponent.prototype.enableAudio = function () {
  72444. var scene = this.scene;
  72445. this._audioEnabled = true;
  72446. var i;
  72447. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72448. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  72449. scene.mainSoundTrack.soundCollection[i].play();
  72450. }
  72451. }
  72452. if (scene.soundTracks) {
  72453. for (i = 0; i < scene.soundTracks.length; i++) {
  72454. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72455. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  72456. scene.soundTracks[i].soundCollection[j].play();
  72457. }
  72458. }
  72459. }
  72460. }
  72461. };
  72462. /**
  72463. * Switch audio to headphone output.
  72464. */
  72465. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  72466. var scene = this.scene;
  72467. this._headphone = true;
  72468. scene.mainSoundTrack.switchPanningModelToHRTF();
  72469. if (scene.soundTracks) {
  72470. for (var i = 0; i < scene.soundTracks.length; i++) {
  72471. scene.soundTracks[i].switchPanningModelToHRTF();
  72472. }
  72473. }
  72474. };
  72475. /**
  72476. * Switch audio to normal speakers.
  72477. */
  72478. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  72479. var scene = this.scene;
  72480. this._headphone = false;
  72481. scene.mainSoundTrack.switchPanningModelToEqualPower();
  72482. if (scene.soundTracks) {
  72483. for (var i = 0; i < scene.soundTracks.length; i++) {
  72484. scene.soundTracks[i].switchPanningModelToEqualPower();
  72485. }
  72486. }
  72487. };
  72488. AudioSceneComponent.prototype._afterRender = function () {
  72489. var scene = this.scene;
  72490. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  72491. return;
  72492. }
  72493. var listeningCamera;
  72494. var audioEngine = BABYLON.Engine.audioEngine;
  72495. if (scene.activeCameras.length > 0) {
  72496. listeningCamera = scene.activeCameras[0];
  72497. }
  72498. else {
  72499. listeningCamera = scene.activeCamera;
  72500. }
  72501. if (listeningCamera && audioEngine.audioContext) {
  72502. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  72503. // for VR cameras
  72504. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  72505. listeningCamera = listeningCamera.rigCameras[0];
  72506. }
  72507. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  72508. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  72509. cameraDirection.normalize();
  72510. // To avoid some errors on GearVR
  72511. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  72512. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  72513. }
  72514. var i;
  72515. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72516. var sound = scene.mainSoundTrack.soundCollection[i];
  72517. if (sound.useCustomAttenuation) {
  72518. sound.updateDistanceFromListener();
  72519. }
  72520. }
  72521. if (scene.soundTracks) {
  72522. for (i = 0; i < scene.soundTracks.length; i++) {
  72523. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72524. sound = scene.soundTracks[i].soundCollection[j];
  72525. if (sound.useCustomAttenuation) {
  72526. sound.updateDistanceFromListener();
  72527. }
  72528. }
  72529. }
  72530. }
  72531. }
  72532. };
  72533. return AudioSceneComponent;
  72534. }());
  72535. BABYLON.AudioSceneComponent = AudioSceneComponent;
  72536. })(BABYLON || (BABYLON = {}));
  72537. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  72538. var BABYLON;
  72539. (function (BABYLON) {
  72540. /**
  72541. * This defines an action helpful to play a defined sound on a triggered action.
  72542. */
  72543. var PlaySoundAction = /** @class */ (function (_super) {
  72544. __extends(PlaySoundAction, _super);
  72545. /**
  72546. * Instantiate the action
  72547. * @param triggerOptions defines the trigger options
  72548. * @param sound defines the sound to play
  72549. * @param condition defines the trigger related conditions
  72550. */
  72551. function PlaySoundAction(triggerOptions, sound, condition) {
  72552. var _this = _super.call(this, triggerOptions, condition) || this;
  72553. _this._sound = sound;
  72554. return _this;
  72555. }
  72556. /** @hidden */
  72557. PlaySoundAction.prototype._prepare = function () {
  72558. };
  72559. /**
  72560. * Execute the action and play the sound.
  72561. */
  72562. PlaySoundAction.prototype.execute = function () {
  72563. if (this._sound !== undefined) {
  72564. this._sound.play();
  72565. }
  72566. };
  72567. /**
  72568. * Serializes the actions and its related information.
  72569. * @param parent defines the object to serialize in
  72570. * @returns the serialized object
  72571. */
  72572. PlaySoundAction.prototype.serialize = function (parent) {
  72573. return _super.prototype._serialize.call(this, {
  72574. name: "PlaySoundAction",
  72575. properties: [{ name: "sound", value: this._sound.name }]
  72576. }, parent);
  72577. };
  72578. return PlaySoundAction;
  72579. }(BABYLON.Action));
  72580. BABYLON.PlaySoundAction = PlaySoundAction;
  72581. /**
  72582. * This defines an action helpful to stop a defined sound on a triggered action.
  72583. */
  72584. var StopSoundAction = /** @class */ (function (_super) {
  72585. __extends(StopSoundAction, _super);
  72586. /**
  72587. * Instantiate the action
  72588. * @param triggerOptions defines the trigger options
  72589. * @param sound defines the sound to stop
  72590. * @param condition defines the trigger related conditions
  72591. */
  72592. function StopSoundAction(triggerOptions, sound, condition) {
  72593. var _this = _super.call(this, triggerOptions, condition) || this;
  72594. _this._sound = sound;
  72595. return _this;
  72596. }
  72597. /** @hidden */
  72598. StopSoundAction.prototype._prepare = function () {
  72599. };
  72600. /**
  72601. * Execute the action and stop the sound.
  72602. */
  72603. StopSoundAction.prototype.execute = function () {
  72604. if (this._sound !== undefined) {
  72605. this._sound.stop();
  72606. }
  72607. };
  72608. /**
  72609. * Serializes the actions and its related information.
  72610. * @param parent defines the object to serialize in
  72611. * @returns the serialized object
  72612. */
  72613. StopSoundAction.prototype.serialize = function (parent) {
  72614. return _super.prototype._serialize.call(this, {
  72615. name: "StopSoundAction",
  72616. properties: [{ name: "sound", value: this._sound.name }]
  72617. }, parent);
  72618. };
  72619. return StopSoundAction;
  72620. }(BABYLON.Action));
  72621. BABYLON.StopSoundAction = StopSoundAction;
  72622. })(BABYLON || (BABYLON = {}));
  72623. //# sourceMappingURL=babylon.directAudioActions.js.map
  72624. var BABYLON;
  72625. (function (BABYLON) {
  72626. /**
  72627. * Class for creating a cube texture
  72628. */
  72629. var CubeTexture = /** @class */ (function (_super) {
  72630. __extends(CubeTexture, _super);
  72631. /**
  72632. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  72633. * as prefiltered data.
  72634. * @param rootUrl defines the url of the texture or the root name of the six images
  72635. * @param scene defines the scene the texture is attached to
  72636. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  72637. * @param noMipmap defines if mipmaps should be created or not
  72638. * @param files defines the six files to load for the different faces
  72639. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  72640. * @param onError defines a callback triggered in case of error during load
  72641. * @param format defines the internal format to use for the texture once loaded
  72642. * @param prefiltered defines whether or not the texture is created from prefiltered data
  72643. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  72644. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72645. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72646. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72647. * @return the cube texture
  72648. */
  72649. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  72650. if (extensions === void 0) { extensions = null; }
  72651. if (noMipmap === void 0) { noMipmap = false; }
  72652. if (files === void 0) { files = null; }
  72653. if (onLoad === void 0) { onLoad = null; }
  72654. if (onError === void 0) { onError = null; }
  72655. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72656. if (prefiltered === void 0) { prefiltered = false; }
  72657. if (forcedExtension === void 0) { forcedExtension = null; }
  72658. if (createPolynomials === void 0) { createPolynomials = false; }
  72659. if (lodScale === void 0) { lodScale = 0.8; }
  72660. if (lodOffset === void 0) { lodOffset = 0; }
  72661. var _this = _super.call(this, scene) || this;
  72662. /**
  72663. * Gets or sets the center of the bounding box associated with the cube texture.
  72664. * It must define where the camera used to render the texture was set
  72665. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72666. */
  72667. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72668. _this._rotationY = 0;
  72669. /** @hidden */
  72670. _this._prefiltered = false;
  72671. _this.name = rootUrl;
  72672. _this.url = rootUrl;
  72673. _this._noMipmap = noMipmap;
  72674. _this.hasAlpha = false;
  72675. _this._format = format;
  72676. _this.isCube = true;
  72677. _this._textureMatrix = BABYLON.Matrix.Identity();
  72678. _this._createPolynomials = createPolynomials;
  72679. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72680. if (!rootUrl && !files) {
  72681. return _this;
  72682. }
  72683. var lastDot = rootUrl.lastIndexOf(".");
  72684. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  72685. var isDDS = (extension === ".dds");
  72686. var isEnv = (extension === ".env");
  72687. if (isEnv) {
  72688. _this.gammaSpace = false;
  72689. _this._prefiltered = false;
  72690. }
  72691. else {
  72692. _this._prefiltered = prefiltered;
  72693. if (prefiltered) {
  72694. _this.gammaSpace = false;
  72695. }
  72696. }
  72697. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  72698. if (!files) {
  72699. if (!isEnv && !isDDS && !extensions) {
  72700. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  72701. }
  72702. files = [];
  72703. if (extensions) {
  72704. for (var index = 0; index < extensions.length; index++) {
  72705. files.push(rootUrl + extensions[index]);
  72706. }
  72707. }
  72708. }
  72709. _this._files = files;
  72710. if (!_this._texture) {
  72711. if (!scene.useDelayedTextureLoading) {
  72712. if (prefiltered) {
  72713. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  72714. }
  72715. else {
  72716. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  72717. }
  72718. }
  72719. else {
  72720. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72721. }
  72722. }
  72723. else if (onLoad) {
  72724. if (_this._texture.isReady) {
  72725. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  72726. }
  72727. else {
  72728. _this._texture.onLoadedObservable.add(onLoad);
  72729. }
  72730. }
  72731. return _this;
  72732. }
  72733. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  72734. /**
  72735. * Returns the bounding box size
  72736. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72737. */
  72738. get: function () {
  72739. return this._boundingBoxSize;
  72740. },
  72741. /**
  72742. * Gets or sets the size of the bounding box associated with the cube texture
  72743. * When defined, the cubemap will switch to local mode
  72744. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72745. * @example https://www.babylonjs-playground.com/#RNASML
  72746. */
  72747. set: function (value) {
  72748. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72749. return;
  72750. }
  72751. this._boundingBoxSize = value;
  72752. var scene = this.getScene();
  72753. if (scene) {
  72754. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72755. }
  72756. },
  72757. enumerable: true,
  72758. configurable: true
  72759. });
  72760. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  72761. /**
  72762. * Gets texture matrix rotation angle around Y axis radians.
  72763. */
  72764. get: function () {
  72765. return this._rotationY;
  72766. },
  72767. /**
  72768. * Sets texture matrix rotation angle around Y axis in radians.
  72769. */
  72770. set: function (value) {
  72771. this._rotationY = value;
  72772. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  72773. },
  72774. enumerable: true,
  72775. configurable: true
  72776. });
  72777. /**
  72778. * Creates a cube texture from an array of image urls
  72779. * @param files defines an array of image urls
  72780. * @param scene defines the hosting scene
  72781. * @param noMipmap specifies if mip maps are not used
  72782. * @returns a cube texture
  72783. */
  72784. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  72785. var rootUrlKey = "";
  72786. files.forEach(function (url) { return rootUrlKey += url; });
  72787. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  72788. };
  72789. /**
  72790. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  72791. * @param url defines the url of the prefiltered texture
  72792. * @param scene defines the scene the texture is attached to
  72793. * @param forcedExtension defines the extension of the file if different from the url
  72794. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72795. * @return the prefiltered texture
  72796. */
  72797. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  72798. if (forcedExtension === void 0) { forcedExtension = null; }
  72799. if (createPolynomials === void 0) { createPolynomials = true; }
  72800. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  72801. };
  72802. /**
  72803. * Delays loading of the cube texture
  72804. */
  72805. CubeTexture.prototype.delayLoad = function () {
  72806. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72807. return;
  72808. }
  72809. var scene = this.getScene();
  72810. if (!scene) {
  72811. return;
  72812. }
  72813. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72814. this._texture = this._getFromCache(this.url, this._noMipmap);
  72815. if (!this._texture) {
  72816. if (this._prefiltered) {
  72817. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  72818. }
  72819. else {
  72820. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  72821. }
  72822. }
  72823. };
  72824. /**
  72825. * Returns the reflection texture matrix
  72826. * @returns the reflection texture matrix
  72827. */
  72828. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  72829. return this._textureMatrix;
  72830. };
  72831. /**
  72832. * Sets the reflection texture matrix
  72833. * @param value Reflection texture matrix
  72834. */
  72835. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72836. this._textureMatrix = value;
  72837. };
  72838. /**
  72839. * Parses text to create a cube texture
  72840. * @param parsedTexture define the serialized text to read from
  72841. * @param scene defines the hosting scene
  72842. * @param rootUrl defines the root url of the cube texture
  72843. * @returns a cube texture
  72844. */
  72845. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72846. var texture = BABYLON.SerializationHelper.Parse(function () {
  72847. var prefiltered = false;
  72848. if (parsedTexture.prefiltered) {
  72849. prefiltered = parsedTexture.prefiltered;
  72850. }
  72851. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  72852. }, parsedTexture, scene);
  72853. // Local Cubemaps
  72854. if (parsedTexture.boundingBoxPosition) {
  72855. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72856. }
  72857. if (parsedTexture.boundingBoxSize) {
  72858. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72859. }
  72860. // Animations
  72861. if (parsedTexture.animations) {
  72862. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  72863. var parsedAnimation = parsedTexture.animations[animationIndex];
  72864. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  72865. }
  72866. }
  72867. return texture;
  72868. };
  72869. /**
  72870. * Makes a clone, or deep copy, of the cube texture
  72871. * @returns a new cube texture
  72872. */
  72873. CubeTexture.prototype.clone = function () {
  72874. var _this = this;
  72875. return BABYLON.SerializationHelper.Clone(function () {
  72876. var scene = _this.getScene();
  72877. if (!scene) {
  72878. return _this;
  72879. }
  72880. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  72881. }, this);
  72882. };
  72883. __decorate([
  72884. BABYLON.serialize("rotationY")
  72885. ], CubeTexture.prototype, "rotationY", null);
  72886. return CubeTexture;
  72887. }(BABYLON.BaseTexture));
  72888. BABYLON.CubeTexture = CubeTexture;
  72889. })(BABYLON || (BABYLON = {}));
  72890. //# sourceMappingURL=babylon.cubeTexture.js.map
  72891. var BABYLON;
  72892. (function (BABYLON) {
  72893. /**
  72894. * Raw cube texture where the raw buffers are passed in
  72895. */
  72896. var RawCubeTexture = /** @class */ (function (_super) {
  72897. __extends(RawCubeTexture, _super);
  72898. /**
  72899. * Creates a cube texture where the raw buffers are passed in.
  72900. * @param scene defines the scene the texture is attached to
  72901. * @param data defines the array of data to use to create each face
  72902. * @param size defines the size of the textures
  72903. * @param format defines the format of the data
  72904. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  72905. * @param generateMipMaps defines if the engine should generate the mip levels
  72906. * @param invertY defines if data must be stored with Y axis inverted
  72907. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  72908. * @param compression defines the compression used (null by default)
  72909. */
  72910. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  72911. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72912. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72913. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72914. if (invertY === void 0) { invertY = false; }
  72915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72916. if (compression === void 0) { compression = null; }
  72917. var _this = _super.call(this, "", scene) || this;
  72918. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  72919. return _this;
  72920. }
  72921. /**
  72922. * Updates the raw cube texture.
  72923. * @param data defines the data to store
  72924. * @param format defines the data format
  72925. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  72926. * @param invertY defines if data must be stored with Y axis inverted
  72927. * @param compression defines the compression used (null by default)
  72928. * @param level defines which level of the texture to update
  72929. */
  72930. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  72931. if (compression === void 0) { compression = null; }
  72932. if (level === void 0) { level = 0; }
  72933. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  72934. };
  72935. /**
  72936. * Updates a raw cube texture with RGBD encoded data.
  72937. * @param data defines the array of data [mipmap][face] to use to create each face
  72938. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  72939. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72940. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72941. * @returns a promsie that resolves when the operation is complete
  72942. */
  72943. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  72944. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  72945. if (lodScale === void 0) { lodScale = 0.8; }
  72946. if (lodOffset === void 0) { lodOffset = 0; }
  72947. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  72948. };
  72949. /**
  72950. * Clones the raw cube texture.
  72951. * @return a new cube texture
  72952. */
  72953. RawCubeTexture.prototype.clone = function () {
  72954. var _this = this;
  72955. return BABYLON.SerializationHelper.Clone(function () {
  72956. var scene = _this.getScene();
  72957. var internalTexture = _this._texture;
  72958. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  72959. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  72960. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  72961. }
  72962. return texture;
  72963. }, this);
  72964. };
  72965. /** @hidden */
  72966. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  72967. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  72968. internalTexture._bufferViewArrayArray = data;
  72969. internalTexture._lodGenerationScale = lodScale;
  72970. internalTexture._lodGenerationOffset = lodOffset;
  72971. internalTexture._sphericalPolynomial = sphericalPolynomial;
  72972. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  72973. internalTexture.isReady = true;
  72974. });
  72975. };
  72976. return RawCubeTexture;
  72977. }(BABYLON.CubeTexture));
  72978. BABYLON.RawCubeTexture = RawCubeTexture;
  72979. })(BABYLON || (BABYLON = {}));
  72980. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  72981. var BABYLON;
  72982. (function (BABYLON) {
  72983. /**
  72984. * This Helps creating a texture that will be created from a camera in your scene.
  72985. * It is basically a dynamic texture that could be used to create special effects for instance.
  72986. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  72987. */
  72988. var RenderTargetTexture = /** @class */ (function (_super) {
  72989. __extends(RenderTargetTexture, _super);
  72990. /**
  72991. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  72992. * or used a shadow, depth texture...
  72993. * @param name The friendly name of the texture
  72994. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  72995. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  72996. * @param generateMipMaps True if mip maps need to be generated after render.
  72997. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  72998. * @param type The type of the buffer in the RTT (int, half float, float...)
  72999. * @param isCube True if a cube texture needs to be created
  73000. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  73001. * @param generateDepthBuffer True to generate a depth buffer
  73002. * @param generateStencilBuffer True to generate a stencil buffer
  73003. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  73004. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  73005. * @param delayAllocation if the texture allocation should be delayed (default: false)
  73006. */
  73007. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) {
  73008. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  73009. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73010. if (isCube === void 0) { isCube = false; }
  73011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73012. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  73013. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  73014. if (isMulti === void 0) { isMulti = false; }
  73015. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73016. if (delayAllocation === void 0) { delayAllocation = false; }
  73017. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73018. _this.isCube = isCube;
  73019. /**
  73020. * Define if particles should be rendered in your texture.
  73021. */
  73022. _this.renderParticles = true;
  73023. /**
  73024. * Define if sprites should be rendered in your texture.
  73025. */
  73026. _this.renderSprites = false;
  73027. /**
  73028. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  73029. */
  73030. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  73031. /**
  73032. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  73033. */
  73034. _this.ignoreCameraViewport = false;
  73035. /**
  73036. * An event triggered when the texture is unbind.
  73037. */
  73038. _this.onBeforeBindObservable = new BABYLON.Observable();
  73039. /**
  73040. * An event triggered when the texture is unbind.
  73041. */
  73042. _this.onAfterUnbindObservable = new BABYLON.Observable();
  73043. /**
  73044. * An event triggered before rendering the texture
  73045. */
  73046. _this.onBeforeRenderObservable = new BABYLON.Observable();
  73047. /**
  73048. * An event triggered after rendering the texture
  73049. */
  73050. _this.onAfterRenderObservable = new BABYLON.Observable();
  73051. /**
  73052. * An event triggered after the texture clear
  73053. */
  73054. _this.onClearObservable = new BABYLON.Observable();
  73055. _this._currentRefreshId = -1;
  73056. _this._refreshRate = 1;
  73057. _this._samples = 1;
  73058. /**
  73059. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  73060. * It must define where the camera used to render the texture is set
  73061. */
  73062. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73063. scene = _this.getScene();
  73064. if (!scene) {
  73065. return _this;
  73066. }
  73067. _this.renderList = new Array();
  73068. _this._engine = scene.getEngine();
  73069. _this.name = name;
  73070. _this.isRenderTarget = true;
  73071. _this._initialSizeParameter = size;
  73072. _this._processSizeParameter(size);
  73073. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  73074. });
  73075. _this._generateMipMaps = generateMipMaps ? true : false;
  73076. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  73077. // Rendering groups
  73078. _this._renderingManager = new BABYLON.RenderingManager(scene);
  73079. _this._renderingManager._useSceneAutoClearSetup = true;
  73080. if (isMulti) {
  73081. return _this;
  73082. }
  73083. _this._renderTargetOptions = {
  73084. generateMipMaps: generateMipMaps,
  73085. type: type,
  73086. format: format,
  73087. samplingMode: samplingMode,
  73088. generateDepthBuffer: generateDepthBuffer,
  73089. generateStencilBuffer: generateStencilBuffer
  73090. };
  73091. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  73092. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73093. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73094. }
  73095. if (!delayAllocation) {
  73096. if (isCube) {
  73097. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  73098. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  73099. _this._textureMatrix = BABYLON.Matrix.Identity();
  73100. }
  73101. else {
  73102. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  73103. }
  73104. }
  73105. return _this;
  73106. }
  73107. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  73108. /**
  73109. * Use this list to define the list of mesh you want to render.
  73110. */
  73111. get: function () {
  73112. return this._renderList;
  73113. },
  73114. set: function (value) {
  73115. this._renderList = value;
  73116. if (this._renderList) {
  73117. this._hookArray(this._renderList);
  73118. }
  73119. },
  73120. enumerable: true,
  73121. configurable: true
  73122. });
  73123. RenderTargetTexture.prototype._hookArray = function (array) {
  73124. var _this = this;
  73125. var oldPush = array.push;
  73126. array.push = function () {
  73127. var items = [];
  73128. for (var _i = 0; _i < arguments.length; _i++) {
  73129. items[_i] = arguments[_i];
  73130. }
  73131. var wasEmpty = array.length === 0;
  73132. var result = oldPush.apply(array, items);
  73133. if (wasEmpty) {
  73134. _this.getScene().meshes.forEach(function (mesh) {
  73135. mesh._markSubMeshesAsLightDirty();
  73136. });
  73137. }
  73138. return result;
  73139. };
  73140. var oldSplice = array.splice;
  73141. array.splice = function (index, deleteCount) {
  73142. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73143. if (array.length === 0) {
  73144. _this.getScene().meshes.forEach(function (mesh) {
  73145. mesh._markSubMeshesAsLightDirty();
  73146. });
  73147. }
  73148. return deleted;
  73149. };
  73150. };
  73151. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  73152. /**
  73153. * Set a after unbind callback in the texture.
  73154. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  73155. */
  73156. set: function (callback) {
  73157. if (this._onAfterUnbindObserver) {
  73158. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  73159. }
  73160. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  73161. },
  73162. enumerable: true,
  73163. configurable: true
  73164. });
  73165. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  73166. /**
  73167. * Set a before render callback in the texture.
  73168. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  73169. */
  73170. set: function (callback) {
  73171. if (this._onBeforeRenderObserver) {
  73172. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73173. }
  73174. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73175. },
  73176. enumerable: true,
  73177. configurable: true
  73178. });
  73179. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  73180. /**
  73181. * Set a after render callback in the texture.
  73182. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  73183. */
  73184. set: function (callback) {
  73185. if (this._onAfterRenderObserver) {
  73186. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73187. }
  73188. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73189. },
  73190. enumerable: true,
  73191. configurable: true
  73192. });
  73193. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  73194. /**
  73195. * Set a clear callback in the texture.
  73196. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  73197. */
  73198. set: function (callback) {
  73199. if (this._onClearObserver) {
  73200. this.onClearObservable.remove(this._onClearObserver);
  73201. }
  73202. this._onClearObserver = this.onClearObservable.add(callback);
  73203. },
  73204. enumerable: true,
  73205. configurable: true
  73206. });
  73207. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  73208. /**
  73209. * Gets render target creation options that were used.
  73210. */
  73211. get: function () {
  73212. return this._renderTargetOptions;
  73213. },
  73214. enumerable: true,
  73215. configurable: true
  73216. });
  73217. RenderTargetTexture.prototype._onRatioRescale = function () {
  73218. if (this._sizeRatio) {
  73219. this.resize(this._initialSizeParameter);
  73220. }
  73221. };
  73222. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  73223. get: function () {
  73224. return this._boundingBoxSize;
  73225. },
  73226. /**
  73227. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  73228. * When defined, the cubemap will switch to local mode
  73229. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73230. * @example https://www.babylonjs-playground.com/#RNASML
  73231. */
  73232. set: function (value) {
  73233. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73234. return;
  73235. }
  73236. this._boundingBoxSize = value;
  73237. var scene = this.getScene();
  73238. if (scene) {
  73239. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73240. }
  73241. },
  73242. enumerable: true,
  73243. configurable: true
  73244. });
  73245. /**
  73246. * Creates a depth stencil texture.
  73247. * This is only available in WebGL 2 or with the depth texture extension available.
  73248. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  73249. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  73250. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  73251. */
  73252. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  73253. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  73254. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  73255. if (generateStencil === void 0) { generateStencil = false; }
  73256. if (!this.getScene()) {
  73257. return;
  73258. }
  73259. var engine = this.getScene().getEngine();
  73260. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  73261. bilinearFiltering: bilinearFiltering,
  73262. comparisonFunction: comparisonFunction,
  73263. generateStencil: generateStencil,
  73264. isCube: this.isCube
  73265. });
  73266. engine.setFrameBufferDepthStencilTexture(this);
  73267. };
  73268. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  73269. if (size.ratio) {
  73270. this._sizeRatio = size.ratio;
  73271. this._size = {
  73272. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  73273. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  73274. };
  73275. }
  73276. else {
  73277. this._size = size;
  73278. }
  73279. };
  73280. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  73281. /**
  73282. * Define the number of samples to use in case of MSAA.
  73283. * It defaults to one meaning no MSAA has been enabled.
  73284. */
  73285. get: function () {
  73286. return this._samples;
  73287. },
  73288. set: function (value) {
  73289. if (this._samples === value) {
  73290. return;
  73291. }
  73292. var scene = this.getScene();
  73293. if (!scene) {
  73294. return;
  73295. }
  73296. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  73297. },
  73298. enumerable: true,
  73299. configurable: true
  73300. });
  73301. /**
  73302. * Resets the refresh counter of the texture and start bak from scratch.
  73303. * Could be usefull to regenerate the texture if it is setup to render only once.
  73304. */
  73305. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  73306. this._currentRefreshId = -1;
  73307. };
  73308. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  73309. /**
  73310. * Define the refresh rate of the texture or the rendering frequency.
  73311. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73312. */
  73313. get: function () {
  73314. return this._refreshRate;
  73315. },
  73316. set: function (value) {
  73317. this._refreshRate = value;
  73318. this.resetRefreshCounter();
  73319. },
  73320. enumerable: true,
  73321. configurable: true
  73322. });
  73323. /**
  73324. * Adds a post process to the render target rendering passes.
  73325. * @param postProcess define the post process to add
  73326. */
  73327. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  73328. if (!this._postProcessManager) {
  73329. var scene = this.getScene();
  73330. if (!scene) {
  73331. return;
  73332. }
  73333. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  73334. this._postProcesses = new Array();
  73335. }
  73336. this._postProcesses.push(postProcess);
  73337. this._postProcesses[0].autoClear = false;
  73338. };
  73339. /**
  73340. * Clear all the post processes attached to the render target
  73341. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  73342. */
  73343. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  73344. if (dispose === void 0) { dispose = false; }
  73345. if (!this._postProcesses) {
  73346. return;
  73347. }
  73348. if (dispose) {
  73349. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  73350. var postProcess = _a[_i];
  73351. postProcess.dispose();
  73352. }
  73353. }
  73354. this._postProcesses = [];
  73355. };
  73356. /**
  73357. * Remove one of the post process from the list of attached post processes to the texture
  73358. * @param postProcess define the post process to remove from the list
  73359. */
  73360. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  73361. if (!this._postProcesses) {
  73362. return;
  73363. }
  73364. var index = this._postProcesses.indexOf(postProcess);
  73365. if (index === -1) {
  73366. return;
  73367. }
  73368. this._postProcesses.splice(index, 1);
  73369. if (this._postProcesses.length > 0) {
  73370. this._postProcesses[0].autoClear = false;
  73371. }
  73372. };
  73373. /** @hidden */
  73374. RenderTargetTexture.prototype._shouldRender = function () {
  73375. if (this._currentRefreshId === -1) { // At least render once
  73376. this._currentRefreshId = 1;
  73377. return true;
  73378. }
  73379. if (this.refreshRate === this._currentRefreshId) {
  73380. this._currentRefreshId = 1;
  73381. return true;
  73382. }
  73383. this._currentRefreshId++;
  73384. return false;
  73385. };
  73386. /**
  73387. * Gets the actual render size of the texture.
  73388. * @returns the width of the render size
  73389. */
  73390. RenderTargetTexture.prototype.getRenderSize = function () {
  73391. return this.getRenderWidth();
  73392. };
  73393. /**
  73394. * Gets the actual render width of the texture.
  73395. * @returns the width of the render size
  73396. */
  73397. RenderTargetTexture.prototype.getRenderWidth = function () {
  73398. if (this._size.width) {
  73399. return this._size.width;
  73400. }
  73401. return this._size;
  73402. };
  73403. /**
  73404. * Gets the actual render height of the texture.
  73405. * @returns the height of the render size
  73406. */
  73407. RenderTargetTexture.prototype.getRenderHeight = function () {
  73408. if (this._size.width) {
  73409. return this._size.height;
  73410. }
  73411. return this._size;
  73412. };
  73413. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  73414. /**
  73415. * Get if the texture can be rescaled or not.
  73416. */
  73417. get: function () {
  73418. return true;
  73419. },
  73420. enumerable: true,
  73421. configurable: true
  73422. });
  73423. /**
  73424. * Resize the texture using a ratio.
  73425. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  73426. */
  73427. RenderTargetTexture.prototype.scale = function (ratio) {
  73428. var newSize = this.getRenderSize() * ratio;
  73429. this.resize(newSize);
  73430. };
  73431. /**
  73432. * Get the texture reflection matrix used to rotate/transform the reflection.
  73433. * @returns the reflection matrix
  73434. */
  73435. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  73436. if (this.isCube) {
  73437. return this._textureMatrix;
  73438. }
  73439. return _super.prototype.getReflectionTextureMatrix.call(this);
  73440. };
  73441. /**
  73442. * Resize the texture to a new desired size.
  73443. * Be carrefull as it will recreate all the data in the new texture.
  73444. * @param size Define the new size. It can be:
  73445. * - a number for squared texture,
  73446. * - an object containing { width: number, height: number }
  73447. * - or an object containing a ratio { ratio: number }
  73448. */
  73449. RenderTargetTexture.prototype.resize = function (size) {
  73450. this.releaseInternalTexture();
  73451. var scene = this.getScene();
  73452. if (!scene) {
  73453. return;
  73454. }
  73455. this._processSizeParameter(size);
  73456. if (this.isCube) {
  73457. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  73458. }
  73459. else {
  73460. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  73461. }
  73462. };
  73463. /**
  73464. * Renders all the objects from the render list into the texture.
  73465. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  73466. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  73467. */
  73468. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  73469. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  73470. if (dumpForDebug === void 0) { dumpForDebug = false; }
  73471. var scene = this.getScene();
  73472. if (!scene) {
  73473. return;
  73474. }
  73475. var engine = scene.getEngine();
  73476. if (this.useCameraPostProcesses !== undefined) {
  73477. useCameraPostProcess = this.useCameraPostProcesses;
  73478. }
  73479. if (this._waitingRenderList) {
  73480. this.renderList = [];
  73481. for (var index = 0; index < this._waitingRenderList.length; index++) {
  73482. var id = this._waitingRenderList[index];
  73483. var mesh_1 = scene.getMeshByID(id);
  73484. if (mesh_1) {
  73485. this.renderList.push(mesh_1);
  73486. }
  73487. }
  73488. delete this._waitingRenderList;
  73489. }
  73490. // Is predicate defined?
  73491. if (this.renderListPredicate) {
  73492. if (this.renderList) {
  73493. this.renderList.length = 0; // Clear previous renderList
  73494. }
  73495. else {
  73496. this.renderList = [];
  73497. }
  73498. var scene = this.getScene();
  73499. if (!scene) {
  73500. return;
  73501. }
  73502. var sceneMeshes = scene.meshes;
  73503. for (var index = 0; index < sceneMeshes.length; index++) {
  73504. var mesh = sceneMeshes[index];
  73505. if (this.renderListPredicate(mesh)) {
  73506. this.renderList.push(mesh);
  73507. }
  73508. }
  73509. }
  73510. this.onBeforeBindObservable.notifyObservers(this);
  73511. // Set custom projection.
  73512. // Needs to be before binding to prevent changing the aspect ratio.
  73513. var camera;
  73514. if (this.activeCamera) {
  73515. camera = this.activeCamera;
  73516. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73517. if (this.activeCamera !== scene.activeCamera) {
  73518. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  73519. }
  73520. }
  73521. else {
  73522. camera = scene.activeCamera;
  73523. if (camera) {
  73524. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73525. }
  73526. }
  73527. // Prepare renderingManager
  73528. this._renderingManager.reset();
  73529. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  73530. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  73531. var sceneRenderId = scene.getRenderId();
  73532. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  73533. var mesh = currentRenderList[meshIndex];
  73534. if (mesh) {
  73535. if (!mesh.isReady(this.refreshRate === 0)) {
  73536. this.resetRefreshCounter();
  73537. continue;
  73538. }
  73539. mesh._preActivateForIntermediateRendering(sceneRenderId);
  73540. var isMasked = void 0;
  73541. if (!this.renderList && camera) {
  73542. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  73543. }
  73544. else {
  73545. isMasked = false;
  73546. }
  73547. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  73548. mesh._activate(sceneRenderId);
  73549. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  73550. var subMesh = mesh.subMeshes[subIndex];
  73551. scene._activeIndices.addCount(subMesh.indexCount, false);
  73552. this._renderingManager.dispatch(subMesh, mesh);
  73553. }
  73554. }
  73555. }
  73556. }
  73557. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  73558. var particleSystem = scene.particleSystems[particleIndex];
  73559. var emitter = particleSystem.emitter;
  73560. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  73561. continue;
  73562. }
  73563. if (currentRenderList.indexOf(emitter) >= 0) {
  73564. this._renderingManager.dispatchParticles(particleSystem);
  73565. }
  73566. }
  73567. if (this.isCube) {
  73568. for (var face = 0; face < 6; face++) {
  73569. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73570. scene.incrementRenderId();
  73571. scene.resetCachedMaterial();
  73572. }
  73573. }
  73574. else {
  73575. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73576. }
  73577. this.onAfterUnbindObservable.notifyObservers(this);
  73578. if (scene.activeCamera) {
  73579. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  73580. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  73581. }
  73582. engine.setViewport(scene.activeCamera.viewport);
  73583. }
  73584. scene.resetCachedMaterial();
  73585. };
  73586. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  73587. var minimum = 128;
  73588. var x = renderDimension * scale;
  73589. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  73590. // Ensure we don't exceed the render dimension (while staying POT)
  73591. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  73592. };
  73593. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73594. var _this = this;
  73595. if (!this._texture) {
  73596. return;
  73597. }
  73598. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  73599. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73600. });
  73601. };
  73602. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  73603. var scene = this.getScene();
  73604. if (!scene) {
  73605. return;
  73606. }
  73607. var engine = scene.getEngine();
  73608. if (!this._texture) {
  73609. return;
  73610. }
  73611. // Bind
  73612. if (this._postProcessManager) {
  73613. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  73614. }
  73615. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  73616. if (this._texture) {
  73617. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  73618. }
  73619. }
  73620. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  73621. // Clear
  73622. if (this.onClearObservable.hasObservers()) {
  73623. this.onClearObservable.notifyObservers(engine);
  73624. }
  73625. else {
  73626. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  73627. }
  73628. if (!this._doNotChangeAspectRatio) {
  73629. scene.updateTransformMatrix(true);
  73630. }
  73631. // Render
  73632. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  73633. if (this._postProcessManager) {
  73634. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  73635. }
  73636. else if (useCameraPostProcess) {
  73637. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  73638. }
  73639. if (!this._doNotChangeAspectRatio) {
  73640. scene.updateTransformMatrix(true);
  73641. }
  73642. // Dump ?
  73643. if (dumpForDebug) {
  73644. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  73645. }
  73646. // Unbind
  73647. if (!this.isCube || faceIndex === 5) {
  73648. if (this.isCube) {
  73649. if (faceIndex === 5) {
  73650. engine.generateMipMapsForCubemap(this._texture);
  73651. }
  73652. }
  73653. this.unbindFrameBuffer(engine, faceIndex);
  73654. }
  73655. else {
  73656. this.onAfterRenderObservable.notifyObservers(faceIndex);
  73657. }
  73658. };
  73659. /**
  73660. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  73661. * This allowed control for front to back rendering or reversly depending of the special needs.
  73662. *
  73663. * @param renderingGroupId The rendering group id corresponding to its index
  73664. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  73665. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  73666. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  73667. */
  73668. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  73669. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  73670. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  73671. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  73672. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  73673. };
  73674. /**
  73675. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73676. *
  73677. * @param renderingGroupId The rendering group id corresponding to its index
  73678. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73679. */
  73680. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73681. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73682. this._renderingManager._useSceneAutoClearSetup = false;
  73683. };
  73684. /**
  73685. * Clones the texture.
  73686. * @returns the cloned texture
  73687. */
  73688. RenderTargetTexture.prototype.clone = function () {
  73689. var textureSize = this.getSize();
  73690. 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);
  73691. // Base texture
  73692. newTexture.hasAlpha = this.hasAlpha;
  73693. newTexture.level = this.level;
  73694. // RenderTarget Texture
  73695. newTexture.coordinatesMode = this.coordinatesMode;
  73696. if (this.renderList) {
  73697. newTexture.renderList = this.renderList.slice(0);
  73698. }
  73699. return newTexture;
  73700. };
  73701. /**
  73702. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  73703. * @returns The JSON representation of the texture
  73704. */
  73705. RenderTargetTexture.prototype.serialize = function () {
  73706. if (!this.name) {
  73707. return null;
  73708. }
  73709. var serializationObject = _super.prototype.serialize.call(this);
  73710. serializationObject.renderTargetSize = this.getRenderSize();
  73711. serializationObject.renderList = [];
  73712. if (this.renderList) {
  73713. for (var index = 0; index < this.renderList.length; index++) {
  73714. serializationObject.renderList.push(this.renderList[index].id);
  73715. }
  73716. }
  73717. return serializationObject;
  73718. };
  73719. /**
  73720. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  73721. */
  73722. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  73723. var objBuffer = this.getInternalTexture();
  73724. var scene = this.getScene();
  73725. if (objBuffer && scene) {
  73726. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  73727. }
  73728. };
  73729. /**
  73730. * Dispose the texture and release its associated resources.
  73731. */
  73732. RenderTargetTexture.prototype.dispose = function () {
  73733. if (this._postProcessManager) {
  73734. this._postProcessManager.dispose();
  73735. this._postProcessManager = null;
  73736. }
  73737. this.clearPostProcesses(true);
  73738. if (this._resizeObserver) {
  73739. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  73740. this._resizeObserver = null;
  73741. }
  73742. this.renderList = null;
  73743. // Remove from custom render targets
  73744. var scene = this.getScene();
  73745. if (!scene) {
  73746. return;
  73747. }
  73748. var index = scene.customRenderTargets.indexOf(this);
  73749. if (index >= 0) {
  73750. scene.customRenderTargets.splice(index, 1);
  73751. }
  73752. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  73753. var camera = _a[_i];
  73754. index = camera.customRenderTargets.indexOf(this);
  73755. if (index >= 0) {
  73756. camera.customRenderTargets.splice(index, 1);
  73757. }
  73758. }
  73759. _super.prototype.dispose.call(this);
  73760. };
  73761. /** @hidden */
  73762. RenderTargetTexture.prototype._rebuild = function () {
  73763. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73764. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73765. }
  73766. if (this._postProcessManager) {
  73767. this._postProcessManager._rebuild();
  73768. }
  73769. };
  73770. /**
  73771. * Clear the info related to rendering groups preventing retention point in material dispose.
  73772. */
  73773. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  73774. if (this._renderingManager) {
  73775. this._renderingManager.freeRenderingGroups();
  73776. }
  73777. };
  73778. /**
  73779. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  73780. */
  73781. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  73782. /**
  73783. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  73784. */
  73785. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  73786. /**
  73787. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  73788. * the central point of your effect and can save a lot of performances.
  73789. */
  73790. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  73791. return RenderTargetTexture;
  73792. }(BABYLON.Texture));
  73793. BABYLON.RenderTargetTexture = RenderTargetTexture;
  73794. })(BABYLON || (BABYLON = {}));
  73795. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  73796. var BABYLON;
  73797. (function (BABYLON) {
  73798. /**
  73799. * A multi render target, like a render target provides the ability to render to a texture.
  73800. * Unlike the render target, it can render to several draw buffers in one draw.
  73801. * This is specially interesting in deferred rendering or for any effects requiring more than
  73802. * just one color from a single pass.
  73803. */
  73804. var MultiRenderTarget = /** @class */ (function (_super) {
  73805. __extends(MultiRenderTarget, _super);
  73806. /**
  73807. * Instantiate a new multi render target texture.
  73808. * A multi render target, like a render target provides the ability to render to a texture.
  73809. * Unlike the render target, it can render to several draw buffers in one draw.
  73810. * This is specially interesting in deferred rendering or for any effects requiring more than
  73811. * just one color from a single pass.
  73812. * @param name Define the name of the texture
  73813. * @param size Define the size of the buffers to render to
  73814. * @param count Define the number of target we are rendering into
  73815. * @param scene Define the scene the texture belongs to
  73816. * @param options Define the options used to create the multi render target
  73817. */
  73818. function MultiRenderTarget(name, size, count, scene, options) {
  73819. var _this = this;
  73820. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  73821. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  73822. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  73823. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  73824. _this._engine = scene.getEngine();
  73825. if (!_this.isSupported) {
  73826. _this.dispose();
  73827. return;
  73828. }
  73829. var types = [];
  73830. var samplingModes = [];
  73831. for (var i = 0; i < count; i++) {
  73832. if (options && options.types && options.types[i] !== undefined) {
  73833. types.push(options.types[i]);
  73834. }
  73835. else {
  73836. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73837. }
  73838. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  73839. samplingModes.push(options.samplingModes[i]);
  73840. }
  73841. else {
  73842. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73843. }
  73844. }
  73845. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  73846. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  73847. _this._size = size;
  73848. _this._multiRenderTargetOptions = {
  73849. samplingModes: samplingModes,
  73850. generateMipMaps: generateMipMaps,
  73851. generateDepthBuffer: generateDepthBuffer,
  73852. generateStencilBuffer: generateStencilBuffer,
  73853. generateDepthTexture: generateDepthTexture,
  73854. types: types,
  73855. textureCount: count
  73856. };
  73857. _this._createInternalTextures();
  73858. _this._createTextures();
  73859. return _this;
  73860. }
  73861. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  73862. /**
  73863. * Get if draw buffers are currently supported by the used hardware and browser.
  73864. */
  73865. get: function () {
  73866. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  73867. },
  73868. enumerable: true,
  73869. configurable: true
  73870. });
  73871. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  73872. /**
  73873. * Get the list of textures generated by the multi render target.
  73874. */
  73875. get: function () {
  73876. return this._textures;
  73877. },
  73878. enumerable: true,
  73879. configurable: true
  73880. });
  73881. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  73882. /**
  73883. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  73884. */
  73885. get: function () {
  73886. return this._textures[this._textures.length - 1];
  73887. },
  73888. enumerable: true,
  73889. configurable: true
  73890. });
  73891. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  73892. /**
  73893. * Set the wrapping mode on U of all the textures we are rendering to.
  73894. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73895. */
  73896. set: function (wrap) {
  73897. if (this._textures) {
  73898. for (var i = 0; i < this._textures.length; i++) {
  73899. this._textures[i].wrapU = wrap;
  73900. }
  73901. }
  73902. },
  73903. enumerable: true,
  73904. configurable: true
  73905. });
  73906. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  73907. /**
  73908. * Set the wrapping mode on V of all the textures we are rendering to.
  73909. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73910. */
  73911. set: function (wrap) {
  73912. if (this._textures) {
  73913. for (var i = 0; i < this._textures.length; i++) {
  73914. this._textures[i].wrapV = wrap;
  73915. }
  73916. }
  73917. },
  73918. enumerable: true,
  73919. configurable: true
  73920. });
  73921. /** @hidden */
  73922. MultiRenderTarget.prototype._rebuild = function () {
  73923. this.releaseInternalTextures();
  73924. this._createInternalTextures();
  73925. for (var i = 0; i < this._internalTextures.length; i++) {
  73926. var texture = this._textures[i];
  73927. texture._texture = this._internalTextures[i];
  73928. }
  73929. // Keeps references to frame buffer and stencil/depth buffer
  73930. this._texture = this._internalTextures[0];
  73931. };
  73932. MultiRenderTarget.prototype._createInternalTextures = function () {
  73933. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  73934. };
  73935. MultiRenderTarget.prototype._createTextures = function () {
  73936. this._textures = [];
  73937. for (var i = 0; i < this._internalTextures.length; i++) {
  73938. var texture = new BABYLON.Texture(null, this.getScene());
  73939. texture._texture = this._internalTextures[i];
  73940. this._textures.push(texture);
  73941. }
  73942. // Keeps references to frame buffer and stencil/depth buffer
  73943. this._texture = this._internalTextures[0];
  73944. };
  73945. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  73946. /**
  73947. * Define the number of samples used if MSAA is enabled.
  73948. */
  73949. get: function () {
  73950. return this._samples;
  73951. },
  73952. set: function (value) {
  73953. if (this._samples === value) {
  73954. return;
  73955. }
  73956. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  73957. },
  73958. enumerable: true,
  73959. configurable: true
  73960. });
  73961. /**
  73962. * Resize all the textures in the multi render target.
  73963. * Be carrefull as it will recreate all the data in the new texture.
  73964. * @param size Define the new size
  73965. */
  73966. MultiRenderTarget.prototype.resize = function (size) {
  73967. this.releaseInternalTextures();
  73968. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  73969. this._createInternalTextures();
  73970. };
  73971. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73972. var _this = this;
  73973. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  73974. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73975. });
  73976. };
  73977. /**
  73978. * Dispose the render targets and their associated resources
  73979. */
  73980. MultiRenderTarget.prototype.dispose = function () {
  73981. this.releaseInternalTextures();
  73982. _super.prototype.dispose.call(this);
  73983. };
  73984. /**
  73985. * Release all the underlying texture used as draw buffers.
  73986. */
  73987. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  73988. if (!this._internalTextures) {
  73989. return;
  73990. }
  73991. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  73992. if (this._internalTextures[i] !== undefined) {
  73993. this._internalTextures[i].dispose();
  73994. this._internalTextures.splice(i, 1);
  73995. }
  73996. }
  73997. };
  73998. return MultiRenderTarget;
  73999. }(BABYLON.RenderTargetTexture));
  74000. BABYLON.MultiRenderTarget = MultiRenderTarget;
  74001. })(BABYLON || (BABYLON = {}));
  74002. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  74003. var BABYLON;
  74004. (function (BABYLON) {
  74005. /**
  74006. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74007. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74008. * You can then easily use it as a reflectionTexture on a flat surface.
  74009. * In case the surface is not a plane, please consider relying on reflection probes.
  74010. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74011. */
  74012. var MirrorTexture = /** @class */ (function (_super) {
  74013. __extends(MirrorTexture, _super);
  74014. /**
  74015. * Instantiates a Mirror Texture.
  74016. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74017. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74018. * You can then easily use it as a reflectionTexture on a flat surface.
  74019. * In case the surface is not a plane, please consider relying on reflection probes.
  74020. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74021. * @param name
  74022. * @param size
  74023. * @param scene
  74024. * @param generateMipMaps
  74025. * @param type
  74026. * @param samplingMode
  74027. * @param generateDepthBuffer
  74028. */
  74029. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  74030. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74032. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  74033. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  74034. _this.scene = scene;
  74035. /**
  74036. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  74037. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  74038. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74039. */
  74040. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  74041. _this._transformMatrix = BABYLON.Matrix.Zero();
  74042. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  74043. _this._adaptiveBlurKernel = 0;
  74044. _this._blurKernelX = 0;
  74045. _this._blurKernelY = 0;
  74046. _this._blurRatio = 1.0;
  74047. _this.ignoreCameraViewport = true;
  74048. _this._updateGammaSpace();
  74049. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74050. _this._updateGammaSpace;
  74051. });
  74052. _this.onBeforeRenderObservable.add(function () {
  74053. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  74054. _this._savedViewMatrix = scene.getViewMatrix();
  74055. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  74056. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  74057. scene.clipPlane = _this.mirrorPlane;
  74058. scene.getEngine().cullBackFaces = false;
  74059. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  74060. });
  74061. _this.onAfterRenderObservable.add(function () {
  74062. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  74063. scene.getEngine().cullBackFaces = true;
  74064. scene._mirroredCameraPosition = null;
  74065. delete scene.clipPlane;
  74066. });
  74067. return _this;
  74068. }
  74069. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  74070. get: function () {
  74071. return this._blurRatio;
  74072. },
  74073. /**
  74074. * Define the blur ratio used to blur the reflection if needed.
  74075. */
  74076. set: function (value) {
  74077. if (this._blurRatio === value) {
  74078. return;
  74079. }
  74080. this._blurRatio = value;
  74081. this._preparePostProcesses();
  74082. },
  74083. enumerable: true,
  74084. configurable: true
  74085. });
  74086. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  74087. /**
  74088. * Define the adaptive blur kernel used to blur the reflection if needed.
  74089. * This will autocompute the closest best match for the `blurKernel`
  74090. */
  74091. set: function (value) {
  74092. this._adaptiveBlurKernel = value;
  74093. this._autoComputeBlurKernel();
  74094. },
  74095. enumerable: true,
  74096. configurable: true
  74097. });
  74098. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  74099. /**
  74100. * Define the blur kernel used to blur the reflection if needed.
  74101. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74102. */
  74103. set: function (value) {
  74104. this.blurKernelX = value;
  74105. this.blurKernelY = value;
  74106. },
  74107. enumerable: true,
  74108. configurable: true
  74109. });
  74110. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  74111. get: function () {
  74112. return this._blurKernelX;
  74113. },
  74114. /**
  74115. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  74116. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74117. */
  74118. set: function (value) {
  74119. if (this._blurKernelX === value) {
  74120. return;
  74121. }
  74122. this._blurKernelX = value;
  74123. this._preparePostProcesses();
  74124. },
  74125. enumerable: true,
  74126. configurable: true
  74127. });
  74128. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  74129. get: function () {
  74130. return this._blurKernelY;
  74131. },
  74132. /**
  74133. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  74134. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74135. */
  74136. set: function (value) {
  74137. if (this._blurKernelY === value) {
  74138. return;
  74139. }
  74140. this._blurKernelY = value;
  74141. this._preparePostProcesses();
  74142. },
  74143. enumerable: true,
  74144. configurable: true
  74145. });
  74146. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  74147. var engine = this.getScene().getEngine();
  74148. var dw = this.getRenderWidth() / engine.getRenderWidth();
  74149. var dh = this.getRenderHeight() / engine.getRenderHeight();
  74150. this.blurKernelX = this._adaptiveBlurKernel * dw;
  74151. this.blurKernelY = this._adaptiveBlurKernel * dh;
  74152. };
  74153. MirrorTexture.prototype._onRatioRescale = function () {
  74154. if (this._sizeRatio) {
  74155. this.resize(this._initialSizeParameter);
  74156. if (!this._adaptiveBlurKernel) {
  74157. this._preparePostProcesses();
  74158. }
  74159. }
  74160. if (this._adaptiveBlurKernel) {
  74161. this._autoComputeBlurKernel();
  74162. }
  74163. };
  74164. MirrorTexture.prototype._updateGammaSpace = function () {
  74165. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  74166. };
  74167. MirrorTexture.prototype._preparePostProcesses = function () {
  74168. this.clearPostProcesses(true);
  74169. if (this._blurKernelX && this._blurKernelY) {
  74170. var engine = this.getScene().getEngine();
  74171. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74172. 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);
  74173. this._blurX.autoClear = false;
  74174. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  74175. this._blurX.inputTexture = this._texture;
  74176. }
  74177. else {
  74178. this._blurX.alwaysForcePOT = true;
  74179. }
  74180. 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);
  74181. this._blurY.autoClear = false;
  74182. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  74183. this.addPostProcess(this._blurX);
  74184. this.addPostProcess(this._blurY);
  74185. }
  74186. else {
  74187. if (this._blurY) {
  74188. this.removePostProcess(this._blurY);
  74189. this._blurY.dispose();
  74190. this._blurY = null;
  74191. }
  74192. if (this._blurX) {
  74193. this.removePostProcess(this._blurX);
  74194. this._blurX.dispose();
  74195. this._blurX = null;
  74196. }
  74197. }
  74198. };
  74199. /**
  74200. * Clone the mirror texture.
  74201. * @returns the cloned texture
  74202. */
  74203. MirrorTexture.prototype.clone = function () {
  74204. var scene = this.getScene();
  74205. if (!scene) {
  74206. return this;
  74207. }
  74208. var textureSize = this.getSize();
  74209. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  74210. // Base texture
  74211. newTexture.hasAlpha = this.hasAlpha;
  74212. newTexture.level = this.level;
  74213. // Mirror Texture
  74214. newTexture.mirrorPlane = this.mirrorPlane.clone();
  74215. if (this.renderList) {
  74216. newTexture.renderList = this.renderList.slice(0);
  74217. }
  74218. return newTexture;
  74219. };
  74220. /**
  74221. * Serialize the texture to a JSON representation you could use in Parse later on
  74222. * @returns the serialized JSON representation
  74223. */
  74224. MirrorTexture.prototype.serialize = function () {
  74225. if (!this.name) {
  74226. return null;
  74227. }
  74228. var serializationObject = _super.prototype.serialize.call(this);
  74229. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  74230. return serializationObject;
  74231. };
  74232. /**
  74233. * Dispose the texture and release its associated resources.
  74234. */
  74235. MirrorTexture.prototype.dispose = function () {
  74236. _super.prototype.dispose.call(this);
  74237. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  74238. };
  74239. return MirrorTexture;
  74240. }(BABYLON.RenderTargetTexture));
  74241. BABYLON.MirrorTexture = MirrorTexture;
  74242. })(BABYLON || (BABYLON = {}));
  74243. //# sourceMappingURL=babylon.mirrorTexture.js.map
  74244. var BABYLON;
  74245. (function (BABYLON) {
  74246. /**
  74247. * Creates a refraction texture used by refraction channel of the standard material.
  74248. * It is like a mirror but to see through a material.
  74249. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74250. */
  74251. var RefractionTexture = /** @class */ (function (_super) {
  74252. __extends(RefractionTexture, _super);
  74253. /**
  74254. * Creates a refraction texture used by refraction channel of the standard material.
  74255. * It is like a mirror but to see through a material.
  74256. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74257. * @param name Define the texture name
  74258. * @param size Define the size of the underlying texture
  74259. * @param scene Define the scene the refraction belongs to
  74260. * @param generateMipMaps Define if we need to generate mips level for the refraction
  74261. */
  74262. function RefractionTexture(name, size, scene, generateMipMaps) {
  74263. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  74264. /**
  74265. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  74266. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  74267. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74268. */
  74269. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  74270. /**
  74271. * Define how deep under the surface we should see.
  74272. */
  74273. _this.depth = 2.0;
  74274. _this.onBeforeRenderObservable.add(function () {
  74275. scene.clipPlane = _this.refractionPlane;
  74276. });
  74277. _this.onAfterRenderObservable.add(function () {
  74278. delete scene.clipPlane;
  74279. });
  74280. return _this;
  74281. }
  74282. /**
  74283. * Clone the refraction texture.
  74284. * @returns the cloned texture
  74285. */
  74286. RefractionTexture.prototype.clone = function () {
  74287. var scene = this.getScene();
  74288. if (!scene) {
  74289. return this;
  74290. }
  74291. var textureSize = this.getSize();
  74292. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  74293. // Base texture
  74294. newTexture.hasAlpha = this.hasAlpha;
  74295. newTexture.level = this.level;
  74296. // Refraction Texture
  74297. newTexture.refractionPlane = this.refractionPlane.clone();
  74298. if (this.renderList) {
  74299. newTexture.renderList = this.renderList.slice(0);
  74300. }
  74301. newTexture.depth = this.depth;
  74302. return newTexture;
  74303. };
  74304. /**
  74305. * Serialize the texture to a JSON representation you could use in Parse later on
  74306. * @returns the serialized JSON representation
  74307. */
  74308. RefractionTexture.prototype.serialize = function () {
  74309. if (!this.name) {
  74310. return null;
  74311. }
  74312. var serializationObject = _super.prototype.serialize.call(this);
  74313. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  74314. serializationObject.depth = this.depth;
  74315. return serializationObject;
  74316. };
  74317. return RefractionTexture;
  74318. }(BABYLON.RenderTargetTexture));
  74319. BABYLON.RefractionTexture = RefractionTexture;
  74320. })(BABYLON || (BABYLON = {}));
  74321. //# sourceMappingURL=babylon.refractionTexture.js.map
  74322. var BABYLON;
  74323. (function (BABYLON) {
  74324. /**
  74325. * A class extending Texture allowing drawing on a texture
  74326. * @see http://doc.babylonjs.com/how_to/dynamictexture
  74327. */
  74328. var DynamicTexture = /** @class */ (function (_super) {
  74329. __extends(DynamicTexture, _super);
  74330. /**
  74331. * Creates a DynamicTexture
  74332. * @param name defines the name of the texture
  74333. * @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
  74334. * @param scene defines the scene where you want the texture
  74335. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  74336. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  74337. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  74338. */
  74339. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  74340. if (scene === void 0) { scene = null; }
  74341. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74342. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  74343. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  74344. _this.name = name;
  74345. _this._engine = _this.getScene().getEngine();
  74346. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74347. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74348. _this._generateMipMaps = generateMipMaps;
  74349. if (options.getContext) {
  74350. _this._canvas = options;
  74351. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74352. }
  74353. else {
  74354. _this._canvas = document.createElement("canvas");
  74355. if (options.width || options.width === 0) {
  74356. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74357. }
  74358. else {
  74359. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  74360. }
  74361. }
  74362. var textureSize = _this.getSize();
  74363. _this._canvas.width = textureSize.width;
  74364. _this._canvas.height = textureSize.height;
  74365. _this._context = _this._canvas.getContext("2d");
  74366. return _this;
  74367. }
  74368. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  74369. /**
  74370. * Gets the current state of canRescale
  74371. */
  74372. get: function () {
  74373. return true;
  74374. },
  74375. enumerable: true,
  74376. configurable: true
  74377. });
  74378. DynamicTexture.prototype._recreate = function (textureSize) {
  74379. this._canvas.width = textureSize.width;
  74380. this._canvas.height = textureSize.height;
  74381. this.releaseInternalTexture();
  74382. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  74383. };
  74384. /**
  74385. * Scales the texture
  74386. * @param ratio the scale factor to apply to both width and height
  74387. */
  74388. DynamicTexture.prototype.scale = function (ratio) {
  74389. var textureSize = this.getSize();
  74390. textureSize.width *= ratio;
  74391. textureSize.height *= ratio;
  74392. this._recreate(textureSize);
  74393. };
  74394. /**
  74395. * Resizes the texture
  74396. * @param width the new width
  74397. * @param height the new height
  74398. */
  74399. DynamicTexture.prototype.scaleTo = function (width, height) {
  74400. var textureSize = this.getSize();
  74401. textureSize.width = width;
  74402. textureSize.height = height;
  74403. this._recreate(textureSize);
  74404. };
  74405. /**
  74406. * Gets the context of the canvas used by the texture
  74407. * @returns the canvas context of the dynamic texture
  74408. */
  74409. DynamicTexture.prototype.getContext = function () {
  74410. return this._context;
  74411. };
  74412. /**
  74413. * Clears the texture
  74414. */
  74415. DynamicTexture.prototype.clear = function () {
  74416. var size = this.getSize();
  74417. this._context.fillRect(0, 0, size.width, size.height);
  74418. };
  74419. /**
  74420. * Updates the texture
  74421. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74422. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  74423. */
  74424. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  74425. if (premulAlpha === void 0) { premulAlpha = false; }
  74426. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  74427. };
  74428. /**
  74429. * Draws text onto the texture
  74430. * @param text defines the text to be drawn
  74431. * @param x defines the placement of the text from the left
  74432. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  74433. * @param font defines the font to be used with font-style, font-size, font-name
  74434. * @param color defines the color used for the text
  74435. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  74436. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74437. * @param update defines whether texture is immediately update (default is true)
  74438. */
  74439. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  74440. if (update === void 0) { update = true; }
  74441. var size = this.getSize();
  74442. if (clearColor) {
  74443. this._context.fillStyle = clearColor;
  74444. this._context.fillRect(0, 0, size.width, size.height);
  74445. }
  74446. this._context.font = font;
  74447. if (x === null || x === undefined) {
  74448. var textSize = this._context.measureText(text);
  74449. x = (size.width - textSize.width) / 2;
  74450. }
  74451. if (y === null || y === undefined) {
  74452. var fontSize = parseInt((font.replace(/\D/g, '')));
  74453. y = (size.height / 2) + (fontSize / 3.65);
  74454. }
  74455. this._context.fillStyle = color;
  74456. this._context.fillText(text, x, y);
  74457. if (update) {
  74458. this.update(invertY);
  74459. }
  74460. };
  74461. /**
  74462. * Clones the texture
  74463. * @returns the clone of the texture.
  74464. */
  74465. DynamicTexture.prototype.clone = function () {
  74466. var scene = this.getScene();
  74467. if (!scene) {
  74468. return this;
  74469. }
  74470. var textureSize = this.getSize();
  74471. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  74472. // Base texture
  74473. newTexture.hasAlpha = this.hasAlpha;
  74474. newTexture.level = this.level;
  74475. // Dynamic Texture
  74476. newTexture.wrapU = this.wrapU;
  74477. newTexture.wrapV = this.wrapV;
  74478. return newTexture;
  74479. };
  74480. /**
  74481. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  74482. * @returns a serialized dynamic texture object
  74483. */
  74484. DynamicTexture.prototype.serialize = function () {
  74485. var scene = this.getScene();
  74486. if (scene && !scene.isReady()) {
  74487. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  74488. }
  74489. var serializationObject = _super.prototype.serialize.call(this);
  74490. serializationObject.base64String = this._canvas.toDataURL();
  74491. serializationObject.invertY = this._invertY;
  74492. serializationObject.samplingMode = this.samplingMode;
  74493. return serializationObject;
  74494. };
  74495. /** @hidden */
  74496. DynamicTexture.prototype._rebuild = function () {
  74497. this.update();
  74498. };
  74499. return DynamicTexture;
  74500. }(BABYLON.Texture));
  74501. BABYLON.DynamicTexture = DynamicTexture;
  74502. })(BABYLON || (BABYLON = {}));
  74503. //# sourceMappingURL=babylon.dynamicTexture.js.map
  74504. var BABYLON;
  74505. (function (BABYLON) {
  74506. /**
  74507. * If you want to display a video in your scene, this is the special texture for that.
  74508. * This special texture works similar to other textures, with the exception of a few parameters.
  74509. * @see https://doc.babylonjs.com/how_to/video_texture
  74510. */
  74511. var VideoTexture = /** @class */ (function (_super) {
  74512. __extends(VideoTexture, _super);
  74513. /**
  74514. * Creates a video texture.
  74515. * If you want to display a video in your scene, this is the special texture for that.
  74516. * This special texture works similar to other textures, with the exception of a few parameters.
  74517. * @see https://doc.babylonjs.com/how_to/video_texture
  74518. * @param name optional name, will detect from video source, if not defined
  74519. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  74520. * @param scene is obviously the current scene.
  74521. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  74522. * @param invertY is false by default but can be used to invert video on Y axis
  74523. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  74524. * @param settings allows finer control over video usage
  74525. */
  74526. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  74527. if (generateMipMaps === void 0) { generateMipMaps = false; }
  74528. if (invertY === void 0) { invertY = false; }
  74529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74530. if (settings === void 0) { settings = {
  74531. autoPlay: true,
  74532. loop: true,
  74533. autoUpdateTexture: true,
  74534. }; }
  74535. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74536. _this._onUserActionRequestedObservable = null;
  74537. _this._stillImageCaptured = false;
  74538. _this._poster = false;
  74539. _this._createInternalTexture = function () {
  74540. if (_this._texture != null) {
  74541. if (_this._poster) {
  74542. _this._texture.dispose();
  74543. _this._poster = false;
  74544. }
  74545. else {
  74546. return;
  74547. }
  74548. }
  74549. if (!_this._engine.needPOTTextures ||
  74550. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  74551. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74552. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74553. }
  74554. else {
  74555. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74556. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74557. _this._generateMipMaps = false;
  74558. }
  74559. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  74560. if (!_this.video.autoplay) {
  74561. var oldHandler_1 = _this.video.onplaying;
  74562. var error_1 = false;
  74563. _this.video.onplaying = function () {
  74564. _this.video.onplaying = oldHandler_1;
  74565. _this._texture.isReady = true;
  74566. _this._updateInternalTexture();
  74567. if (!error_1) {
  74568. _this.video.pause();
  74569. }
  74570. if (_this.onLoadObservable.hasObservers()) {
  74571. _this.onLoadObservable.notifyObservers(_this);
  74572. }
  74573. };
  74574. var playing = _this.video.play();
  74575. if (playing) {
  74576. playing.then(function () {
  74577. // Everything is good.
  74578. })
  74579. .catch(function () {
  74580. error_1 = true;
  74581. // On Chrome for instance, new policies might prevent playing without user interaction.
  74582. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  74583. _this._onUserActionRequestedObservable.notifyObservers(_this);
  74584. }
  74585. });
  74586. }
  74587. else {
  74588. _this.video.onplaying = oldHandler_1;
  74589. _this._texture.isReady = true;
  74590. _this._updateInternalTexture();
  74591. if (_this.onLoadObservable.hasObservers()) {
  74592. _this.onLoadObservable.notifyObservers(_this);
  74593. }
  74594. }
  74595. }
  74596. else {
  74597. _this._texture.isReady = true;
  74598. _this._updateInternalTexture();
  74599. if (_this.onLoadObservable.hasObservers()) {
  74600. _this.onLoadObservable.notifyObservers(_this);
  74601. }
  74602. }
  74603. };
  74604. _this.reset = function () {
  74605. if (_this._texture == null) {
  74606. return;
  74607. }
  74608. if (!_this._poster) {
  74609. _this._texture.dispose();
  74610. _this._texture = null;
  74611. }
  74612. };
  74613. _this._updateInternalTexture = function (e) {
  74614. if (_this._texture == null || !_this._texture.isReady) {
  74615. return;
  74616. }
  74617. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  74618. return;
  74619. }
  74620. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  74621. };
  74622. _this._engine = _this.getScene().getEngine();
  74623. _this._generateMipMaps = generateMipMaps;
  74624. _this._samplingMode = samplingMode;
  74625. _this.autoUpdateTexture = settings.autoUpdateTexture;
  74626. _this.name = name || _this._getName(src);
  74627. _this.video = _this._getVideo(src);
  74628. if (settings.poster) {
  74629. _this.video.poster = settings.poster;
  74630. }
  74631. if (settings.autoPlay !== undefined) {
  74632. _this.video.autoplay = settings.autoPlay;
  74633. }
  74634. if (settings.loop !== undefined) {
  74635. _this.video.loop = settings.loop;
  74636. }
  74637. _this.video.setAttribute("playsinline", "");
  74638. _this.video.addEventListener("canplay", _this._createInternalTexture);
  74639. _this.video.addEventListener("paused", _this._updateInternalTexture);
  74640. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  74641. _this.video.addEventListener("emptied", _this.reset);
  74642. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  74643. _this._createInternalTexture();
  74644. }
  74645. if (settings.poster) {
  74646. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  74647. _this._poster = true;
  74648. }
  74649. return _this;
  74650. }
  74651. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  74652. /**
  74653. * Event triggerd when a dom action is required by the user to play the video.
  74654. * This happens due to recent changes in browser policies preventing video to auto start.
  74655. */
  74656. get: function () {
  74657. if (!this._onUserActionRequestedObservable) {
  74658. this._onUserActionRequestedObservable = new BABYLON.Observable();
  74659. }
  74660. return this._onUserActionRequestedObservable;
  74661. },
  74662. enumerable: true,
  74663. configurable: true
  74664. });
  74665. VideoTexture.prototype._getName = function (src) {
  74666. if (src instanceof HTMLVideoElement) {
  74667. return src.currentSrc;
  74668. }
  74669. if (typeof src === "object") {
  74670. return src.toString();
  74671. }
  74672. return src;
  74673. };
  74674. VideoTexture.prototype._getVideo = function (src) {
  74675. if (src instanceof HTMLVideoElement) {
  74676. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  74677. return src;
  74678. }
  74679. var video = document.createElement("video");
  74680. if (typeof src === "string") {
  74681. BABYLON.Tools.SetCorsBehavior(src, video);
  74682. video.src = src;
  74683. }
  74684. else {
  74685. BABYLON.Tools.SetCorsBehavior(src[0], video);
  74686. src.forEach(function (url) {
  74687. var source = document.createElement("source");
  74688. source.src = url;
  74689. video.appendChild(source);
  74690. });
  74691. }
  74692. return video;
  74693. };
  74694. /**
  74695. * @hidden Internal method to initiate `update`.
  74696. */
  74697. VideoTexture.prototype._rebuild = function () {
  74698. this.update();
  74699. };
  74700. /**
  74701. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  74702. */
  74703. VideoTexture.prototype.update = function () {
  74704. if (!this.autoUpdateTexture) {
  74705. // Expecting user to call `updateTexture` manually
  74706. return;
  74707. }
  74708. this.updateTexture(true);
  74709. };
  74710. /**
  74711. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  74712. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  74713. */
  74714. VideoTexture.prototype.updateTexture = function (isVisible) {
  74715. if (!isVisible) {
  74716. return;
  74717. }
  74718. if (this.video.paused && this._stillImageCaptured) {
  74719. return;
  74720. }
  74721. this._stillImageCaptured = true;
  74722. this._updateInternalTexture();
  74723. };
  74724. /**
  74725. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  74726. * @param url New url.
  74727. */
  74728. VideoTexture.prototype.updateURL = function (url) {
  74729. this.video.src = url;
  74730. };
  74731. /**
  74732. * Dispose the texture and release its associated resources.
  74733. */
  74734. VideoTexture.prototype.dispose = function () {
  74735. _super.prototype.dispose.call(this);
  74736. if (this._onUserActionRequestedObservable) {
  74737. this._onUserActionRequestedObservable.clear();
  74738. this._onUserActionRequestedObservable = null;
  74739. }
  74740. this.video.removeEventListener("canplay", this._createInternalTexture);
  74741. this.video.removeEventListener("paused", this._updateInternalTexture);
  74742. this.video.removeEventListener("seeked", this._updateInternalTexture);
  74743. this.video.removeEventListener("emptied", this.reset);
  74744. this.video.pause();
  74745. };
  74746. /**
  74747. * Creates a video texture straight from your WebCam video feed.
  74748. * @param scene Define the scene the texture should be created in
  74749. * @param onReady Define a callback to triggered once the texture will be ready
  74750. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  74751. */
  74752. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  74753. var video = document.createElement("video");
  74754. video.setAttribute('autoplay', '');
  74755. video.setAttribute('muted', '');
  74756. video.setAttribute('playsinline', '');
  74757. var constraintsDeviceId;
  74758. if (constraints && constraints.deviceId) {
  74759. constraintsDeviceId = {
  74760. exact: constraints.deviceId,
  74761. };
  74762. }
  74763. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  74764. if (navigator.mediaDevices) {
  74765. navigator.mediaDevices.getUserMedia({ video: constraints })
  74766. .then(function (stream) {
  74767. if (video.mozSrcObject !== undefined) {
  74768. // hack for Firefox < 19
  74769. video.mozSrcObject = stream;
  74770. }
  74771. else {
  74772. video.srcObject = stream;
  74773. }
  74774. var onPlaying = function () {
  74775. if (onReady) {
  74776. onReady(new VideoTexture("video", video, scene, true, true));
  74777. }
  74778. video.removeEventListener("playing", onPlaying);
  74779. };
  74780. video.addEventListener("playing", onPlaying);
  74781. video.play();
  74782. })
  74783. .catch(function (err) {
  74784. BABYLON.Tools.Error(err.name);
  74785. });
  74786. }
  74787. else {
  74788. navigator.getUserMedia =
  74789. navigator.getUserMedia ||
  74790. navigator.webkitGetUserMedia ||
  74791. navigator.mozGetUserMedia ||
  74792. navigator.msGetUserMedia;
  74793. if (navigator.getUserMedia) {
  74794. navigator.getUserMedia({
  74795. video: {
  74796. deviceId: constraintsDeviceId,
  74797. width: {
  74798. min: (constraints && constraints.minWidth) || 256,
  74799. max: (constraints && constraints.maxWidth) || 640,
  74800. },
  74801. height: {
  74802. min: (constraints && constraints.minHeight) || 256,
  74803. max: (constraints && constraints.maxHeight) || 480,
  74804. },
  74805. },
  74806. }, function (stream) {
  74807. if (video.mozSrcObject !== undefined) {
  74808. // hack for Firefox < 19
  74809. video.mozSrcObject = stream;
  74810. }
  74811. else {
  74812. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  74813. }
  74814. video.play();
  74815. if (onReady) {
  74816. onReady(new VideoTexture("video", video, scene, true, true));
  74817. }
  74818. }, function (e) {
  74819. BABYLON.Tools.Error(e.name);
  74820. });
  74821. }
  74822. }
  74823. };
  74824. return VideoTexture;
  74825. }(BABYLON.Texture));
  74826. BABYLON.VideoTexture = VideoTexture;
  74827. })(BABYLON || (BABYLON = {}));
  74828. //# sourceMappingURL=babylon.videoTexture.js.map
  74829. var BABYLON;
  74830. (function (BABYLON) {
  74831. /**
  74832. * Raw texture can help creating a texture directly from an array of data.
  74833. * This can be super useful if you either get the data from an uncompressed source or
  74834. * if you wish to create your texture pixel by pixel.
  74835. */
  74836. var RawTexture = /** @class */ (function (_super) {
  74837. __extends(RawTexture, _super);
  74838. /**
  74839. * Instantiates a new RawTexture.
  74840. * Raw texture can help creating a texture directly from an array of data.
  74841. * This can be super useful if you either get the data from an uncompressed source or
  74842. * if you wish to create your texture pixel by pixel.
  74843. * @param data define the array of data to use to create the texture
  74844. * @param width define the width of the texture
  74845. * @param height define the height of the texture
  74846. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74847. * @param scene define the scene the texture belongs to
  74848. * @param generateMipMaps define whether mip maps should be generated or not
  74849. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74850. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74851. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74852. */
  74853. function RawTexture(data, width, height,
  74854. /**
  74855. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74856. */
  74857. format, scene, generateMipMaps, invertY, samplingMode, type) {
  74858. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74859. if (invertY === void 0) { invertY = false; }
  74860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74861. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74862. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74863. _this.format = format;
  74864. _this._engine = scene.getEngine();
  74865. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  74866. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74867. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74868. return _this;
  74869. }
  74870. /**
  74871. * Updates the texture underlying data.
  74872. * @param data Define the new data of the texture
  74873. */
  74874. RawTexture.prototype.update = function (data) {
  74875. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  74876. };
  74877. /**
  74878. * Creates a luminance texture from some data.
  74879. * @param data Define the texture data
  74880. * @param width Define the width of the texture
  74881. * @param height Define the height of the texture
  74882. * @param scene Define the scene the texture belongs to
  74883. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74884. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74885. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74886. * @returns the luminance texture
  74887. */
  74888. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74889. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74890. if (invertY === void 0) { invertY = false; }
  74891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74892. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  74893. };
  74894. /**
  74895. * Creates a luminance alpha texture from some data.
  74896. * @param data Define the texture data
  74897. * @param width Define the width of the texture
  74898. * @param height Define the height of the texture
  74899. * @param scene Define the scene the texture belongs to
  74900. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74901. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74902. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74903. * @returns the luminance alpha texture
  74904. */
  74905. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74906. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74907. if (invertY === void 0) { invertY = false; }
  74908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74909. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74910. };
  74911. /**
  74912. * Creates an alpha texture from some data.
  74913. * @param data Define the texture data
  74914. * @param width Define the width of the texture
  74915. * @param height Define the height of the texture
  74916. * @param scene Define the scene the texture belongs to
  74917. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74918. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74919. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74920. * @returns the alpha texture
  74921. */
  74922. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74924. if (invertY === void 0) { invertY = false; }
  74925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74926. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  74927. };
  74928. /**
  74929. * Creates a RGB texture from some data.
  74930. * @param data Define the texture data
  74931. * @param width Define the width of the texture
  74932. * @param height Define the height of the texture
  74933. * @param scene Define the scene the texture belongs to
  74934. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74935. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74936. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74937. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74938. * @returns the RGB alpha texture
  74939. */
  74940. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74941. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74942. if (invertY === void 0) { invertY = false; }
  74943. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74944. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74945. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  74946. };
  74947. /**
  74948. * Creates a RGBA texture from some data.
  74949. * @param data Define the texture data
  74950. * @param width Define the width of the texture
  74951. * @param height Define the height of the texture
  74952. * @param scene Define the scene the texture belongs to
  74953. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74954. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74955. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74956. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74957. * @returns the RGBA texture
  74958. */
  74959. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74960. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74961. if (invertY === void 0) { invertY = false; }
  74962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74963. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74964. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  74965. };
  74966. /**
  74967. * Creates a R texture from some data.
  74968. * @param data Define the texture data
  74969. * @param width Define the width of the texture
  74970. * @param height Define the height of the texture
  74971. * @param scene Define the scene the texture belongs to
  74972. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74973. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74974. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74975. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74976. * @returns the R texture
  74977. */
  74978. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  74979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74980. if (invertY === void 0) { invertY = false; }
  74981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74982. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74983. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  74984. };
  74985. return RawTexture;
  74986. }(BABYLON.Texture));
  74987. BABYLON.RawTexture = RawTexture;
  74988. })(BABYLON || (BABYLON = {}));
  74989. //# sourceMappingURL=babylon.rawTexture.js.map
  74990. var BABYLON;
  74991. (function (BABYLON) {
  74992. /**
  74993. * Class used to store 3D textures containing user data
  74994. */
  74995. var RawTexture3D = /** @class */ (function (_super) {
  74996. __extends(RawTexture3D, _super);
  74997. /**
  74998. * Create a new RawTexture3D
  74999. * @param data defines the data of the texture
  75000. * @param width defines the width of the texture
  75001. * @param height defines the height of the texture
  75002. * @param depth defines the depth of the texture
  75003. * @param format defines the texture format to use
  75004. * @param scene defines the hosting scene
  75005. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  75006. * @param invertY defines if texture must be stored with Y axis inverted
  75007. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  75008. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  75009. */
  75010. function RawTexture3D(data, width, height, depth,
  75011. /** Gets or sets the texture format to use */
  75012. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  75013. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75014. if (invertY === void 0) { invertY = false; }
  75015. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75016. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75017. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  75018. _this.format = format;
  75019. _this._engine = scene.getEngine();
  75020. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  75021. _this.is3D = true;
  75022. return _this;
  75023. }
  75024. /**
  75025. * Update the texture with new data
  75026. * @param data defines the data to store in the texture
  75027. */
  75028. RawTexture3D.prototype.update = function (data) {
  75029. if (!this._texture) {
  75030. return;
  75031. }
  75032. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  75033. };
  75034. return RawTexture3D;
  75035. }(BABYLON.Texture));
  75036. BABYLON.RawTexture3D = RawTexture3D;
  75037. })(BABYLON || (BABYLON = {}));
  75038. //# sourceMappingURL=babylon.rawTexture3D.js.map
  75039. var BABYLON;
  75040. (function (BABYLON) {
  75041. /**
  75042. * PostProcessManager is used to manage one or more post processes or post process pipelines
  75043. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75044. */
  75045. var PostProcessManager = /** @class */ (function () {
  75046. /**
  75047. * Creates a new instance PostProcess
  75048. * @param scene The scene that the post process is associated with.
  75049. */
  75050. function PostProcessManager(scene) {
  75051. this._vertexBuffers = {};
  75052. this._scene = scene;
  75053. }
  75054. PostProcessManager.prototype._prepareBuffers = function () {
  75055. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  75056. return;
  75057. }
  75058. // VBO
  75059. var vertices = [];
  75060. vertices.push(1, 1);
  75061. vertices.push(-1, 1);
  75062. vertices.push(-1, -1);
  75063. vertices.push(1, -1);
  75064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75065. this._buildIndexBuffer();
  75066. };
  75067. PostProcessManager.prototype._buildIndexBuffer = function () {
  75068. // Indices
  75069. var indices = [];
  75070. indices.push(0);
  75071. indices.push(1);
  75072. indices.push(2);
  75073. indices.push(0);
  75074. indices.push(2);
  75075. indices.push(3);
  75076. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  75077. };
  75078. /**
  75079. * Rebuilds the vertex buffers of the manager.
  75080. * @hidden
  75081. */
  75082. PostProcessManager.prototype._rebuild = function () {
  75083. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75084. if (!vb) {
  75085. return;
  75086. }
  75087. vb._rebuild();
  75088. this._buildIndexBuffer();
  75089. };
  75090. // Methods
  75091. /**
  75092. * Prepares a frame to be run through a post process.
  75093. * @param sourceTexture The input texture to the post procesess. (default: null)
  75094. * @param postProcesses An array of post processes to be run. (default: null)
  75095. * @returns True if the post processes were able to be run.
  75096. * @hidden
  75097. */
  75098. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  75099. if (sourceTexture === void 0) { sourceTexture = null; }
  75100. if (postProcesses === void 0) { postProcesses = null; }
  75101. var camera = this._scene.activeCamera;
  75102. if (!camera) {
  75103. return false;
  75104. }
  75105. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75106. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75107. return false;
  75108. }
  75109. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  75110. return true;
  75111. };
  75112. /**
  75113. * Manually render a set of post processes to a texture.
  75114. * @param postProcesses An array of post processes to be run.
  75115. * @param targetTexture The target texture to render to.
  75116. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  75117. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  75118. * @param lodLevel defines which lod of the texture to render to
  75119. */
  75120. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  75121. if (targetTexture === void 0) { targetTexture = null; }
  75122. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75123. if (faceIndex === void 0) { faceIndex = 0; }
  75124. if (lodLevel === void 0) { lodLevel = 0; }
  75125. var engine = this._scene.getEngine();
  75126. for (var index = 0; index < postProcesses.length; index++) {
  75127. if (index < postProcesses.length - 1) {
  75128. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  75129. }
  75130. else {
  75131. if (targetTexture) {
  75132. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  75133. }
  75134. else {
  75135. engine.restoreDefaultFramebuffer();
  75136. }
  75137. }
  75138. var pp = postProcesses[index];
  75139. var effect = pp.apply();
  75140. if (effect) {
  75141. pp.onBeforeRenderObservable.notifyObservers(effect);
  75142. // VBOs
  75143. this._prepareBuffers();
  75144. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75145. // Draw order
  75146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75147. pp.onAfterRenderObservable.notifyObservers(effect);
  75148. }
  75149. }
  75150. // Restore depth buffer
  75151. engine.setDepthBuffer(true);
  75152. engine.setDepthWrite(true);
  75153. };
  75154. /**
  75155. * Finalize the result of the output of the postprocesses.
  75156. * @param doNotPresent If true the result will not be displayed to the screen.
  75157. * @param targetTexture The target texture to render to.
  75158. * @param faceIndex The index of the face to bind the target texture to.
  75159. * @param postProcesses The array of post processes to render.
  75160. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  75161. * @hidden
  75162. */
  75163. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  75164. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75165. var camera = this._scene.activeCamera;
  75166. if (!camera) {
  75167. return;
  75168. }
  75169. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75170. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75171. return;
  75172. }
  75173. var engine = this._scene.getEngine();
  75174. for (var index = 0, len = postProcesses.length; index < len; index++) {
  75175. var pp = postProcesses[index];
  75176. if (index < len - 1) {
  75177. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  75178. }
  75179. else {
  75180. if (targetTexture) {
  75181. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  75182. pp._outputTexture = targetTexture;
  75183. }
  75184. else {
  75185. engine.restoreDefaultFramebuffer();
  75186. pp._outputTexture = null;
  75187. }
  75188. }
  75189. if (doNotPresent) {
  75190. break;
  75191. }
  75192. var effect = pp.apply();
  75193. if (effect) {
  75194. pp.onBeforeRenderObservable.notifyObservers(effect);
  75195. // VBOs
  75196. this._prepareBuffers();
  75197. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75198. // Draw order
  75199. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75200. pp.onAfterRenderObservable.notifyObservers(effect);
  75201. }
  75202. }
  75203. // Restore states
  75204. engine.setDepthBuffer(true);
  75205. engine.setDepthWrite(true);
  75206. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75207. };
  75208. /**
  75209. * Disposes of the post process manager.
  75210. */
  75211. PostProcessManager.prototype.dispose = function () {
  75212. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75213. if (buffer) {
  75214. buffer.dispose();
  75215. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75216. }
  75217. if (this._indexBuffer) {
  75218. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75219. this._indexBuffer = null;
  75220. }
  75221. };
  75222. return PostProcessManager;
  75223. }());
  75224. BABYLON.PostProcessManager = PostProcessManager;
  75225. })(BABYLON || (BABYLON = {}));
  75226. //# sourceMappingURL=babylon.postProcessManager.js.map
  75227. var BABYLON;
  75228. (function (BABYLON) {
  75229. /**
  75230. * PostProcess can be used to apply a shader to a texture after it has been rendered
  75231. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75232. */
  75233. var PostProcess = /** @class */ (function () {
  75234. /**
  75235. * Creates a new instance PostProcess
  75236. * @param name The name of the PostProcess.
  75237. * @param fragmentUrl The url of the fragment shader to be used.
  75238. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  75239. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  75240. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75241. * @param camera The camera to apply the render pass to.
  75242. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75243. * @param engine The engine which the post process will be applied. (default: current engine)
  75244. * @param reusable If the post process can be reused on the same frame. (default: false)
  75245. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  75246. * @param textureType Type of textures used when performing the post process. (default: 0)
  75247. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  75248. * @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
  75249. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  75250. */
  75251. function PostProcess(
  75252. /** Name of the PostProcess. */
  75253. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  75254. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  75255. if (defines === void 0) { defines = null; }
  75256. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75257. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  75258. if (blockCompilation === void 0) { blockCompilation = false; }
  75259. this.name = name;
  75260. /**
  75261. * Width of the texture to apply the post process on
  75262. */
  75263. this.width = -1;
  75264. /**
  75265. * Height of the texture to apply the post process on
  75266. */
  75267. this.height = -1;
  75268. /**
  75269. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  75270. * @hidden
  75271. */
  75272. this._outputTexture = null;
  75273. /**
  75274. * If the buffer needs to be cleared before applying the post process. (default: true)
  75275. * Should be set to false if shader will overwrite all previous pixels.
  75276. */
  75277. this.autoClear = true;
  75278. /**
  75279. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  75280. */
  75281. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  75282. /**
  75283. * Animations to be used for the post processing
  75284. */
  75285. this.animations = new Array();
  75286. /**
  75287. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  75288. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  75289. */
  75290. this.enablePixelPerfectMode = false;
  75291. /**
  75292. * Force the postprocess to be applied without taking in account viewport
  75293. */
  75294. this.forceFullscreenViewport = true;
  75295. /**
  75296. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  75297. *
  75298. * | Value | Type | Description |
  75299. * | ----- | ----------------------------------- | ----------- |
  75300. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  75301. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  75302. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  75303. *
  75304. */
  75305. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  75306. /**
  75307. * Force textures to be a power of two (default: false)
  75308. */
  75309. this.alwaysForcePOT = false;
  75310. this._samples = 1;
  75311. /**
  75312. * Modify the scale of the post process to be the same as the viewport (default: false)
  75313. */
  75314. this.adaptScaleToCurrentViewport = false;
  75315. this._reusable = false;
  75316. /**
  75317. * Smart array of input and output textures for the post process.
  75318. * @hidden
  75319. */
  75320. this._textures = new BABYLON.SmartArray(2);
  75321. /**
  75322. * The index in _textures that corresponds to the output texture.
  75323. * @hidden
  75324. */
  75325. this._currentRenderTextureInd = 0;
  75326. this._scaleRatio = new BABYLON.Vector2(1, 1);
  75327. this._texelSize = BABYLON.Vector2.Zero();
  75328. // Events
  75329. /**
  75330. * An event triggered when the postprocess is activated.
  75331. */
  75332. this.onActivateObservable = new BABYLON.Observable();
  75333. /**
  75334. * An event triggered when the postprocess changes its size.
  75335. */
  75336. this.onSizeChangedObservable = new BABYLON.Observable();
  75337. /**
  75338. * An event triggered when the postprocess applies its effect.
  75339. */
  75340. this.onApplyObservable = new BABYLON.Observable();
  75341. /**
  75342. * An event triggered before rendering the postprocess
  75343. */
  75344. this.onBeforeRenderObservable = new BABYLON.Observable();
  75345. /**
  75346. * An event triggered after rendering the postprocess
  75347. */
  75348. this.onAfterRenderObservable = new BABYLON.Observable();
  75349. if (camera != null) {
  75350. this._camera = camera;
  75351. this._scene = camera.getScene();
  75352. camera.attachPostProcess(this);
  75353. this._engine = this._scene.getEngine();
  75354. this._scene.postProcesses.push(this);
  75355. }
  75356. else if (engine) {
  75357. this._engine = engine;
  75358. this._engine.postProcesses.push(this);
  75359. }
  75360. this._options = options;
  75361. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  75362. this._reusable = reusable || false;
  75363. this._textureType = textureType;
  75364. this._samplers = samplers || [];
  75365. this._samplers.push("textureSampler");
  75366. this._fragmentUrl = fragmentUrl;
  75367. this._vertexUrl = vertexUrl;
  75368. this._parameters = parameters || [];
  75369. this._parameters.push("scale");
  75370. this._indexParameters = indexParameters;
  75371. if (!blockCompilation) {
  75372. this.updateEffect(defines);
  75373. }
  75374. }
  75375. Object.defineProperty(PostProcess.prototype, "samples", {
  75376. /**
  75377. * Number of sample textures (default: 1)
  75378. */
  75379. get: function () {
  75380. return this._samples;
  75381. },
  75382. set: function (n) {
  75383. var _this = this;
  75384. this._samples = n;
  75385. this._textures.forEach(function (texture) {
  75386. if (texture.samples !== _this._samples) {
  75387. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  75388. }
  75389. });
  75390. },
  75391. enumerable: true,
  75392. configurable: true
  75393. });
  75394. Object.defineProperty(PostProcess.prototype, "onActivate", {
  75395. /**
  75396. * A function that is added to the onActivateObservable
  75397. */
  75398. set: function (callback) {
  75399. if (this._onActivateObserver) {
  75400. this.onActivateObservable.remove(this._onActivateObserver);
  75401. }
  75402. if (callback) {
  75403. this._onActivateObserver = this.onActivateObservable.add(callback);
  75404. }
  75405. },
  75406. enumerable: true,
  75407. configurable: true
  75408. });
  75409. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  75410. /**
  75411. * A function that is added to the onSizeChangedObservable
  75412. */
  75413. set: function (callback) {
  75414. if (this._onSizeChangedObserver) {
  75415. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  75416. }
  75417. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  75418. },
  75419. enumerable: true,
  75420. configurable: true
  75421. });
  75422. Object.defineProperty(PostProcess.prototype, "onApply", {
  75423. /**
  75424. * A function that is added to the onApplyObservable
  75425. */
  75426. set: function (callback) {
  75427. if (this._onApplyObserver) {
  75428. this.onApplyObservable.remove(this._onApplyObserver);
  75429. }
  75430. this._onApplyObserver = this.onApplyObservable.add(callback);
  75431. },
  75432. enumerable: true,
  75433. configurable: true
  75434. });
  75435. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  75436. /**
  75437. * A function that is added to the onBeforeRenderObservable
  75438. */
  75439. set: function (callback) {
  75440. if (this._onBeforeRenderObserver) {
  75441. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75442. }
  75443. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75444. },
  75445. enumerable: true,
  75446. configurable: true
  75447. });
  75448. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  75449. /**
  75450. * A function that is added to the onAfterRenderObservable
  75451. */
  75452. set: function (callback) {
  75453. if (this._onAfterRenderObserver) {
  75454. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75455. }
  75456. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75457. },
  75458. enumerable: true,
  75459. configurable: true
  75460. });
  75461. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  75462. /**
  75463. * 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
  75464. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  75465. */
  75466. get: function () {
  75467. return this._textures.data[this._currentRenderTextureInd];
  75468. },
  75469. set: function (value) {
  75470. this._forcedOutputTexture = value;
  75471. },
  75472. enumerable: true,
  75473. configurable: true
  75474. });
  75475. /**
  75476. * Gets the camera which post process is applied to.
  75477. * @returns The camera the post process is applied to.
  75478. */
  75479. PostProcess.prototype.getCamera = function () {
  75480. return this._camera;
  75481. };
  75482. Object.defineProperty(PostProcess.prototype, "texelSize", {
  75483. /**
  75484. * Gets the texel size of the postprocess.
  75485. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  75486. */
  75487. get: function () {
  75488. if (this._shareOutputWithPostProcess) {
  75489. return this._shareOutputWithPostProcess.texelSize;
  75490. }
  75491. if (this._forcedOutputTexture) {
  75492. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  75493. }
  75494. return this._texelSize;
  75495. },
  75496. enumerable: true,
  75497. configurable: true
  75498. });
  75499. /**
  75500. * Gets the engine which this post process belongs to.
  75501. * @returns The engine the post process was enabled with.
  75502. */
  75503. PostProcess.prototype.getEngine = function () {
  75504. return this._engine;
  75505. };
  75506. /**
  75507. * The effect that is created when initializing the post process.
  75508. * @returns The created effect corrisponding the the postprocess.
  75509. */
  75510. PostProcess.prototype.getEffect = function () {
  75511. return this._effect;
  75512. };
  75513. /**
  75514. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  75515. * @param postProcess The post process to share the output with.
  75516. * @returns This post process.
  75517. */
  75518. PostProcess.prototype.shareOutputWith = function (postProcess) {
  75519. this._disposeTextures();
  75520. this._shareOutputWithPostProcess = postProcess;
  75521. return this;
  75522. };
  75523. /**
  75524. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  75525. * This should be called if the post process that shares output with this post process is disabled/disposed.
  75526. */
  75527. PostProcess.prototype.useOwnOutput = function () {
  75528. if (this._textures.length == 0) {
  75529. this._textures = new BABYLON.SmartArray(2);
  75530. }
  75531. this._shareOutputWithPostProcess = null;
  75532. };
  75533. /**
  75534. * Updates the effect with the current post process compile time values and recompiles the shader.
  75535. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75536. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75537. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75538. * @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
  75539. * @param onCompiled Called when the shader has been compiled.
  75540. * @param onError Called if there is an error when compiling a shader.
  75541. */
  75542. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75543. if (defines === void 0) { defines = null; }
  75544. if (uniforms === void 0) { uniforms = null; }
  75545. if (samplers === void 0) { samplers = null; }
  75546. 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);
  75547. };
  75548. /**
  75549. * The post process is reusable if it can be used multiple times within one frame.
  75550. * @returns If the post process is reusable
  75551. */
  75552. PostProcess.prototype.isReusable = function () {
  75553. return this._reusable;
  75554. };
  75555. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  75556. PostProcess.prototype.markTextureDirty = function () {
  75557. this.width = -1;
  75558. };
  75559. /**
  75560. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  75561. * 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.
  75562. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  75563. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  75564. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  75565. * @returns The target texture that was bound to be written to.
  75566. */
  75567. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  75568. var _this = this;
  75569. if (sourceTexture === void 0) { sourceTexture = null; }
  75570. camera = camera || this._camera;
  75571. var scene = camera.getScene();
  75572. var engine = scene.getEngine();
  75573. var maxSize = engine.getCaps().maxTextureSize;
  75574. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  75575. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  75576. // 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
  75577. var webVRCamera = camera.parent;
  75578. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  75579. requiredWidth /= 2;
  75580. }
  75581. var desiredWidth = (this._options.width || requiredWidth);
  75582. var desiredHeight = this._options.height || requiredHeight;
  75583. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  75584. if (this.adaptScaleToCurrentViewport) {
  75585. var currentViewport = engine.currentViewport;
  75586. if (currentViewport) {
  75587. desiredWidth *= currentViewport.width;
  75588. desiredHeight *= currentViewport.height;
  75589. }
  75590. }
  75591. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  75592. if (!this._options.width) {
  75593. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  75594. }
  75595. if (!this._options.height) {
  75596. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  75597. }
  75598. }
  75599. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  75600. if (this._textures.length > 0) {
  75601. for (var i = 0; i < this._textures.length; i++) {
  75602. this._engine._releaseTexture(this._textures.data[i]);
  75603. }
  75604. this._textures.reset();
  75605. }
  75606. this.width = desiredWidth;
  75607. this.height = desiredHeight;
  75608. var textureSize = { width: this.width, height: this.height };
  75609. var textureOptions = {
  75610. generateMipMaps: false,
  75611. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  75612. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  75613. samplingMode: this.renderTargetSamplingMode,
  75614. type: this._textureType
  75615. };
  75616. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75617. if (this._reusable) {
  75618. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75619. }
  75620. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  75621. this.onSizeChangedObservable.notifyObservers(this);
  75622. }
  75623. this._textures.forEach(function (texture) {
  75624. if (texture.samples !== _this.samples) {
  75625. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  75626. }
  75627. });
  75628. }
  75629. var target;
  75630. if (this._shareOutputWithPostProcess) {
  75631. target = this._shareOutputWithPostProcess.inputTexture;
  75632. }
  75633. else if (this._forcedOutputTexture) {
  75634. target = this._forcedOutputTexture;
  75635. this.width = this._forcedOutputTexture.width;
  75636. this.height = this._forcedOutputTexture.height;
  75637. }
  75638. else {
  75639. target = this.inputTexture;
  75640. }
  75641. // Bind the input of this post process to be used as the output of the previous post process.
  75642. if (this.enablePixelPerfectMode) {
  75643. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  75644. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  75645. }
  75646. else {
  75647. this._scaleRatio.copyFromFloats(1, 1);
  75648. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  75649. }
  75650. this.onActivateObservable.notifyObservers(camera);
  75651. // Clear
  75652. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  75653. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  75654. }
  75655. if (this._reusable) {
  75656. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  75657. }
  75658. return target;
  75659. };
  75660. Object.defineProperty(PostProcess.prototype, "isSupported", {
  75661. /**
  75662. * If the post process is supported.
  75663. */
  75664. get: function () {
  75665. return this._effect.isSupported;
  75666. },
  75667. enumerable: true,
  75668. configurable: true
  75669. });
  75670. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  75671. /**
  75672. * The aspect ratio of the output texture.
  75673. */
  75674. get: function () {
  75675. if (this._shareOutputWithPostProcess) {
  75676. return this._shareOutputWithPostProcess.aspectRatio;
  75677. }
  75678. if (this._forcedOutputTexture) {
  75679. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  75680. }
  75681. return this.width / this.height;
  75682. },
  75683. enumerable: true,
  75684. configurable: true
  75685. });
  75686. /**
  75687. * Get a value indicating if the post-process is ready to be used
  75688. * @returns true if the post-process is ready (shader is compiled)
  75689. */
  75690. PostProcess.prototype.isReady = function () {
  75691. return this._effect && this._effect.isReady();
  75692. };
  75693. /**
  75694. * Binds all textures and uniforms to the shader, this will be run on every pass.
  75695. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  75696. */
  75697. PostProcess.prototype.apply = function () {
  75698. // Check
  75699. if (!this._effect || !this._effect.isReady()) {
  75700. return null;
  75701. }
  75702. // States
  75703. this._engine.enableEffect(this._effect);
  75704. this._engine.setState(false);
  75705. this._engine.setDepthBuffer(false);
  75706. this._engine.setDepthWrite(false);
  75707. // Alpha
  75708. this._engine.setAlphaMode(this.alphaMode);
  75709. if (this.alphaConstants) {
  75710. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  75711. }
  75712. // Bind the output texture of the preivous post process as the input to this post process.
  75713. var source;
  75714. if (this._shareOutputWithPostProcess) {
  75715. source = this._shareOutputWithPostProcess.inputTexture;
  75716. }
  75717. else if (this._forcedOutputTexture) {
  75718. source = this._forcedOutputTexture;
  75719. }
  75720. else {
  75721. source = this.inputTexture;
  75722. }
  75723. this._effect._bindTexture("textureSampler", source);
  75724. // Parameters
  75725. this._effect.setVector2("scale", this._scaleRatio);
  75726. this.onApplyObservable.notifyObservers(this._effect);
  75727. return this._effect;
  75728. };
  75729. PostProcess.prototype._disposeTextures = function () {
  75730. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  75731. return;
  75732. }
  75733. if (this._textures.length > 0) {
  75734. for (var i = 0; i < this._textures.length; i++) {
  75735. this._engine._releaseTexture(this._textures.data[i]);
  75736. }
  75737. }
  75738. this._textures.dispose();
  75739. };
  75740. /**
  75741. * Disposes the post process.
  75742. * @param camera The camera to dispose the post process on.
  75743. */
  75744. PostProcess.prototype.dispose = function (camera) {
  75745. camera = camera || this._camera;
  75746. this._disposeTextures();
  75747. if (this._scene) {
  75748. var index_1 = this._scene.postProcesses.indexOf(this);
  75749. if (index_1 !== -1) {
  75750. this._scene.postProcesses.splice(index_1, 1);
  75751. }
  75752. }
  75753. else {
  75754. var index_2 = this._engine.postProcesses.indexOf(this);
  75755. if (index_2 !== -1) {
  75756. this._engine.postProcesses.splice(index_2, 1);
  75757. }
  75758. }
  75759. if (!camera) {
  75760. return;
  75761. }
  75762. camera.detachPostProcess(this);
  75763. var index = camera._postProcesses.indexOf(this);
  75764. if (index === 0 && camera._postProcesses.length > 0) {
  75765. var firstPostProcess = this._camera._getFirstPostProcess();
  75766. if (firstPostProcess) {
  75767. firstPostProcess.markTextureDirty();
  75768. }
  75769. }
  75770. this.onActivateObservable.clear();
  75771. this.onAfterRenderObservable.clear();
  75772. this.onApplyObservable.clear();
  75773. this.onBeforeRenderObservable.clear();
  75774. this.onSizeChangedObservable.clear();
  75775. };
  75776. return PostProcess;
  75777. }());
  75778. BABYLON.PostProcess = PostProcess;
  75779. })(BABYLON || (BABYLON = {}));
  75780. //# sourceMappingURL=babylon.postProcess.js.map
  75781. var BABYLON;
  75782. (function (BABYLON) {
  75783. /**
  75784. * PassPostProcess which produces an output the same as it's input
  75785. */
  75786. var PassPostProcess = /** @class */ (function (_super) {
  75787. __extends(PassPostProcess, _super);
  75788. /**
  75789. * Creates the PassPostProcess
  75790. * @param name The name of the effect.
  75791. * @param options The required width/height ratio to downsize to before computing the render pass.
  75792. * @param camera The camera to apply the render pass to.
  75793. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75794. * @param engine The engine which the post process will be applied. (default: current engine)
  75795. * @param reusable If the post process can be reused on the same frame. (default: false)
  75796. * @param textureType The type of texture to be used when performing the post processing.
  75797. * @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)
  75798. */
  75799. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75800. if (camera === void 0) { camera = null; }
  75801. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75802. if (blockCompilation === void 0) { blockCompilation = false; }
  75803. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  75804. }
  75805. return PassPostProcess;
  75806. }(BABYLON.PostProcess));
  75807. BABYLON.PassPostProcess = PassPostProcess;
  75808. })(BABYLON || (BABYLON = {}));
  75809. //# sourceMappingURL=babylon.passPostProcess.js.map
  75810. var __assign = (this && this.__assign) || function () {
  75811. __assign = Object.assign || function(t) {
  75812. for (var s, i = 1, n = arguments.length; i < n; i++) {
  75813. s = arguments[i];
  75814. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  75815. t[p] = s[p];
  75816. }
  75817. return t;
  75818. };
  75819. return __assign.apply(this, arguments);
  75820. };
  75821. var BABYLON;
  75822. (function (BABYLON) {
  75823. /**
  75824. * Default implementation IShadowGenerator.
  75825. * This is the main object responsible of generating shadows in the framework.
  75826. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  75827. */
  75828. var ShadowGenerator = /** @class */ (function () {
  75829. /**
  75830. * Creates a ShadowGenerator object.
  75831. * A ShadowGenerator is the required tool to use the shadows.
  75832. * Each light casting shadows needs to use its own ShadowGenerator.
  75833. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  75834. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  75835. * @param light The light object generating the shadows.
  75836. * @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.
  75837. */
  75838. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  75839. this._bias = 0.00005;
  75840. this._normalBias = 0;
  75841. this._blurBoxOffset = 1;
  75842. this._blurScale = 2;
  75843. this._blurKernel = 1;
  75844. this._useKernelBlur = false;
  75845. this._filter = ShadowGenerator.FILTER_NONE;
  75846. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  75847. this._contactHardeningLightSizeUVRatio = 0.1;
  75848. this._darkness = 0;
  75849. this._transparencyShadow = false;
  75850. /**
  75851. * Controls the extent to which the shadows fade out at the edge of the frustum
  75852. * Used only by directionals and spots
  75853. */
  75854. this.frustumEdgeFalloff = 0;
  75855. /**
  75856. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  75857. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  75858. * It might on the other hand introduce peter panning.
  75859. */
  75860. this.forceBackFacesOnly = false;
  75861. this._lightDirection = BABYLON.Vector3.Zero();
  75862. this._viewMatrix = BABYLON.Matrix.Zero();
  75863. this._projectionMatrix = BABYLON.Matrix.Zero();
  75864. this._transformMatrix = BABYLON.Matrix.Zero();
  75865. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75866. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75867. this._currentFaceIndex = 0;
  75868. this._currentFaceIndexCache = 0;
  75869. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  75870. this._mapSize = mapSize;
  75871. this._light = light;
  75872. this._scene = light.getScene();
  75873. light._shadowGenerator = this;
  75874. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  75875. if (!component) {
  75876. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  75877. this._scene._addComponent(component);
  75878. }
  75879. // Texture type fallback from float to int if not supported.
  75880. var caps = this._scene.getEngine().getCaps();
  75881. if (!useFullFloatFirst) {
  75882. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75883. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75884. }
  75885. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75886. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75887. }
  75888. else {
  75889. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75890. }
  75891. }
  75892. else {
  75893. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75894. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75895. }
  75896. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75897. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75898. }
  75899. else {
  75900. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75901. }
  75902. }
  75903. this._initializeGenerator();
  75904. this._applyFilterValues();
  75905. }
  75906. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  75907. /**
  75908. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  75909. */
  75910. get: function () {
  75911. return this._bias;
  75912. },
  75913. /**
  75914. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  75915. */
  75916. set: function (bias) {
  75917. this._bias = bias;
  75918. },
  75919. enumerable: true,
  75920. configurable: true
  75921. });
  75922. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  75923. /**
  75924. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75925. */
  75926. get: function () {
  75927. return this._normalBias;
  75928. },
  75929. /**
  75930. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  75931. */
  75932. set: function (normalBias) {
  75933. this._normalBias = normalBias;
  75934. },
  75935. enumerable: true,
  75936. configurable: true
  75937. });
  75938. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  75939. /**
  75940. * Gets the blur box offset: offset applied during the blur pass.
  75941. * Only usefull if useKernelBlur = false
  75942. */
  75943. get: function () {
  75944. return this._blurBoxOffset;
  75945. },
  75946. /**
  75947. * Sets the blur box offset: offset applied during the blur pass.
  75948. * Only usefull if useKernelBlur = false
  75949. */
  75950. set: function (value) {
  75951. if (this._blurBoxOffset === value) {
  75952. return;
  75953. }
  75954. this._blurBoxOffset = value;
  75955. this._disposeBlurPostProcesses();
  75956. },
  75957. enumerable: true,
  75958. configurable: true
  75959. });
  75960. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  75961. /**
  75962. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  75963. * 2 means half of the size.
  75964. */
  75965. get: function () {
  75966. return this._blurScale;
  75967. },
  75968. /**
  75969. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  75970. * 2 means half of the size.
  75971. */
  75972. set: function (value) {
  75973. if (this._blurScale === value) {
  75974. return;
  75975. }
  75976. this._blurScale = value;
  75977. this._disposeBlurPostProcesses();
  75978. },
  75979. enumerable: true,
  75980. configurable: true
  75981. });
  75982. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  75983. /**
  75984. * Gets the blur kernel: kernel size of the blur pass.
  75985. * Only usefull if useKernelBlur = true
  75986. */
  75987. get: function () {
  75988. return this._blurKernel;
  75989. },
  75990. /**
  75991. * Sets the blur kernel: kernel size of the blur pass.
  75992. * Only usefull if useKernelBlur = true
  75993. */
  75994. set: function (value) {
  75995. if (this._blurKernel === value) {
  75996. return;
  75997. }
  75998. this._blurKernel = value;
  75999. this._disposeBlurPostProcesses();
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  76005. /**
  76006. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  76007. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  76008. */
  76009. get: function () {
  76010. return this._useKernelBlur;
  76011. },
  76012. /**
  76013. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  76014. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  76015. */
  76016. set: function (value) {
  76017. if (this._useKernelBlur === value) {
  76018. return;
  76019. }
  76020. this._useKernelBlur = value;
  76021. this._disposeBlurPostProcesses();
  76022. },
  76023. enumerable: true,
  76024. configurable: true
  76025. });
  76026. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  76027. /**
  76028. * Gets the depth scale used in ESM mode.
  76029. */
  76030. get: function () {
  76031. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  76032. },
  76033. /**
  76034. * Sets the depth scale used in ESM mode.
  76035. * This can override the scale stored on the light.
  76036. */
  76037. set: function (value) {
  76038. this._depthScale = value;
  76039. },
  76040. enumerable: true,
  76041. configurable: true
  76042. });
  76043. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  76044. /**
  76045. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  76046. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76047. */
  76048. get: function () {
  76049. return this._filter;
  76050. },
  76051. /**
  76052. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  76053. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76054. */
  76055. set: function (value) {
  76056. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  76057. if (this._light.needCube()) {
  76058. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76059. this.useExponentialShadowMap = true;
  76060. return;
  76061. }
  76062. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76063. this.useCloseExponentialShadowMap = true;
  76064. return;
  76065. }
  76066. // PCF on cubemap would also be expensive
  76067. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76068. this.usePoissonSampling = true;
  76069. return;
  76070. }
  76071. }
  76072. // Weblg1 fallback for PCF.
  76073. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76074. if (this._scene.getEngine().webGLVersion === 1) {
  76075. this.usePoissonSampling = true;
  76076. return;
  76077. }
  76078. }
  76079. if (this._filter === value) {
  76080. return;
  76081. }
  76082. this._filter = value;
  76083. this._disposeBlurPostProcesses();
  76084. this._applyFilterValues();
  76085. this._light._markMeshesAsLightDirty();
  76086. },
  76087. enumerable: true,
  76088. configurable: true
  76089. });
  76090. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  76091. /**
  76092. * Gets if the current filter is set to Poisson Sampling.
  76093. */
  76094. get: function () {
  76095. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  76096. },
  76097. /**
  76098. * Sets the current filter to Poisson Sampling.
  76099. */
  76100. set: function (value) {
  76101. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  76102. return;
  76103. }
  76104. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  76105. },
  76106. enumerable: true,
  76107. configurable: true
  76108. });
  76109. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  76110. /**
  76111. * Gets if the current filter is set to VSM.
  76112. * DEPRECATED. Should use useExponentialShadowMap instead.
  76113. */
  76114. get: function () {
  76115. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  76116. return this.useExponentialShadowMap;
  76117. },
  76118. /**
  76119. * Sets the current filter is to VSM.
  76120. * DEPRECATED. Should use useExponentialShadowMap instead.
  76121. */
  76122. set: function (value) {
  76123. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  76124. this.useExponentialShadowMap = value;
  76125. },
  76126. enumerable: true,
  76127. configurable: true
  76128. });
  76129. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  76130. /**
  76131. * Gets if the current filter is set to blurred VSM.
  76132. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  76133. */
  76134. get: function () {
  76135. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  76136. return this.useBlurExponentialShadowMap;
  76137. },
  76138. /**
  76139. * Sets the current filter is to blurred VSM.
  76140. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  76141. */
  76142. set: function (value) {
  76143. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  76144. this.useBlurExponentialShadowMap = value;
  76145. },
  76146. enumerable: true,
  76147. configurable: true
  76148. });
  76149. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  76150. /**
  76151. * Gets if the current filter is set to ESM.
  76152. */
  76153. get: function () {
  76154. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  76155. },
  76156. /**
  76157. * Sets the current filter is to ESM.
  76158. */
  76159. set: function (value) {
  76160. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  76161. return;
  76162. }
  76163. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76164. },
  76165. enumerable: true,
  76166. configurable: true
  76167. });
  76168. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  76169. /**
  76170. * Gets if the current filter is set to filtered ESM.
  76171. */
  76172. get: function () {
  76173. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  76174. },
  76175. /**
  76176. * Gets if the current filter is set to filtered ESM.
  76177. */
  76178. set: function (value) {
  76179. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76180. return;
  76181. }
  76182. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76183. },
  76184. enumerable: true,
  76185. configurable: true
  76186. });
  76187. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  76188. /**
  76189. * Gets if the current filter is set to "close ESM" (using the inverse of the
  76190. * exponential to prevent steep falloff artifacts).
  76191. */
  76192. get: function () {
  76193. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  76194. },
  76195. /**
  76196. * Sets the current filter to "close ESM" (using the inverse of the
  76197. * exponential to prevent steep falloff artifacts).
  76198. */
  76199. set: function (value) {
  76200. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  76201. return;
  76202. }
  76203. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76204. },
  76205. enumerable: true,
  76206. configurable: true
  76207. });
  76208. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  76209. /**
  76210. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  76211. * exponential to prevent steep falloff artifacts).
  76212. */
  76213. get: function () {
  76214. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  76215. },
  76216. /**
  76217. * Sets the current filter to filtered "close ESM" (using the inverse of the
  76218. * exponential to prevent steep falloff artifacts).
  76219. */
  76220. set: function (value) {
  76221. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76222. return;
  76223. }
  76224. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76225. },
  76226. enumerable: true,
  76227. configurable: true
  76228. });
  76229. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  76230. /**
  76231. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  76232. */
  76233. get: function () {
  76234. return this.filter === ShadowGenerator.FILTER_PCF;
  76235. },
  76236. /**
  76237. * Sets the current filter to "PCF" (percentage closer filtering).
  76238. */
  76239. set: function (value) {
  76240. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  76241. return;
  76242. }
  76243. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  76244. },
  76245. enumerable: true,
  76246. configurable: true
  76247. });
  76248. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  76249. /**
  76250. * Gets the PCF or PCSS Quality.
  76251. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76252. */
  76253. get: function () {
  76254. return this._filteringQuality;
  76255. },
  76256. /**
  76257. * Sets the PCF or PCSS Quality.
  76258. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76259. */
  76260. set: function (filteringQuality) {
  76261. this._filteringQuality = filteringQuality;
  76262. },
  76263. enumerable: true,
  76264. configurable: true
  76265. });
  76266. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  76267. /**
  76268. * Gets if the current filter is set to "PCSS" (contact hardening).
  76269. */
  76270. get: function () {
  76271. return this.filter === ShadowGenerator.FILTER_PCSS;
  76272. },
  76273. /**
  76274. * Sets the current filter to "PCSS" (contact hardening).
  76275. */
  76276. set: function (value) {
  76277. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  76278. return;
  76279. }
  76280. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  76281. },
  76282. enumerable: true,
  76283. configurable: true
  76284. });
  76285. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  76286. /**
  76287. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76288. * Using a ratio helps keeping shape stability independently of the map size.
  76289. *
  76290. * It does not account for the light projection as it was having too much
  76291. * instability during the light setup or during light position changes.
  76292. *
  76293. * Only valid if useContactHardeningShadow is true.
  76294. */
  76295. get: function () {
  76296. return this._contactHardeningLightSizeUVRatio;
  76297. },
  76298. /**
  76299. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76300. * Using a ratio helps keeping shape stability independently of the map size.
  76301. *
  76302. * It does not account for the light projection as it was having too much
  76303. * instability during the light setup or during light position changes.
  76304. *
  76305. * Only valid if useContactHardeningShadow is true.
  76306. */
  76307. set: function (contactHardeningLightSizeUVRatio) {
  76308. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  76309. },
  76310. enumerable: true,
  76311. configurable: true
  76312. });
  76313. /**
  76314. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  76315. * 0 means strongest and 1 would means no shadow.
  76316. * @returns the darkness.
  76317. */
  76318. ShadowGenerator.prototype.getDarkness = function () {
  76319. return this._darkness;
  76320. };
  76321. /**
  76322. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  76323. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  76324. * @returns the shadow generator allowing fluent coding.
  76325. */
  76326. ShadowGenerator.prototype.setDarkness = function (darkness) {
  76327. if (darkness >= 1.0) {
  76328. this._darkness = 1.0;
  76329. }
  76330. else if (darkness <= 0.0) {
  76331. this._darkness = 0.0;
  76332. }
  76333. else {
  76334. this._darkness = darkness;
  76335. }
  76336. return this;
  76337. };
  76338. /**
  76339. * Sets the ability to have transparent shadow (boolean).
  76340. * @param transparent True if transparent else False
  76341. * @returns the shadow generator allowing fluent coding
  76342. */
  76343. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  76344. this._transparencyShadow = transparent;
  76345. return this;
  76346. };
  76347. /**
  76348. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  76349. * @returns The render target texture if present otherwise, null
  76350. */
  76351. ShadowGenerator.prototype.getShadowMap = function () {
  76352. return this._shadowMap;
  76353. };
  76354. /**
  76355. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  76356. * @returns The render target texture if the shadow map is present otherwise, null
  76357. */
  76358. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  76359. if (this._shadowMap2) {
  76360. return this._shadowMap2;
  76361. }
  76362. return this._shadowMap;
  76363. };
  76364. /**
  76365. * Helper function to add a mesh and its descendants to the list of shadow casters.
  76366. * @param mesh Mesh to add
  76367. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  76368. * @returns the Shadow Generator itself
  76369. */
  76370. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  76371. if (includeDescendants === void 0) { includeDescendants = true; }
  76372. var _a;
  76373. if (!this._shadowMap) {
  76374. return this;
  76375. }
  76376. if (!this._shadowMap.renderList) {
  76377. this._shadowMap.renderList = [];
  76378. }
  76379. this._shadowMap.renderList.push(mesh);
  76380. if (includeDescendants) {
  76381. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  76382. }
  76383. return this;
  76384. };
  76385. /**
  76386. * Helper function to remove a mesh and its descendants from the list of shadow casters
  76387. * @param mesh Mesh to remove
  76388. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  76389. * @returns the Shadow Generator itself
  76390. */
  76391. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  76392. if (includeDescendants === void 0) { includeDescendants = true; }
  76393. if (!this._shadowMap || !this._shadowMap.renderList) {
  76394. return this;
  76395. }
  76396. var index = this._shadowMap.renderList.indexOf(mesh);
  76397. if (index !== -1) {
  76398. this._shadowMap.renderList.splice(index, 1);
  76399. }
  76400. if (includeDescendants) {
  76401. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  76402. var child = _a[_i];
  76403. this.removeShadowCaster(child);
  76404. }
  76405. }
  76406. return this;
  76407. };
  76408. /**
  76409. * Returns the associated light object.
  76410. * @returns the light generating the shadow
  76411. */
  76412. ShadowGenerator.prototype.getLight = function () {
  76413. return this._light;
  76414. };
  76415. ShadowGenerator.prototype._initializeGenerator = function () {
  76416. this._light._markMeshesAsLightDirty();
  76417. this._initializeShadowMap();
  76418. };
  76419. ShadowGenerator.prototype._initializeShadowMap = function () {
  76420. var _this = this;
  76421. // Render target
  76422. var engine = this._scene.getEngine();
  76423. if (engine.webGLVersion > 1) {
  76424. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  76425. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  76426. }
  76427. else {
  76428. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  76429. }
  76430. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76431. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76432. this._shadowMap.anisotropicFilteringLevel = 1;
  76433. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76434. this._shadowMap.renderParticles = false;
  76435. this._shadowMap.ignoreCameraViewport = true;
  76436. // Record Face Index before render.
  76437. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  76438. _this._currentFaceIndex = faceIndex;
  76439. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76440. engine.setColorWrite(false);
  76441. }
  76442. });
  76443. // Custom render function.
  76444. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  76445. // Blur if required afer render.
  76446. this._shadowMap.onAfterUnbindObservable.add(function () {
  76447. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76448. engine.setColorWrite(true);
  76449. }
  76450. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  76451. return;
  76452. }
  76453. var shadowMap = _this.getShadowMapForRendering();
  76454. if (shadowMap) {
  76455. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  76456. }
  76457. });
  76458. // Clear according to the chosen filter.
  76459. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  76460. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  76461. this._shadowMap.onClearObservable.add(function (engine) {
  76462. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76463. engine.clear(clearOne, false, true, false);
  76464. }
  76465. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  76466. engine.clear(clearZero, true, true, false);
  76467. }
  76468. else {
  76469. engine.clear(clearOne, true, true, false);
  76470. }
  76471. });
  76472. };
  76473. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  76474. var _this = this;
  76475. var engine = this._scene.getEngine();
  76476. var targetSize = this._mapSize / this.blurScale;
  76477. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  76478. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  76479. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76480. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76481. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76482. }
  76483. if (this.useKernelBlur) {
  76484. 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);
  76485. this._kernelBlurXPostprocess.width = targetSize;
  76486. this._kernelBlurXPostprocess.height = targetSize;
  76487. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  76488. effect.setTexture("textureSampler", _this._shadowMap);
  76489. });
  76490. 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);
  76491. this._kernelBlurXPostprocess.autoClear = false;
  76492. this._kernelBlurYPostprocess.autoClear = false;
  76493. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76494. this._kernelBlurXPostprocess.packedFloat = true;
  76495. this._kernelBlurYPostprocess.packedFloat = true;
  76496. }
  76497. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  76498. }
  76499. else {
  76500. 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);
  76501. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  76502. effect.setFloat2("screenSize", targetSize, targetSize);
  76503. effect.setTexture("textureSampler", _this._shadowMap);
  76504. });
  76505. this._boxBlurPostprocess.autoClear = false;
  76506. this._blurPostProcesses = [this._boxBlurPostprocess];
  76507. }
  76508. };
  76509. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76510. var index;
  76511. var engine = this._scene.getEngine();
  76512. if (depthOnlySubMeshes.length) {
  76513. engine.setColorWrite(false);
  76514. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76515. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  76516. }
  76517. engine.setColorWrite(true);
  76518. }
  76519. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76520. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  76521. }
  76522. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76523. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  76524. }
  76525. if (this._transparencyShadow) {
  76526. for (index = 0; index < transparentSubMeshes.length; index++) {
  76527. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  76528. }
  76529. }
  76530. };
  76531. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  76532. var _this = this;
  76533. var mesh = subMesh.getRenderingMesh();
  76534. var scene = this._scene;
  76535. var engine = scene.getEngine();
  76536. var material = subMesh.getMaterial();
  76537. if (!material) {
  76538. return;
  76539. }
  76540. // Culling
  76541. engine.setState(material.backFaceCulling);
  76542. // Managing instances
  76543. var batch = mesh._getInstancesRenderList(subMesh._id);
  76544. if (batch.mustReturn) {
  76545. return;
  76546. }
  76547. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76548. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  76549. engine.enableEffect(this._effect);
  76550. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76551. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  76552. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  76553. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76554. this._effect.setVector3("lightData", this._cachedDirection);
  76555. }
  76556. else {
  76557. this._effect.setVector3("lightData", this._cachedPosition);
  76558. }
  76559. if (scene.activeCamera) {
  76560. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  76561. }
  76562. // Alpha test
  76563. if (material && material.needAlphaTesting()) {
  76564. var alphaTexture = material.getAlphaTestTexture();
  76565. if (alphaTexture) {
  76566. this._effect.setTexture("diffuseSampler", alphaTexture);
  76567. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  76568. }
  76569. }
  76570. // Bones
  76571. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76572. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  76573. }
  76574. // Morph targets
  76575. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  76576. if (this.forceBackFacesOnly) {
  76577. engine.setState(true, 0, false, true);
  76578. }
  76579. // Draw
  76580. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76581. if (this.forceBackFacesOnly) {
  76582. engine.setState(true, 0, false, false);
  76583. }
  76584. }
  76585. else {
  76586. // Need to reset refresh rate of the shadowMap
  76587. if (this._shadowMap) {
  76588. this._shadowMap.resetRefreshCounter();
  76589. }
  76590. }
  76591. };
  76592. ShadowGenerator.prototype._applyFilterValues = function () {
  76593. if (!this._shadowMap) {
  76594. return;
  76595. }
  76596. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  76597. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  76598. }
  76599. else {
  76600. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76601. }
  76602. };
  76603. /**
  76604. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76605. * @param onCompiled Callback triggered at the and of the effects compilation
  76606. * @param options Sets of optional options forcing the compilation with different modes
  76607. */
  76608. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  76609. var _this = this;
  76610. var localOptions = __assign({ useInstances: false }, options);
  76611. var shadowMap = this.getShadowMap();
  76612. if (!shadowMap) {
  76613. if (onCompiled) {
  76614. onCompiled(this);
  76615. }
  76616. return;
  76617. }
  76618. var renderList = shadowMap.renderList;
  76619. if (!renderList) {
  76620. if (onCompiled) {
  76621. onCompiled(this);
  76622. }
  76623. return;
  76624. }
  76625. var subMeshes = new Array();
  76626. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  76627. var mesh = renderList_1[_i];
  76628. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  76629. }
  76630. if (subMeshes.length === 0) {
  76631. if (onCompiled) {
  76632. onCompiled(this);
  76633. }
  76634. return;
  76635. }
  76636. var currentIndex = 0;
  76637. var checkReady = function () {
  76638. if (!_this._scene || !_this._scene.getEngine()) {
  76639. return;
  76640. }
  76641. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  76642. currentIndex++;
  76643. if (currentIndex >= subMeshes.length) {
  76644. if (onCompiled) {
  76645. onCompiled(_this);
  76646. }
  76647. return;
  76648. }
  76649. }
  76650. setTimeout(checkReady, 16);
  76651. };
  76652. checkReady();
  76653. };
  76654. /**
  76655. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76656. * @param options Sets of optional options forcing the compilation with different modes
  76657. * @returns A promise that resolves when the compilation completes
  76658. */
  76659. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  76660. var _this = this;
  76661. return new Promise(function (resolve) {
  76662. _this.forceCompilation(function () {
  76663. resolve();
  76664. }, options);
  76665. });
  76666. };
  76667. /**
  76668. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  76669. * @param subMesh The submesh we want to render in the shadow map
  76670. * @param useInstances Defines wether will draw in the map using instances
  76671. * @returns true if ready otherwise, false
  76672. */
  76673. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  76674. var defines = [];
  76675. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76676. defines.push("#define FLOAT");
  76677. }
  76678. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76679. defines.push("#define ESM");
  76680. }
  76681. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  76682. defines.push("#define DEPTHTEXTURE");
  76683. }
  76684. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76685. var mesh = subMesh.getMesh();
  76686. var material = subMesh.getMaterial();
  76687. // Normal bias.
  76688. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76689. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76690. defines.push("#define NORMAL");
  76691. if (mesh.nonUniformScaling) {
  76692. defines.push("#define NONUNIFORMSCALING");
  76693. }
  76694. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76695. defines.push("#define DIRECTIONINLIGHTDATA");
  76696. }
  76697. }
  76698. // Alpha test
  76699. if (material && material.needAlphaTesting()) {
  76700. var alphaTexture = material.getAlphaTestTexture();
  76701. if (alphaTexture) {
  76702. defines.push("#define ALPHATEST");
  76703. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76704. attribs.push(BABYLON.VertexBuffer.UVKind);
  76705. defines.push("#define UV1");
  76706. }
  76707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76708. if (alphaTexture.coordinatesIndex === 1) {
  76709. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76710. defines.push("#define UV2");
  76711. }
  76712. }
  76713. }
  76714. }
  76715. // Bones
  76716. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76717. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76718. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76719. if (mesh.numBoneInfluencers > 4) {
  76720. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76721. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76722. }
  76723. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76724. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  76725. }
  76726. else {
  76727. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76728. }
  76729. // Morph targets
  76730. var manager = mesh.morphTargetManager;
  76731. var morphInfluencers = 0;
  76732. if (manager) {
  76733. if (manager.numInfluencers > 0) {
  76734. defines.push("#define MORPHTARGETS");
  76735. morphInfluencers = manager.numInfluencers;
  76736. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  76737. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  76738. }
  76739. }
  76740. // Instances
  76741. if (useInstances) {
  76742. defines.push("#define INSTANCES");
  76743. attribs.push("world0");
  76744. attribs.push("world1");
  76745. attribs.push("world2");
  76746. attribs.push("world3");
  76747. }
  76748. // Get correct effect
  76749. var join = defines.join("\n");
  76750. if (this._cachedDefines !== join) {
  76751. this._cachedDefines = join;
  76752. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  76753. }
  76754. if (!this._effect.isReady()) {
  76755. return false;
  76756. }
  76757. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76758. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  76759. this._initializeBlurRTTAndPostProcesses();
  76760. }
  76761. }
  76762. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  76763. return false;
  76764. }
  76765. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  76766. return false;
  76767. }
  76768. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  76769. return false;
  76770. }
  76771. return true;
  76772. };
  76773. /**
  76774. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  76775. * @param defines Defines of the material we want to update
  76776. * @param lightIndex Index of the light in the enabled light list of the material
  76777. */
  76778. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  76779. var scene = this._scene;
  76780. var light = this._light;
  76781. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76782. return;
  76783. }
  76784. defines["SHADOW" + lightIndex] = true;
  76785. if (this.useContactHardeningShadow) {
  76786. defines["SHADOWPCSS" + lightIndex] = true;
  76787. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76788. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76789. }
  76790. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76791. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76792. }
  76793. // else default to high.
  76794. }
  76795. if (this.usePercentageCloserFiltering) {
  76796. defines["SHADOWPCF" + lightIndex] = true;
  76797. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76798. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76799. }
  76800. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76801. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76802. }
  76803. // else default to high.
  76804. }
  76805. else if (this.usePoissonSampling) {
  76806. defines["SHADOWPOISSON" + lightIndex] = true;
  76807. }
  76808. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76809. defines["SHADOWESM" + lightIndex] = true;
  76810. }
  76811. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76812. defines["SHADOWCLOSEESM" + lightIndex] = true;
  76813. }
  76814. if (light.needCube()) {
  76815. defines["SHADOWCUBE" + lightIndex] = true;
  76816. }
  76817. };
  76818. /**
  76819. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  76820. * defined in the generator but impacting the effect).
  76821. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  76822. * @param effect The effect we are binfing the information for
  76823. */
  76824. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  76825. var light = this._light;
  76826. var scene = this._scene;
  76827. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76828. return;
  76829. }
  76830. var camera = scene.activeCamera;
  76831. if (!camera) {
  76832. return;
  76833. }
  76834. var shadowMap = this.getShadowMap();
  76835. if (!shadowMap) {
  76836. return;
  76837. }
  76838. if (!light.needCube()) {
  76839. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  76840. }
  76841. // Only PCF uses depth stencil texture.
  76842. if (this._filter === ShadowGenerator.FILTER_PCF) {
  76843. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76844. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76845. }
  76846. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  76847. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76848. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  76849. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76850. }
  76851. else {
  76852. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76853. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  76854. }
  76855. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  76856. };
  76857. /**
  76858. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  76859. * (eq to shadow prjection matrix * light transform matrix)
  76860. * @returns The transform matrix used to create the shadow map
  76861. */
  76862. ShadowGenerator.prototype.getTransformMatrix = function () {
  76863. var scene = this._scene;
  76864. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  76865. return this._transformMatrix;
  76866. }
  76867. this._currentRenderID = scene.getRenderId();
  76868. this._currentFaceIndexCache = this._currentFaceIndex;
  76869. var lightPosition = this._light.position;
  76870. if (this._light.computeTransformedInformation()) {
  76871. lightPosition = this._light.transformedPosition;
  76872. }
  76873. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  76874. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  76875. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  76876. }
  76877. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  76878. this._cachedPosition.copyFrom(lightPosition);
  76879. this._cachedDirection.copyFrom(this._lightDirection);
  76880. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  76881. var shadowMap = this.getShadowMap();
  76882. if (shadowMap) {
  76883. var renderList = shadowMap.renderList;
  76884. if (renderList) {
  76885. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  76886. }
  76887. }
  76888. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  76889. }
  76890. return this._transformMatrix;
  76891. };
  76892. /**
  76893. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  76894. * Cube and 2D textures for instance.
  76895. */
  76896. ShadowGenerator.prototype.recreateShadowMap = function () {
  76897. var shadowMap = this._shadowMap;
  76898. if (!shadowMap) {
  76899. return;
  76900. }
  76901. // Track render list.
  76902. var renderList = shadowMap.renderList;
  76903. // Clean up existing data.
  76904. this._disposeRTTandPostProcesses();
  76905. // Reinitializes.
  76906. this._initializeGenerator();
  76907. // Reaffect the filter to ensure a correct fallback if necessary.
  76908. this.filter = this.filter;
  76909. // Reaffect the filter.
  76910. this._applyFilterValues();
  76911. // Reaffect Render List.
  76912. this._shadowMap.renderList = renderList;
  76913. };
  76914. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  76915. if (this._shadowMap2) {
  76916. this._shadowMap2.dispose();
  76917. this._shadowMap2 = null;
  76918. }
  76919. if (this._boxBlurPostprocess) {
  76920. this._boxBlurPostprocess.dispose();
  76921. this._boxBlurPostprocess = null;
  76922. }
  76923. if (this._kernelBlurXPostprocess) {
  76924. this._kernelBlurXPostprocess.dispose();
  76925. this._kernelBlurXPostprocess = null;
  76926. }
  76927. if (this._kernelBlurYPostprocess) {
  76928. this._kernelBlurYPostprocess.dispose();
  76929. this._kernelBlurYPostprocess = null;
  76930. }
  76931. this._blurPostProcesses = [];
  76932. };
  76933. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  76934. if (this._shadowMap) {
  76935. this._shadowMap.dispose();
  76936. this._shadowMap = null;
  76937. }
  76938. this._disposeBlurPostProcesses();
  76939. };
  76940. /**
  76941. * Disposes the ShadowGenerator.
  76942. * Returns nothing.
  76943. */
  76944. ShadowGenerator.prototype.dispose = function () {
  76945. this._disposeRTTandPostProcesses();
  76946. if (this._light) {
  76947. this._light._shadowGenerator = null;
  76948. this._light._markMeshesAsLightDirty();
  76949. }
  76950. };
  76951. /**
  76952. * Serializes the shadow generator setup to a json object.
  76953. * @returns The serialized JSON object
  76954. */
  76955. ShadowGenerator.prototype.serialize = function () {
  76956. var serializationObject = {};
  76957. var shadowMap = this.getShadowMap();
  76958. if (!shadowMap) {
  76959. return serializationObject;
  76960. }
  76961. serializationObject.lightId = this._light.id;
  76962. serializationObject.mapSize = shadowMap.getRenderSize();
  76963. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  76964. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  76965. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76966. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  76967. serializationObject.usePoissonSampling = this.usePoissonSampling;
  76968. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  76969. serializationObject.depthScale = this.depthScale;
  76970. serializationObject.darkness = this.getDarkness();
  76971. serializationObject.blurBoxOffset = this.blurBoxOffset;
  76972. serializationObject.blurKernel = this.blurKernel;
  76973. serializationObject.blurScale = this.blurScale;
  76974. serializationObject.useKernelBlur = this.useKernelBlur;
  76975. serializationObject.transparencyShadow = this._transparencyShadow;
  76976. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  76977. serializationObject.bias = this.bias;
  76978. serializationObject.normalBias = this.normalBias;
  76979. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  76980. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  76981. serializationObject.filteringQuality = this.filteringQuality;
  76982. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  76983. serializationObject.renderList = [];
  76984. if (shadowMap.renderList) {
  76985. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  76986. var mesh = shadowMap.renderList[meshIndex];
  76987. serializationObject.renderList.push(mesh.id);
  76988. }
  76989. }
  76990. return serializationObject;
  76991. };
  76992. /**
  76993. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  76994. * @param parsedShadowGenerator The JSON object to parse
  76995. * @param scene The scene to create the shadow map for
  76996. * @returns The parsed shadow generator
  76997. */
  76998. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  76999. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  77000. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  77001. var shadowMap = shadowGenerator.getShadowMap();
  77002. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  77003. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  77004. meshes.forEach(function (mesh) {
  77005. if (!shadowMap) {
  77006. return;
  77007. }
  77008. if (!shadowMap.renderList) {
  77009. shadowMap.renderList = [];
  77010. }
  77011. shadowMap.renderList.push(mesh);
  77012. });
  77013. }
  77014. if (parsedShadowGenerator.usePoissonSampling) {
  77015. shadowGenerator.usePoissonSampling = true;
  77016. }
  77017. else if (parsedShadowGenerator.useExponentialShadowMap) {
  77018. shadowGenerator.useExponentialShadowMap = true;
  77019. }
  77020. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  77021. shadowGenerator.useBlurExponentialShadowMap = true;
  77022. }
  77023. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  77024. shadowGenerator.useCloseExponentialShadowMap = true;
  77025. }
  77026. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  77027. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  77028. }
  77029. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  77030. shadowGenerator.usePercentageCloserFiltering = true;
  77031. }
  77032. else if (parsedShadowGenerator.useContactHardeningShadow) {
  77033. shadowGenerator.useContactHardeningShadow = true;
  77034. }
  77035. if (parsedShadowGenerator.filteringQuality) {
  77036. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  77037. }
  77038. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  77039. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  77040. }
  77041. // Backward compat
  77042. else if (parsedShadowGenerator.useVarianceShadowMap) {
  77043. shadowGenerator.useExponentialShadowMap = true;
  77044. }
  77045. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  77046. shadowGenerator.useBlurExponentialShadowMap = true;
  77047. }
  77048. if (parsedShadowGenerator.depthScale) {
  77049. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  77050. }
  77051. if (parsedShadowGenerator.blurScale) {
  77052. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  77053. }
  77054. if (parsedShadowGenerator.blurBoxOffset) {
  77055. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  77056. }
  77057. if (parsedShadowGenerator.useKernelBlur) {
  77058. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  77059. }
  77060. if (parsedShadowGenerator.blurKernel) {
  77061. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  77062. }
  77063. if (parsedShadowGenerator.bias !== undefined) {
  77064. shadowGenerator.bias = parsedShadowGenerator.bias;
  77065. }
  77066. if (parsedShadowGenerator.normalBias !== undefined) {
  77067. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  77068. }
  77069. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  77070. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  77071. }
  77072. if (parsedShadowGenerator.darkness) {
  77073. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  77074. }
  77075. if (parsedShadowGenerator.transparencyShadow) {
  77076. shadowGenerator.setTransparencyShadow(true);
  77077. }
  77078. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  77079. return shadowGenerator;
  77080. };
  77081. /**
  77082. * Shadow generator mode None: no filtering applied.
  77083. */
  77084. ShadowGenerator.FILTER_NONE = 0;
  77085. /**
  77086. * Shadow generator mode ESM: Exponential Shadow Mapping.
  77087. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77088. */
  77089. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  77090. /**
  77091. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  77092. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  77093. */
  77094. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  77095. /**
  77096. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  77097. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77098. */
  77099. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  77100. /**
  77101. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  77102. * edge artifacts on steep falloff.
  77103. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77104. */
  77105. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  77106. /**
  77107. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  77108. * edge artifacts on steep falloff.
  77109. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77110. */
  77111. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  77112. /**
  77113. * Shadow generator mode PCF: Percentage Closer Filtering
  77114. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77115. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  77116. */
  77117. ShadowGenerator.FILTER_PCF = 6;
  77118. /**
  77119. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  77120. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77121. * Contact Hardening
  77122. */
  77123. ShadowGenerator.FILTER_PCSS = 7;
  77124. /**
  77125. * Reserved for PCF and PCSS
  77126. * Highest Quality.
  77127. *
  77128. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  77129. *
  77130. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  77131. */
  77132. ShadowGenerator.QUALITY_HIGH = 0;
  77133. /**
  77134. * Reserved for PCF and PCSS
  77135. * Good tradeoff for quality/perf cross devices
  77136. *
  77137. * Execute PCF on a 3*3 kernel.
  77138. *
  77139. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  77140. */
  77141. ShadowGenerator.QUALITY_MEDIUM = 1;
  77142. /**
  77143. * Reserved for PCF and PCSS
  77144. * The lowest quality but the fastest.
  77145. *
  77146. * Execute PCF on a 1*1 kernel.
  77147. *
  77148. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  77149. */
  77150. ShadowGenerator.QUALITY_LOW = 2;
  77151. return ShadowGenerator;
  77152. }());
  77153. BABYLON.ShadowGenerator = ShadowGenerator;
  77154. })(BABYLON || (BABYLON = {}));
  77155. //# sourceMappingURL=babylon.shadowGenerator.js.map
  77156. var BABYLON;
  77157. (function (BABYLON) {
  77158. // Adds the parser to the scene parsers.
  77159. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  77160. // Shadows
  77161. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  77162. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  77163. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  77164. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  77165. // SG would be available on their associated lights
  77166. }
  77167. }
  77168. });
  77169. /**
  77170. * Defines the shadow generator component responsible to manage any shadow generators
  77171. * in a given scene.
  77172. */
  77173. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  77174. /**
  77175. * Creates a new instance of the component for the given scene
  77176. * @param scene Defines the scene to register the component in
  77177. */
  77178. function ShadowGeneratorSceneComponent(scene) {
  77179. /**
  77180. * The component name helpfull to identify the component in the list of scene components.
  77181. */
  77182. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  77183. this.scene = scene;
  77184. }
  77185. /**
  77186. * Registers the component in a given scene
  77187. */
  77188. ShadowGeneratorSceneComponent.prototype.register = function () {
  77189. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  77190. };
  77191. /**
  77192. * Rebuilds the elements related to this component in case of
  77193. * context lost for instance.
  77194. */
  77195. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  77196. // Nothing To Do Here.
  77197. };
  77198. /**
  77199. * Serializes the component data to the specified json object
  77200. * @param serializationObject The object to serialize to
  77201. */
  77202. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  77203. // Shadows
  77204. serializationObject.shadowGenerators = [];
  77205. var lights = this.scene.lights;
  77206. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  77207. var light = lights_1[_i];
  77208. var shadowGenerator = light.getShadowGenerator();
  77209. if (shadowGenerator) {
  77210. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77211. }
  77212. }
  77213. };
  77214. /**
  77215. * Adds all the element from the container to the scene
  77216. * @param container the container holding the elements
  77217. */
  77218. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  77219. // Nothing To Do Here. (directly attached to a light)
  77220. };
  77221. /**
  77222. * Removes all the elements in the container from the scene
  77223. * @param container contains the elements to remove
  77224. */
  77225. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  77226. // Nothing To Do Here. (directly attached to a light)
  77227. };
  77228. /**
  77229. * Rebuilds the elements related to this component in case of
  77230. * context lost for instance.
  77231. */
  77232. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  77233. // Nothing To Do Here.
  77234. };
  77235. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77236. // Shadows
  77237. var scene = this.scene;
  77238. if (this.scene.shadowsEnabled) {
  77239. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  77240. var light = scene.lights[lightIndex];
  77241. var shadowGenerator = light.getShadowGenerator();
  77242. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  77243. var shadowMap = (shadowGenerator.getShadowMap());
  77244. if (scene.textures.indexOf(shadowMap) !== -1) {
  77245. renderTargets.push(shadowMap);
  77246. }
  77247. }
  77248. }
  77249. }
  77250. };
  77251. return ShadowGeneratorSceneComponent;
  77252. }());
  77253. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  77254. })(BABYLON || (BABYLON = {}));
  77255. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  77256. var BABYLON;
  77257. (function (BABYLON) {
  77258. /**
  77259. * Class used for the default loading screen
  77260. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77261. */
  77262. var DefaultLoadingScreen = /** @class */ (function () {
  77263. /**
  77264. * Creates a new default loading screen
  77265. * @param _renderingCanvas defines the canvas used to render the scene
  77266. * @param _loadingText defines the default text to display
  77267. * @param _loadingDivBackgroundColor defines the default background color
  77268. */
  77269. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  77270. if (_loadingText === void 0) { _loadingText = ""; }
  77271. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  77272. var _this = this;
  77273. this._renderingCanvas = _renderingCanvas;
  77274. this._loadingText = _loadingText;
  77275. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  77276. // Resize
  77277. this._resizeLoadingUI = function () {
  77278. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  77279. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  77280. if (!_this._loadingDiv) {
  77281. return;
  77282. }
  77283. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  77284. _this._loadingDiv.style.left = canvasRect.left + "px";
  77285. _this._loadingDiv.style.top = canvasRect.top + "px";
  77286. _this._loadingDiv.style.width = canvasRect.width + "px";
  77287. _this._loadingDiv.style.height = canvasRect.height + "px";
  77288. };
  77289. }
  77290. /**
  77291. * Function called to display the loading screen
  77292. */
  77293. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  77294. if (this._loadingDiv) {
  77295. // Do not add a loading screen if there is already one
  77296. return;
  77297. }
  77298. this._loadingDiv = document.createElement("div");
  77299. this._loadingDiv.id = "babylonjsLoadingDiv";
  77300. this._loadingDiv.style.opacity = "0";
  77301. this._loadingDiv.style.transition = "opacity 1.5s ease";
  77302. this._loadingDiv.style.pointerEvents = "none";
  77303. // Loading text
  77304. this._loadingTextDiv = document.createElement("div");
  77305. this._loadingTextDiv.style.position = "absolute";
  77306. this._loadingTextDiv.style.left = "0";
  77307. this._loadingTextDiv.style.top = "50%";
  77308. this._loadingTextDiv.style.marginTop = "80px";
  77309. this._loadingTextDiv.style.width = "100%";
  77310. this._loadingTextDiv.style.height = "20px";
  77311. this._loadingTextDiv.style.fontFamily = "Arial";
  77312. this._loadingTextDiv.style.fontSize = "14px";
  77313. this._loadingTextDiv.style.color = "white";
  77314. this._loadingTextDiv.style.textAlign = "center";
  77315. this._loadingTextDiv.innerHTML = "Loading";
  77316. this._loadingDiv.appendChild(this._loadingTextDiv);
  77317. //set the predefined text
  77318. this._loadingTextDiv.innerHTML = this._loadingText;
  77319. // Generating keyframes
  77320. var style = document.createElement('style');
  77321. style.type = 'text/css';
  77322. 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 }";
  77323. style.innerHTML = keyFrames;
  77324. document.getElementsByTagName('head')[0].appendChild(style);
  77325. // Loading img
  77326. var imgBack = new Image();
  77327. 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";
  77328. imgBack.style.position = "absolute";
  77329. imgBack.style.left = "50%";
  77330. imgBack.style.top = "50%";
  77331. imgBack.style.marginLeft = "-60px";
  77332. imgBack.style.marginTop = "-60px";
  77333. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  77334. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  77335. imgBack.style.transformOrigin = "50% 50%";
  77336. imgBack.style.webkitTransformOrigin = "50% 50%";
  77337. this._loadingDiv.appendChild(imgBack);
  77338. this._resizeLoadingUI();
  77339. window.addEventListener("resize", this._resizeLoadingUI);
  77340. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77341. document.body.appendChild(this._loadingDiv);
  77342. this._loadingDiv.style.opacity = "1";
  77343. };
  77344. /**
  77345. * Function called to hide the loading screen
  77346. */
  77347. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  77348. var _this = this;
  77349. if (!this._loadingDiv) {
  77350. return;
  77351. }
  77352. var onTransitionEnd = function () {
  77353. if (!_this._loadingDiv) {
  77354. return;
  77355. }
  77356. document.body.removeChild(_this._loadingDiv);
  77357. window.removeEventListener("resize", _this._resizeLoadingUI);
  77358. _this._loadingDiv = null;
  77359. };
  77360. this._loadingDiv.style.opacity = "0";
  77361. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  77362. };
  77363. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  77364. get: function () {
  77365. return this._loadingText;
  77366. },
  77367. /**
  77368. * Gets or sets the text to display while loading
  77369. */
  77370. set: function (text) {
  77371. this._loadingText = text;
  77372. if (this._loadingTextDiv) {
  77373. this._loadingTextDiv.innerHTML = this._loadingText;
  77374. }
  77375. },
  77376. enumerable: true,
  77377. configurable: true
  77378. });
  77379. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  77380. /**
  77381. * Gets or sets the color to use for the background
  77382. */
  77383. get: function () {
  77384. return this._loadingDivBackgroundColor;
  77385. },
  77386. set: function (color) {
  77387. this._loadingDivBackgroundColor = color;
  77388. if (!this._loadingDiv) {
  77389. return;
  77390. }
  77391. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77392. },
  77393. enumerable: true,
  77394. configurable: true
  77395. });
  77396. return DefaultLoadingScreen;
  77397. }());
  77398. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  77399. })(BABYLON || (BABYLON = {}));
  77400. //# sourceMappingURL=babylon.loadingScreen.js.map
  77401. var BABYLON;
  77402. (function (BABYLON) {
  77403. /**
  77404. * Class used to represent data loading progression
  77405. */
  77406. var SceneLoaderProgressEvent = /** @class */ (function () {
  77407. /**
  77408. * Create a new progress event
  77409. * @param lengthComputable defines if data length to load can be evaluated
  77410. * @param loaded defines the loaded data length
  77411. * @param total defines the data length to load
  77412. */
  77413. function SceneLoaderProgressEvent(
  77414. /** defines if data length to load can be evaluated */
  77415. lengthComputable,
  77416. /** defines the loaded data length */
  77417. loaded,
  77418. /** defines the data length to load */
  77419. total) {
  77420. this.lengthComputable = lengthComputable;
  77421. this.loaded = loaded;
  77422. this.total = total;
  77423. }
  77424. /**
  77425. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  77426. * @param event defines the source event
  77427. * @returns a new SceneLoaderProgressEvent
  77428. */
  77429. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  77430. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  77431. };
  77432. return SceneLoaderProgressEvent;
  77433. }());
  77434. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  77435. /**
  77436. * Class used to load scene from various file formats using registered plugins
  77437. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  77438. */
  77439. var SceneLoader = /** @class */ (function () {
  77440. function SceneLoader() {
  77441. }
  77442. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  77443. /**
  77444. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  77445. */
  77446. get: function () {
  77447. return SceneLoader._ForceFullSceneLoadingForIncremental;
  77448. },
  77449. set: function (value) {
  77450. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  77451. },
  77452. enumerable: true,
  77453. configurable: true
  77454. });
  77455. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  77456. /**
  77457. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  77458. */
  77459. get: function () {
  77460. return SceneLoader._ShowLoadingScreen;
  77461. },
  77462. set: function (value) {
  77463. SceneLoader._ShowLoadingScreen = value;
  77464. },
  77465. enumerable: true,
  77466. configurable: true
  77467. });
  77468. Object.defineProperty(SceneLoader, "loggingLevel", {
  77469. /**
  77470. * Defines the current logging level (while loading the scene)
  77471. * @ignorenaming
  77472. */
  77473. get: function () {
  77474. return SceneLoader._loggingLevel;
  77475. },
  77476. set: function (value) {
  77477. SceneLoader._loggingLevel = value;
  77478. },
  77479. enumerable: true,
  77480. configurable: true
  77481. });
  77482. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  77483. /**
  77484. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  77485. */
  77486. get: function () {
  77487. return SceneLoader._CleanBoneMatrixWeights;
  77488. },
  77489. set: function (value) {
  77490. SceneLoader._CleanBoneMatrixWeights = value;
  77491. },
  77492. enumerable: true,
  77493. configurable: true
  77494. });
  77495. SceneLoader._getDefaultPlugin = function () {
  77496. return SceneLoader._registeredPlugins[".babylon"];
  77497. };
  77498. SceneLoader._getPluginForExtension = function (extension) {
  77499. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  77500. if (registeredPlugin) {
  77501. return registeredPlugin;
  77502. }
  77503. 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");
  77504. return SceneLoader._getDefaultPlugin();
  77505. };
  77506. SceneLoader._getPluginForDirectLoad = function (data) {
  77507. for (var extension in SceneLoader._registeredPlugins) {
  77508. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  77509. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  77510. return SceneLoader._registeredPlugins[extension];
  77511. }
  77512. }
  77513. return SceneLoader._getDefaultPlugin();
  77514. };
  77515. SceneLoader._getPluginForFilename = function (sceneFilename) {
  77516. var queryStringPosition = sceneFilename.indexOf("?");
  77517. if (queryStringPosition !== -1) {
  77518. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  77519. }
  77520. var dotPosition = sceneFilename.lastIndexOf(".");
  77521. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  77522. return SceneLoader._getPluginForExtension(extension);
  77523. };
  77524. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  77525. SceneLoader._getDirectLoad = function (sceneFilename) {
  77526. if (sceneFilename.substr(0, 5) === "data:") {
  77527. return sceneFilename.substr(5);
  77528. }
  77529. return null;
  77530. };
  77531. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  77532. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  77533. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  77534. var plugin;
  77535. if (registeredPlugin.plugin.createPlugin) {
  77536. plugin = registeredPlugin.plugin.createPlugin();
  77537. }
  77538. else {
  77539. plugin = registeredPlugin.plugin;
  77540. }
  77541. var useArrayBuffer = registeredPlugin.isBinary;
  77542. var offlineProvider;
  77543. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  77544. var dataCallback = function (data, responseURL) {
  77545. if (scene.isDisposed) {
  77546. onError("Scene has been disposed");
  77547. return;
  77548. }
  77549. scene.offlineProvider = offlineProvider;
  77550. onSuccess(plugin, data, responseURL);
  77551. };
  77552. var request = null;
  77553. var pluginDisposed = false;
  77554. var onDisposeObservable = plugin.onDisposeObservable;
  77555. if (onDisposeObservable) {
  77556. onDisposeObservable.add(function () {
  77557. pluginDisposed = true;
  77558. if (request) {
  77559. request.abort();
  77560. request = null;
  77561. }
  77562. onDispose();
  77563. });
  77564. }
  77565. var manifestChecked = function () {
  77566. if (pluginDisposed) {
  77567. return;
  77568. }
  77569. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  77570. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  77571. } : undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  77572. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  77573. });
  77574. };
  77575. if (directLoad) {
  77576. dataCallback(directLoad);
  77577. return plugin;
  77578. }
  77579. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  77580. var engine = scene.getEngine();
  77581. var canUseOfflineSupport = engine.enableOfflineSupport;
  77582. if (canUseOfflineSupport) {
  77583. // Also check for exceptions
  77584. var exceptionFound = false;
  77585. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  77586. var regex = _a[_i];
  77587. if (regex.test(fileInfo.url)) {
  77588. exceptionFound = true;
  77589. break;
  77590. }
  77591. }
  77592. canUseOfflineSupport = !exceptionFound;
  77593. }
  77594. if (canUseOfflineSupport && BABYLON.Engine.OfflineProviderFactory) {
  77595. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  77596. offlineProvider = BABYLON.Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  77597. }
  77598. else {
  77599. manifestChecked();
  77600. }
  77601. }
  77602. // Loading file from disk via input file or drag'n'drop
  77603. else {
  77604. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  77605. if (file) {
  77606. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  77607. }
  77608. else {
  77609. onError("Unable to find file named " + fileInfo.name);
  77610. }
  77611. }
  77612. return plugin;
  77613. };
  77614. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  77615. var url;
  77616. var name;
  77617. if (!sceneFilename) {
  77618. url = rootUrl;
  77619. name = BABYLON.Tools.GetFilename(rootUrl);
  77620. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  77621. }
  77622. else {
  77623. if (sceneFilename.substr(0, 1) === "/") {
  77624. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  77625. return null;
  77626. }
  77627. url = rootUrl + sceneFilename;
  77628. name = sceneFilename;
  77629. }
  77630. return {
  77631. url: url,
  77632. rootUrl: rootUrl,
  77633. name: name
  77634. };
  77635. };
  77636. // Public functions
  77637. /**
  77638. * Gets a plugin that can load the given extension
  77639. * @param extension defines the extension to load
  77640. * @returns a plugin or null if none works
  77641. */
  77642. SceneLoader.GetPluginForExtension = function (extension) {
  77643. return SceneLoader._getPluginForExtension(extension).plugin;
  77644. };
  77645. /**
  77646. * Gets a boolean indicating that the given extension can be loaded
  77647. * @param extension defines the extension to load
  77648. * @returns true if the extension is supported
  77649. */
  77650. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  77651. return !!SceneLoader._registeredPlugins[extension];
  77652. };
  77653. /**
  77654. * Adds a new plugin to the list of registered plugins
  77655. * @param plugin defines the plugin to add
  77656. */
  77657. SceneLoader.RegisterPlugin = function (plugin) {
  77658. if (typeof plugin.extensions === "string") {
  77659. var extension = plugin.extensions;
  77660. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77661. plugin: plugin,
  77662. isBinary: false
  77663. };
  77664. }
  77665. else {
  77666. var extensions = plugin.extensions;
  77667. Object.keys(extensions).forEach(function (extension) {
  77668. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77669. plugin: plugin,
  77670. isBinary: extensions[extension].isBinary
  77671. };
  77672. });
  77673. }
  77674. };
  77675. /**
  77676. * Import meshes into a scene
  77677. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77678. * @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)
  77679. * @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)
  77680. * @param scene the instance of BABYLON.Scene to append to
  77681. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  77682. * @param onProgress a callback with a progress event for each file being loaded
  77683. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77684. * @param pluginExtension the extension used to determine the plugin
  77685. * @returns The loaded plugin
  77686. */
  77687. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77688. if (sceneFilename === void 0) { sceneFilename = ""; }
  77689. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77690. if (onSuccess === void 0) { onSuccess = null; }
  77691. if (onProgress === void 0) { onProgress = null; }
  77692. if (onError === void 0) { onError = null; }
  77693. if (pluginExtension === void 0) { pluginExtension = null; }
  77694. if (!scene) {
  77695. BABYLON.Tools.Error("No scene available to import mesh to");
  77696. return null;
  77697. }
  77698. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77699. if (!fileInfo) {
  77700. return null;
  77701. }
  77702. var loadingToken = {};
  77703. scene._addPendingData(loadingToken);
  77704. var disposeHandler = function () {
  77705. scene._removePendingData(loadingToken);
  77706. };
  77707. var errorHandler = function (message, exception) {
  77708. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  77709. if (onError) {
  77710. onError(scene, errorMessage, exception);
  77711. }
  77712. else {
  77713. BABYLON.Tools.Error(errorMessage);
  77714. // should the exception be thrown?
  77715. }
  77716. disposeHandler();
  77717. };
  77718. var progressHandler = onProgress ? function (event) {
  77719. try {
  77720. onProgress(event);
  77721. }
  77722. catch (e) {
  77723. errorHandler("Error in onProgress callback", e);
  77724. }
  77725. } : undefined;
  77726. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  77727. scene.importedMeshesFiles.push(fileInfo.url);
  77728. if (onSuccess) {
  77729. try {
  77730. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  77731. }
  77732. catch (e) {
  77733. errorHandler("Error in onSuccess callback", e);
  77734. }
  77735. }
  77736. scene._removePendingData(loadingToken);
  77737. };
  77738. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77739. if (plugin.rewriteRootURL) {
  77740. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  77741. }
  77742. if (plugin.importMesh) {
  77743. var syncedPlugin = plugin;
  77744. var meshes = new Array();
  77745. var particleSystems = new Array();
  77746. var skeletons = new Array();
  77747. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  77748. return;
  77749. }
  77750. scene.loadingPluginName = plugin.name;
  77751. successHandler(meshes, particleSystems, skeletons, []);
  77752. }
  77753. else {
  77754. var asyncedPlugin = plugin;
  77755. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  77756. scene.loadingPluginName = plugin.name;
  77757. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  77758. }).catch(function (error) {
  77759. errorHandler(error.message, error);
  77760. });
  77761. }
  77762. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77763. };
  77764. /**
  77765. * Import meshes into a scene
  77766. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77767. * @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)
  77768. * @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)
  77769. * @param scene the instance of BABYLON.Scene to append to
  77770. * @param onProgress a callback with a progress event for each file being loaded
  77771. * @param pluginExtension the extension used to determine the plugin
  77772. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  77773. */
  77774. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77775. if (sceneFilename === void 0) { sceneFilename = ""; }
  77776. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77777. if (onProgress === void 0) { onProgress = null; }
  77778. if (pluginExtension === void 0) { pluginExtension = null; }
  77779. return new Promise(function (resolve, reject) {
  77780. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  77781. resolve({
  77782. meshes: meshes,
  77783. particleSystems: particleSystems,
  77784. skeletons: skeletons,
  77785. animationGroups: animationGroups
  77786. });
  77787. }, onProgress, function (scene, message, exception) {
  77788. reject(exception || new Error(message));
  77789. }, pluginExtension);
  77790. });
  77791. };
  77792. /**
  77793. * Load a scene
  77794. * @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)
  77795. * @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)
  77796. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77797. * @param onSuccess a callback with the scene when import succeeds
  77798. * @param onProgress a callback with a progress event for each file being loaded
  77799. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77800. * @param pluginExtension the extension used to determine the plugin
  77801. * @returns The loaded plugin
  77802. */
  77803. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  77804. if (onSuccess === void 0) { onSuccess = null; }
  77805. if (onProgress === void 0) { onProgress = null; }
  77806. if (onError === void 0) { onError = null; }
  77807. if (pluginExtension === void 0) { pluginExtension = null; }
  77808. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  77809. };
  77810. /**
  77811. * Load a scene
  77812. * @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)
  77813. * @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)
  77814. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77815. * @param onProgress a callback with a progress event for each file being loaded
  77816. * @param pluginExtension the extension used to determine the plugin
  77817. * @returns The loaded scene
  77818. */
  77819. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  77820. if (onProgress === void 0) { onProgress = null; }
  77821. if (pluginExtension === void 0) { pluginExtension = null; }
  77822. return new Promise(function (resolve, reject) {
  77823. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  77824. resolve(scene);
  77825. }, onProgress, function (scene, message, exception) {
  77826. reject(exception || new Error(message));
  77827. }, pluginExtension);
  77828. });
  77829. };
  77830. /**
  77831. * Append a scene
  77832. * @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)
  77833. * @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)
  77834. * @param scene is the instance of BABYLON.Scene to append to
  77835. * @param onSuccess a callback with the scene when import succeeds
  77836. * @param onProgress a callback with a progress event for each file being loaded
  77837. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77838. * @param pluginExtension the extension used to determine the plugin
  77839. * @returns The loaded plugin
  77840. */
  77841. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77842. if (sceneFilename === void 0) { sceneFilename = ""; }
  77843. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77844. if (onSuccess === void 0) { onSuccess = null; }
  77845. if (onProgress === void 0) { onProgress = null; }
  77846. if (onError === void 0) { onError = null; }
  77847. if (pluginExtension === void 0) { pluginExtension = null; }
  77848. if (!scene) {
  77849. BABYLON.Tools.Error("No scene available to append to");
  77850. return null;
  77851. }
  77852. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77853. if (!fileInfo) {
  77854. return null;
  77855. }
  77856. if (SceneLoader.ShowLoadingScreen) {
  77857. scene.getEngine().displayLoadingUI();
  77858. }
  77859. var loadingToken = {};
  77860. scene._addPendingData(loadingToken);
  77861. var disposeHandler = function () {
  77862. scene._removePendingData(loadingToken);
  77863. scene.getEngine().hideLoadingUI();
  77864. };
  77865. var errorHandler = function (message, exception) {
  77866. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  77867. if (onError) {
  77868. onError(scene, errorMessage, exception);
  77869. }
  77870. else {
  77871. BABYLON.Tools.Error(errorMessage);
  77872. // should the exception be thrown?
  77873. }
  77874. disposeHandler();
  77875. };
  77876. var progressHandler = onProgress ? function (event) {
  77877. try {
  77878. onProgress(event);
  77879. }
  77880. catch (e) {
  77881. errorHandler("Error in onProgress callback", e);
  77882. }
  77883. } : undefined;
  77884. var successHandler = function () {
  77885. if (onSuccess) {
  77886. try {
  77887. onSuccess(scene);
  77888. }
  77889. catch (e) {
  77890. errorHandler("Error in onSuccess callback", e);
  77891. }
  77892. }
  77893. scene._removePendingData(loadingToken);
  77894. };
  77895. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77896. if (plugin.load) {
  77897. var syncedPlugin = plugin;
  77898. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  77899. return;
  77900. }
  77901. scene.loadingPluginName = plugin.name;
  77902. successHandler();
  77903. }
  77904. else {
  77905. var asyncedPlugin = plugin;
  77906. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  77907. scene.loadingPluginName = plugin.name;
  77908. successHandler();
  77909. }).catch(function (error) {
  77910. errorHandler(error.message, error);
  77911. });
  77912. }
  77913. if (SceneLoader.ShowLoadingScreen) {
  77914. scene.executeWhenReady(function () {
  77915. scene.getEngine().hideLoadingUI();
  77916. });
  77917. }
  77918. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77919. };
  77920. /**
  77921. * Append a scene
  77922. * @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)
  77923. * @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)
  77924. * @param scene is the instance of BABYLON.Scene to append to
  77925. * @param onProgress a callback with a progress event for each file being loaded
  77926. * @param pluginExtension the extension used to determine the plugin
  77927. * @returns The given scene
  77928. */
  77929. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77930. if (sceneFilename === void 0) { sceneFilename = ""; }
  77931. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77932. if (onProgress === void 0) { onProgress = null; }
  77933. if (pluginExtension === void 0) { pluginExtension = null; }
  77934. return new Promise(function (resolve, reject) {
  77935. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  77936. resolve(scene);
  77937. }, onProgress, function (scene, message, exception) {
  77938. reject(exception || new Error(message));
  77939. }, pluginExtension);
  77940. });
  77941. };
  77942. /**
  77943. * Load a scene into an asset container
  77944. * @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)
  77945. * @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)
  77946. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  77947. * @param onSuccess a callback with the scene when import succeeds
  77948. * @param onProgress a callback with a progress event for each file being loaded
  77949. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77950. * @param pluginExtension the extension used to determine the plugin
  77951. * @returns The loaded plugin
  77952. */
  77953. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77954. if (sceneFilename === void 0) { sceneFilename = ""; }
  77955. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77956. if (onSuccess === void 0) { onSuccess = null; }
  77957. if (onProgress === void 0) { onProgress = null; }
  77958. if (onError === void 0) { onError = null; }
  77959. if (pluginExtension === void 0) { pluginExtension = null; }
  77960. if (!scene) {
  77961. BABYLON.Tools.Error("No scene available to load asset container to");
  77962. return null;
  77963. }
  77964. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77965. if (!fileInfo) {
  77966. return null;
  77967. }
  77968. var loadingToken = {};
  77969. scene._addPendingData(loadingToken);
  77970. var disposeHandler = function () {
  77971. scene._removePendingData(loadingToken);
  77972. };
  77973. var errorHandler = function (message, exception) {
  77974. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  77975. if (onError) {
  77976. onError(scene, errorMessage, exception);
  77977. }
  77978. else {
  77979. BABYLON.Tools.Error(errorMessage);
  77980. // should the exception be thrown?
  77981. }
  77982. disposeHandler();
  77983. };
  77984. var progressHandler = onProgress ? function (event) {
  77985. try {
  77986. onProgress(event);
  77987. }
  77988. catch (e) {
  77989. errorHandler("Error in onProgress callback", e);
  77990. }
  77991. } : undefined;
  77992. var successHandler = function (assets) {
  77993. if (onSuccess) {
  77994. try {
  77995. onSuccess(assets);
  77996. }
  77997. catch (e) {
  77998. errorHandler("Error in onSuccess callback", e);
  77999. }
  78000. }
  78001. scene._removePendingData(loadingToken);
  78002. };
  78003. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  78004. if (plugin.loadAssetContainer) {
  78005. var syncedPlugin = plugin;
  78006. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  78007. if (!assetContainer) {
  78008. return;
  78009. }
  78010. scene.loadingPluginName = plugin.name;
  78011. successHandler(assetContainer);
  78012. }
  78013. else if (plugin.loadAssetContainerAsync) {
  78014. var asyncedPlugin = plugin;
  78015. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  78016. scene.loadingPluginName = plugin.name;
  78017. successHandler(assetContainer);
  78018. }).catch(function (error) {
  78019. errorHandler(error.message, error);
  78020. });
  78021. }
  78022. else {
  78023. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  78024. }
  78025. if (SceneLoader.ShowLoadingScreen) {
  78026. scene.executeWhenReady(function () {
  78027. scene.getEngine().hideLoadingUI();
  78028. });
  78029. }
  78030. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  78031. };
  78032. /**
  78033. * Load a scene into an asset container
  78034. * @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)
  78035. * @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)
  78036. * @param scene is the instance of BABYLON.Scene to append to
  78037. * @param onProgress a callback with a progress event for each file being loaded
  78038. * @param pluginExtension the extension used to determine the plugin
  78039. * @returns The loaded asset container
  78040. */
  78041. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78042. if (sceneFilename === void 0) { sceneFilename = ""; }
  78043. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78044. if (onProgress === void 0) { onProgress = null; }
  78045. if (pluginExtension === void 0) { pluginExtension = null; }
  78046. return new Promise(function (resolve, reject) {
  78047. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  78048. resolve(assetContainer);
  78049. }, onProgress, function (scene, message, exception) {
  78050. reject(exception || new Error(message));
  78051. }, pluginExtension);
  78052. });
  78053. };
  78054. // Flags
  78055. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  78056. SceneLoader._ShowLoadingScreen = true;
  78057. SceneLoader._CleanBoneMatrixWeights = false;
  78058. /**
  78059. * No logging while loading
  78060. */
  78061. SceneLoader.NO_LOGGING = 0;
  78062. /**
  78063. * Minimal logging while loading
  78064. */
  78065. SceneLoader.MINIMAL_LOGGING = 1;
  78066. /**
  78067. * Summary logging while loading
  78068. */
  78069. SceneLoader.SUMMARY_LOGGING = 2;
  78070. /**
  78071. * Detailled logging while loading
  78072. */
  78073. SceneLoader.DETAILED_LOGGING = 3;
  78074. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  78075. // Members
  78076. /**
  78077. * Event raised when a plugin is used to load a scene
  78078. */
  78079. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  78080. SceneLoader._registeredPlugins = {};
  78081. return SceneLoader;
  78082. }());
  78083. BABYLON.SceneLoader = SceneLoader;
  78084. })(BABYLON || (BABYLON = {}));
  78085. //# sourceMappingURL=babylon.sceneLoader.js.map
  78086. var BABYLON;
  78087. (function (BABYLON) {
  78088. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  78089. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78090. var parsedMaterial = parsedData.materials[index];
  78091. if (parsedMaterial.id === id) {
  78092. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78093. }
  78094. }
  78095. return null;
  78096. };
  78097. var isDescendantOf = function (mesh, names, hierarchyIds) {
  78098. for (var i in names) {
  78099. if (mesh.name === names[i]) {
  78100. hierarchyIds.push(mesh.id);
  78101. return true;
  78102. }
  78103. }
  78104. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  78105. hierarchyIds.push(mesh.id);
  78106. return true;
  78107. }
  78108. return false;
  78109. };
  78110. var logOperation = function (operation, producer) {
  78111. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  78112. };
  78113. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  78114. if (addToScene === void 0) { addToScene = false; }
  78115. var container = new BABYLON.AssetContainer(scene);
  78116. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78117. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78118. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78119. // and avoid problems with multiple concurrent .babylon loads.
  78120. var log = "importScene has failed JSON parse";
  78121. try {
  78122. var parsedData = JSON.parse(data);
  78123. log = "";
  78124. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78125. var index;
  78126. var cache;
  78127. // Lights
  78128. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  78129. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  78130. var parsedLight = parsedData.lights[index];
  78131. var light = BABYLON.Light.Parse(parsedLight, scene);
  78132. if (light) {
  78133. container.lights.push(light);
  78134. log += (index === 0 ? "\n\tLights:" : "");
  78135. log += "\n\t\t" + light.toString(fullDetails);
  78136. }
  78137. }
  78138. }
  78139. // Animations
  78140. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  78141. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  78142. var parsedAnimation = parsedData.animations[index];
  78143. var animation = BABYLON.Animation.Parse(parsedAnimation);
  78144. scene.animations.push(animation);
  78145. container.animations.push(animation);
  78146. log += (index === 0 ? "\n\tAnimations:" : "");
  78147. log += "\n\t\t" + animation.toString(fullDetails);
  78148. }
  78149. }
  78150. // Materials
  78151. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  78152. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78153. var parsedMaterial = parsedData.materials[index];
  78154. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78155. container.materials.push(mat);
  78156. log += (index === 0 ? "\n\tMaterials:" : "");
  78157. log += "\n\t\t" + mat.toString(fullDetails);
  78158. }
  78159. }
  78160. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78161. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  78162. var parsedMultiMaterial = parsedData.multiMaterials[index];
  78163. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78164. container.multiMaterials.push(mmat);
  78165. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  78166. log += "\n\t\t" + mmat.toString(fullDetails);
  78167. }
  78168. }
  78169. // Morph targets
  78170. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78171. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78172. var managerData = _a[_i];
  78173. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  78174. }
  78175. }
  78176. // Skeletons
  78177. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78178. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  78179. var parsedSkeleton = parsedData.skeletons[index];
  78180. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78181. container.skeletons.push(skeleton);
  78182. log += (index === 0 ? "\n\tSkeletons:" : "");
  78183. log += "\n\t\t" + skeleton.toString(fullDetails);
  78184. }
  78185. }
  78186. // Geometries
  78187. var geometries = parsedData.geometries;
  78188. if (geometries !== undefined && geometries !== null) {
  78189. var addedGeometry = new Array();
  78190. // Boxes
  78191. var boxes = geometries.boxes;
  78192. if (boxes !== undefined && boxes !== null) {
  78193. for (index = 0, cache = boxes.length; index < cache; index++) {
  78194. var parsedBox = boxes[index];
  78195. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  78196. }
  78197. }
  78198. // Spheres
  78199. var spheres = geometries.spheres;
  78200. if (spheres !== undefined && spheres !== null) {
  78201. for (index = 0, cache = spheres.length; index < cache; index++) {
  78202. var parsedSphere = spheres[index];
  78203. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  78204. }
  78205. }
  78206. // Cylinders
  78207. var cylinders = geometries.cylinders;
  78208. if (cylinders !== undefined && cylinders !== null) {
  78209. for (index = 0, cache = cylinders.length; index < cache; index++) {
  78210. var parsedCylinder = cylinders[index];
  78211. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  78212. }
  78213. }
  78214. // Toruses
  78215. var toruses = geometries.toruses;
  78216. if (toruses !== undefined && toruses !== null) {
  78217. for (index = 0, cache = toruses.length; index < cache; index++) {
  78218. var parsedTorus = toruses[index];
  78219. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  78220. }
  78221. }
  78222. // Grounds
  78223. var grounds = geometries.grounds;
  78224. if (grounds !== undefined && grounds !== null) {
  78225. for (index = 0, cache = grounds.length; index < cache; index++) {
  78226. var parsedGround = grounds[index];
  78227. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  78228. }
  78229. }
  78230. // Planes
  78231. var planes = geometries.planes;
  78232. if (planes !== undefined && planes !== null) {
  78233. for (index = 0, cache = planes.length; index < cache; index++) {
  78234. var parsedPlane = planes[index];
  78235. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  78236. }
  78237. }
  78238. // TorusKnots
  78239. var torusKnots = geometries.torusKnots;
  78240. if (torusKnots !== undefined && torusKnots !== null) {
  78241. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  78242. var parsedTorusKnot = torusKnots[index];
  78243. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  78244. }
  78245. }
  78246. // VertexData
  78247. var vertexData = geometries.vertexData;
  78248. if (vertexData !== undefined && vertexData !== null) {
  78249. for (index = 0, cache = vertexData.length; index < cache; index++) {
  78250. var parsedVertexData = vertexData[index];
  78251. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  78252. }
  78253. }
  78254. addedGeometry.forEach(function (g) {
  78255. if (g) {
  78256. container.geometries.push(g);
  78257. }
  78258. });
  78259. }
  78260. // Transform nodes
  78261. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  78262. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  78263. var parsedTransformNode = parsedData.transformNodes[index];
  78264. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  78265. container.transformNodes.push(node);
  78266. }
  78267. }
  78268. // Meshes
  78269. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78270. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78271. var parsedMesh = parsedData.meshes[index];
  78272. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78273. container.meshes.push(mesh);
  78274. log += (index === 0 ? "\n\tMeshes:" : "");
  78275. log += "\n\t\t" + mesh.toString(fullDetails);
  78276. }
  78277. }
  78278. // Cameras
  78279. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  78280. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  78281. var parsedCamera = parsedData.cameras[index];
  78282. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  78283. container.cameras.push(camera);
  78284. log += (index === 0 ? "\n\tCameras:" : "");
  78285. log += "\n\t\t" + camera.toString(fullDetails);
  78286. }
  78287. }
  78288. // Animation Groups
  78289. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  78290. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  78291. var parsedAnimationGroup = parsedData.animationGroups[index];
  78292. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  78293. container.animationGroups.push(animationGroup);
  78294. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  78295. log += "\n\t\t" + animationGroup.toString(fullDetails);
  78296. }
  78297. }
  78298. // Browsing all the graph to connect the dots
  78299. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  78300. var camera = scene.cameras[index];
  78301. if (camera._waitingParentId) {
  78302. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  78303. camera._waitingParentId = null;
  78304. }
  78305. }
  78306. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78307. var light_1 = scene.lights[index];
  78308. if (light_1 && light_1._waitingParentId) {
  78309. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  78310. light_1._waitingParentId = null;
  78311. }
  78312. }
  78313. // Connect parents & children and parse actions
  78314. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  78315. var transformNode = scene.transformNodes[index];
  78316. if (transformNode._waitingParentId) {
  78317. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  78318. transformNode._waitingParentId = null;
  78319. }
  78320. }
  78321. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78322. var mesh = scene.meshes[index];
  78323. if (mesh._waitingParentId) {
  78324. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  78325. mesh._waitingParentId = null;
  78326. }
  78327. }
  78328. // freeze world matrix application
  78329. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78330. var currentMesh = scene.meshes[index];
  78331. if (currentMesh._waitingFreezeWorldMatrix) {
  78332. currentMesh.freezeWorldMatrix();
  78333. currentMesh._waitingFreezeWorldMatrix = null;
  78334. }
  78335. else {
  78336. currentMesh.computeWorldMatrix(true);
  78337. }
  78338. }
  78339. // Lights exclusions / inclusions
  78340. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78341. var light_2 = scene.lights[index];
  78342. // Excluded check
  78343. if (light_2._excludedMeshesIds.length > 0) {
  78344. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  78345. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  78346. if (excludedMesh) {
  78347. light_2.excludedMeshes.push(excludedMesh);
  78348. }
  78349. }
  78350. light_2._excludedMeshesIds = [];
  78351. }
  78352. // Included check
  78353. if (light_2._includedOnlyMeshesIds.length > 0) {
  78354. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  78355. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  78356. if (includedOnlyMesh) {
  78357. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  78358. }
  78359. }
  78360. light_2._includedOnlyMeshesIds = [];
  78361. }
  78362. }
  78363. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  78364. // Actions (scene) Done last as it can access other objects.
  78365. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78366. var mesh = scene.meshes[index];
  78367. if (mesh._waitingActions) {
  78368. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  78369. mesh._waitingActions = null;
  78370. }
  78371. }
  78372. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  78373. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  78374. }
  78375. if (!addToScene) {
  78376. container.removeAllFromScene();
  78377. }
  78378. }
  78379. catch (err) {
  78380. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  78381. if (onError) {
  78382. onError(msg, err);
  78383. }
  78384. else {
  78385. BABYLON.Tools.Log(msg);
  78386. throw err;
  78387. }
  78388. }
  78389. finally {
  78390. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78391. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78392. }
  78393. }
  78394. return container;
  78395. };
  78396. BABYLON.SceneLoader.RegisterPlugin({
  78397. name: "babylon.js",
  78398. extensions: ".babylon",
  78399. canDirectLoad: function (data) {
  78400. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  78401. return true;
  78402. }
  78403. return false;
  78404. },
  78405. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  78406. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78407. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78408. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78409. // and avoid problems with multiple concurrent .babylon loads.
  78410. var log = "importMesh has failed JSON parse";
  78411. try {
  78412. var parsedData = JSON.parse(data);
  78413. log = "";
  78414. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78415. if (!meshesNames) {
  78416. meshesNames = null;
  78417. }
  78418. else if (!Array.isArray(meshesNames)) {
  78419. meshesNames = [meshesNames];
  78420. }
  78421. var hierarchyIds = new Array();
  78422. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78423. var loadedSkeletonsIds = [];
  78424. var loadedMaterialsIds = [];
  78425. var index;
  78426. var cache;
  78427. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78428. var parsedMesh = parsedData.meshes[index];
  78429. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  78430. if (meshesNames !== null) {
  78431. // Remove found mesh name from list.
  78432. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  78433. }
  78434. //Geometry?
  78435. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  78436. //does the file contain geometries?
  78437. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  78438. //find the correct geometry and add it to the scene
  78439. var found = false;
  78440. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  78441. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  78442. return;
  78443. }
  78444. else {
  78445. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  78446. if (parsedGeometryData.id === parsedMesh.geometryId) {
  78447. switch (geometryType) {
  78448. case "boxes":
  78449. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  78450. break;
  78451. case "spheres":
  78452. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  78453. break;
  78454. case "cylinders":
  78455. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  78456. break;
  78457. case "toruses":
  78458. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  78459. break;
  78460. case "grounds":
  78461. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  78462. break;
  78463. case "planes":
  78464. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  78465. break;
  78466. case "torusKnots":
  78467. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  78468. break;
  78469. case "vertexData":
  78470. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  78471. break;
  78472. }
  78473. found = true;
  78474. }
  78475. });
  78476. }
  78477. });
  78478. if (found === false) {
  78479. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  78480. }
  78481. }
  78482. }
  78483. // Material ?
  78484. if (parsedMesh.materialId) {
  78485. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  78486. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78487. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  78488. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  78489. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  78490. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  78491. var subMatId = parsedMultiMaterial.materials[matIndex];
  78492. loadedMaterialsIds.push(subMatId);
  78493. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  78494. if (mat) {
  78495. log += "\n\tMaterial " + mat.toString(fullDetails);
  78496. }
  78497. }
  78498. loadedMaterialsIds.push(parsedMultiMaterial.id);
  78499. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78500. if (mmat) {
  78501. materialFound = true;
  78502. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  78503. }
  78504. break;
  78505. }
  78506. }
  78507. }
  78508. if (materialFound === false) {
  78509. loadedMaterialsIds.push(parsedMesh.materialId);
  78510. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  78511. if (!mat) {
  78512. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  78513. }
  78514. else {
  78515. log += "\n\tMaterial " + mat.toString(fullDetails);
  78516. }
  78517. }
  78518. }
  78519. // Skeleton ?
  78520. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78521. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  78522. if (skeletonAlreadyLoaded === false) {
  78523. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  78524. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  78525. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  78526. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78527. skeletons.push(skeleton);
  78528. loadedSkeletonsIds.push(parsedSkeleton.id);
  78529. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  78530. }
  78531. }
  78532. }
  78533. }
  78534. // Morph targets ?
  78535. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78536. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78537. var managerData = _a[_i];
  78538. BABYLON.MorphTargetManager.Parse(managerData, scene);
  78539. }
  78540. }
  78541. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78542. meshes.push(mesh);
  78543. log += "\n\tMesh " + mesh.toString(fullDetails);
  78544. }
  78545. }
  78546. // Connecting parents
  78547. var currentMesh;
  78548. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78549. currentMesh = scene.meshes[index];
  78550. if (currentMesh._waitingParentId) {
  78551. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  78552. currentMesh._waitingParentId = null;
  78553. }
  78554. }
  78555. // freeze and compute world matrix application
  78556. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78557. currentMesh = scene.meshes[index];
  78558. if (currentMesh._waitingFreezeWorldMatrix) {
  78559. currentMesh.freezeWorldMatrix();
  78560. currentMesh._waitingFreezeWorldMatrix = null;
  78561. }
  78562. else {
  78563. currentMesh.computeWorldMatrix(true);
  78564. }
  78565. }
  78566. }
  78567. // Particles
  78568. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  78569. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  78570. if (parser) {
  78571. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  78572. var parsedParticleSystem = parsedData.particleSystems[index];
  78573. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  78574. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  78575. }
  78576. }
  78577. }
  78578. }
  78579. return true;
  78580. }
  78581. catch (err) {
  78582. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  78583. if (onError) {
  78584. onError(msg, err);
  78585. }
  78586. else {
  78587. BABYLON.Tools.Log(msg);
  78588. throw err;
  78589. }
  78590. }
  78591. finally {
  78592. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78593. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78594. }
  78595. }
  78596. return false;
  78597. },
  78598. load: function (scene, data, rootUrl, onError) {
  78599. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78600. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78601. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78602. // and avoid problems with multiple concurrent .babylon loads.
  78603. var log = "importScene has failed JSON parse";
  78604. try {
  78605. var parsedData = JSON.parse(data);
  78606. log = "";
  78607. // Scene
  78608. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  78609. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  78610. }
  78611. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  78612. scene.autoClear = parsedData.autoClear;
  78613. }
  78614. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  78615. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  78616. }
  78617. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  78618. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  78619. }
  78620. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  78621. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  78622. }
  78623. // Fog
  78624. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  78625. scene.fogMode = parsedData.fogMode;
  78626. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  78627. scene.fogStart = parsedData.fogStart;
  78628. scene.fogEnd = parsedData.fogEnd;
  78629. scene.fogDensity = parsedData.fogDensity;
  78630. log += "\tFog mode for scene: ";
  78631. switch (scene.fogMode) {
  78632. // getters not compiling, so using hardcoded
  78633. case 1:
  78634. log += "exp\n";
  78635. break;
  78636. case 2:
  78637. log += "exp2\n";
  78638. break;
  78639. case 3:
  78640. log += "linear\n";
  78641. break;
  78642. }
  78643. }
  78644. //Physics
  78645. if (parsedData.physicsEnabled) {
  78646. var physicsPlugin;
  78647. if (parsedData.physicsEngine === "cannon") {
  78648. physicsPlugin = new BABYLON.CannonJSPlugin();
  78649. }
  78650. else if (parsedData.physicsEngine === "oimo") {
  78651. physicsPlugin = new BABYLON.OimoJSPlugin();
  78652. }
  78653. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  78654. //else - default engine, which is currently oimo
  78655. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  78656. scene.enablePhysics(physicsGravity, physicsPlugin);
  78657. }
  78658. // Metadata
  78659. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  78660. scene.metadata = parsedData.metadata;
  78661. }
  78662. //collisions, if defined. otherwise, default is true
  78663. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  78664. scene.collisionsEnabled = parsedData.collisionsEnabled;
  78665. }
  78666. scene.workerCollisions = !!parsedData.workerCollisions;
  78667. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  78668. if (!container) {
  78669. return false;
  78670. }
  78671. if (parsedData.autoAnimate) {
  78672. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  78673. }
  78674. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  78675. scene.setActiveCameraByID(parsedData.activeCameraID);
  78676. }
  78677. // Environment texture
  78678. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  78679. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  78680. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  78681. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  78682. if (parsedData.environmentTextureRotationY) {
  78683. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  78684. }
  78685. scene.environmentTexture = hdrTexture;
  78686. }
  78687. else {
  78688. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  78689. if (parsedData.environmentTextureRotationY) {
  78690. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  78691. }
  78692. scene.environmentTexture = cubeTexture;
  78693. }
  78694. if (parsedData.createDefaultSkybox === true) {
  78695. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  78696. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  78697. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  78698. }
  78699. }
  78700. // Finish
  78701. return true;
  78702. }
  78703. catch (err) {
  78704. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  78705. if (onError) {
  78706. onError(msg, err);
  78707. }
  78708. else {
  78709. BABYLON.Tools.Log(msg);
  78710. throw err;
  78711. }
  78712. }
  78713. finally {
  78714. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78715. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78716. }
  78717. }
  78718. return false;
  78719. },
  78720. loadAssetContainer: function (scene, data, rootUrl, onError) {
  78721. var container = loadAssetContainer(scene, data, rootUrl, onError);
  78722. return container;
  78723. }
  78724. });
  78725. })(BABYLON || (BABYLON = {}));
  78726. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  78727. var BABYLON;
  78728. (function (BABYLON) {
  78729. /**
  78730. * Class used to help managing file picking and drag'n'drop
  78731. */
  78732. var FilesInput = /** @class */ (function () {
  78733. /**
  78734. * Creates a new FilesInput
  78735. * @param engine defines the rendering engine
  78736. * @param scene defines the hosting scene
  78737. * @param sceneLoadedCallback callback called when scene is loaded
  78738. * @param progressCallback callback called to track progress
  78739. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  78740. * @param textureLoadingCallback callback called when a texture is loading
  78741. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  78742. * @param onReloadCallback callback called when a reload is requested
  78743. * @param errorCallback callback call if an error occurs
  78744. */
  78745. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  78746. /**
  78747. * Callback called when a file is processed
  78748. */
  78749. this.onProcessFileCallback = function () { return true; };
  78750. this._engine = engine;
  78751. this._currentScene = scene;
  78752. this._sceneLoadedCallback = sceneLoadedCallback;
  78753. this._progressCallback = progressCallback;
  78754. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  78755. this._textureLoadingCallback = textureLoadingCallback;
  78756. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  78757. this._onReloadCallback = onReloadCallback;
  78758. this._errorCallback = errorCallback;
  78759. }
  78760. /**
  78761. * Calls this function to listen to drag'n'drop events on a specific DOM element
  78762. * @param elementToMonitor defines the DOM element to track
  78763. */
  78764. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  78765. var _this = this;
  78766. if (elementToMonitor) {
  78767. this._elementToMonitor = elementToMonitor;
  78768. this._dragEnterHandler = function (e) { _this.drag(e); };
  78769. this._dragOverHandler = function (e) { _this.drag(e); };
  78770. this._dropHandler = function (e) { _this.drop(e); };
  78771. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  78772. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  78773. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  78774. }
  78775. };
  78776. /**
  78777. * Release all associated resources
  78778. */
  78779. FilesInput.prototype.dispose = function () {
  78780. if (!this._elementToMonitor) {
  78781. return;
  78782. }
  78783. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  78784. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  78785. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  78786. };
  78787. FilesInput.prototype.renderFunction = function () {
  78788. if (this._additionalRenderLoopLogicCallback) {
  78789. this._additionalRenderLoopLogicCallback();
  78790. }
  78791. if (this._currentScene) {
  78792. if (this._textureLoadingCallback) {
  78793. var remaining = this._currentScene.getWaitingItemsCount();
  78794. if (remaining > 0) {
  78795. this._textureLoadingCallback(remaining);
  78796. }
  78797. }
  78798. this._currentScene.render();
  78799. }
  78800. };
  78801. FilesInput.prototype.drag = function (e) {
  78802. e.stopPropagation();
  78803. e.preventDefault();
  78804. };
  78805. FilesInput.prototype.drop = function (eventDrop) {
  78806. eventDrop.stopPropagation();
  78807. eventDrop.preventDefault();
  78808. this.loadFiles(eventDrop);
  78809. };
  78810. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  78811. var _this = this;
  78812. var reader = folder.createReader();
  78813. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  78814. reader.readEntries(function (entries) {
  78815. remaining.count += entries.length;
  78816. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  78817. var entry = entries_1[_i];
  78818. if (entry.isFile) {
  78819. entry.file(function (file) {
  78820. file.correctName = relativePath + file.name;
  78821. files.push(file);
  78822. if (--remaining.count === 0) {
  78823. callback();
  78824. }
  78825. });
  78826. }
  78827. else if (entry.isDirectory) {
  78828. _this._traverseFolder(entry, files, remaining, callback);
  78829. }
  78830. }
  78831. if (--remaining.count) {
  78832. callback();
  78833. }
  78834. });
  78835. };
  78836. FilesInput.prototype._processFiles = function (files) {
  78837. for (var i = 0; i < files.length; i++) {
  78838. var name = files[i].correctName.toLowerCase();
  78839. var extension = name.split('.').pop();
  78840. if (!this.onProcessFileCallback(files[i], name, extension)) {
  78841. continue;
  78842. }
  78843. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  78844. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  78845. this._sceneFileToLoad = files[i];
  78846. }
  78847. FilesInput.FilesToLoad[name] = files[i];
  78848. }
  78849. };
  78850. /**
  78851. * Load files from a drop event
  78852. * @param event defines the drop event to use as source
  78853. */
  78854. FilesInput.prototype.loadFiles = function (event) {
  78855. var _this = this;
  78856. // Handling data transfer via drag'n'drop
  78857. if (event && event.dataTransfer && event.dataTransfer.files) {
  78858. this._filesToLoad = event.dataTransfer.files;
  78859. }
  78860. // Handling files from input files
  78861. if (event && event.target && event.target.files) {
  78862. this._filesToLoad = event.target.files;
  78863. }
  78864. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  78865. return;
  78866. }
  78867. if (this._startingProcessingFilesCallback) {
  78868. this._startingProcessingFilesCallback(this._filesToLoad);
  78869. }
  78870. if (this._filesToLoad && this._filesToLoad.length > 0) {
  78871. var files_1 = new Array();
  78872. var folders = [];
  78873. var items = event.dataTransfer ? event.dataTransfer.items : null;
  78874. for (var i = 0; i < this._filesToLoad.length; i++) {
  78875. var fileToLoad = this._filesToLoad[i];
  78876. var name_1 = fileToLoad.name.toLowerCase();
  78877. var entry = void 0;
  78878. fileToLoad.correctName = name_1;
  78879. if (items) {
  78880. var item = items[i];
  78881. if (item.getAsEntry) {
  78882. entry = item.getAsEntry();
  78883. }
  78884. else if (item.webkitGetAsEntry) {
  78885. entry = item.webkitGetAsEntry();
  78886. }
  78887. }
  78888. if (!entry) {
  78889. files_1.push(fileToLoad);
  78890. }
  78891. else {
  78892. if (entry.isDirectory) {
  78893. folders.push(entry);
  78894. }
  78895. else {
  78896. files_1.push(fileToLoad);
  78897. }
  78898. }
  78899. }
  78900. if (folders.length === 0) {
  78901. this._processFiles(files_1);
  78902. this._processReload();
  78903. }
  78904. else {
  78905. var remaining = { count: folders.length };
  78906. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  78907. var folder = folders_1[_i];
  78908. this._traverseFolder(folder, files_1, remaining, function () {
  78909. _this._processFiles(files_1);
  78910. if (remaining.count === 0) {
  78911. _this._processReload();
  78912. }
  78913. });
  78914. }
  78915. }
  78916. }
  78917. };
  78918. FilesInput.prototype._processReload = function () {
  78919. if (this._onReloadCallback) {
  78920. this._onReloadCallback(this._sceneFileToLoad);
  78921. }
  78922. else {
  78923. this.reload();
  78924. }
  78925. };
  78926. /**
  78927. * Reload the current scene from the loaded files
  78928. */
  78929. FilesInput.prototype.reload = function () {
  78930. var _this = this;
  78931. // If a scene file has been provided
  78932. if (this._sceneFileToLoad) {
  78933. if (this._currentScene) {
  78934. if (BABYLON.Tools.errorsCount > 0) {
  78935. BABYLON.Tools.ClearLogCache();
  78936. }
  78937. this._engine.stopRenderLoop();
  78938. }
  78939. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  78940. if (_this._progressCallback) {
  78941. _this._progressCallback(progress);
  78942. }
  78943. }).then(function (scene) {
  78944. if (_this._currentScene) {
  78945. _this._currentScene.dispose();
  78946. }
  78947. _this._currentScene = scene;
  78948. if (_this._sceneLoadedCallback) {
  78949. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  78950. }
  78951. // Wait for textures and shaders to be ready
  78952. _this._currentScene.executeWhenReady(function () {
  78953. _this._engine.runRenderLoop(function () {
  78954. _this.renderFunction();
  78955. });
  78956. });
  78957. }).catch(function (error) {
  78958. if (_this._errorCallback) {
  78959. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  78960. }
  78961. });
  78962. }
  78963. else {
  78964. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  78965. }
  78966. };
  78967. /**
  78968. * List of files ready to be loaded
  78969. */
  78970. FilesInput.FilesToLoad = {};
  78971. return FilesInput;
  78972. }());
  78973. BABYLON.FilesInput = FilesInput;
  78974. })(BABYLON || (BABYLON = {}));
  78975. //# sourceMappingURL=babylon.filesInput.js.map
  78976. var BABYLON;
  78977. (function (BABYLON) {
  78978. /**
  78979. * Class used to store custom tags
  78980. */
  78981. var Tags = /** @class */ (function () {
  78982. function Tags() {
  78983. }
  78984. /**
  78985. * Adds support for tags on the given object
  78986. * @param obj defines the object to use
  78987. */
  78988. Tags.EnableFor = function (obj) {
  78989. obj._tags = obj._tags || {};
  78990. obj.hasTags = function () {
  78991. return Tags.HasTags(obj);
  78992. };
  78993. obj.addTags = function (tagsString) {
  78994. return Tags.AddTagsTo(obj, tagsString);
  78995. };
  78996. obj.removeTags = function (tagsString) {
  78997. return Tags.RemoveTagsFrom(obj, tagsString);
  78998. };
  78999. obj.matchesTagsQuery = function (tagsQuery) {
  79000. return Tags.MatchesQuery(obj, tagsQuery);
  79001. };
  79002. };
  79003. /**
  79004. * Removes tags support
  79005. * @param obj defines the object to use
  79006. */
  79007. Tags.DisableFor = function (obj) {
  79008. delete obj._tags;
  79009. delete obj.hasTags;
  79010. delete obj.addTags;
  79011. delete obj.removeTags;
  79012. delete obj.matchesTagsQuery;
  79013. };
  79014. /**
  79015. * Gets a boolean indicating if the given object has tags
  79016. * @param obj defines the object to use
  79017. * @returns a boolean
  79018. */
  79019. Tags.HasTags = function (obj) {
  79020. if (!obj._tags) {
  79021. return false;
  79022. }
  79023. return !BABYLON.Tools.IsEmpty(obj._tags);
  79024. };
  79025. /**
  79026. * Gets the tags available on a given object
  79027. * @param obj defines the object to use
  79028. * @param asString defines if the tags must be returned as a string instead of an array of strings
  79029. * @returns the tags
  79030. */
  79031. Tags.GetTags = function (obj, asString) {
  79032. if (asString === void 0) { asString = true; }
  79033. if (!obj._tags) {
  79034. return null;
  79035. }
  79036. if (asString) {
  79037. var tagsArray = [];
  79038. for (var tag in obj._tags) {
  79039. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  79040. tagsArray.push(tag);
  79041. }
  79042. }
  79043. return tagsArray.join(" ");
  79044. }
  79045. else {
  79046. return obj._tags;
  79047. }
  79048. };
  79049. /**
  79050. * Adds tags to an object
  79051. * @param obj defines the object to use
  79052. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  79053. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  79054. */
  79055. Tags.AddTagsTo = function (obj, tagsString) {
  79056. if (!tagsString) {
  79057. return;
  79058. }
  79059. if (typeof tagsString !== "string") {
  79060. return;
  79061. }
  79062. var tags = tagsString.split(" ");
  79063. tags.forEach(function (tag, index, array) {
  79064. Tags._AddTagTo(obj, tag);
  79065. });
  79066. };
  79067. /**
  79068. * @hidden
  79069. */
  79070. Tags._AddTagTo = function (obj, tag) {
  79071. tag = tag.trim();
  79072. if (tag === "" || tag === "true" || tag === "false") {
  79073. return;
  79074. }
  79075. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  79076. return;
  79077. }
  79078. Tags.EnableFor(obj);
  79079. obj._tags[tag] = true;
  79080. };
  79081. /**
  79082. * Removes specific tags from a specific object
  79083. * @param obj defines the object to use
  79084. * @param tagsString defines the tags to remove
  79085. */
  79086. Tags.RemoveTagsFrom = function (obj, tagsString) {
  79087. if (!Tags.HasTags(obj)) {
  79088. return;
  79089. }
  79090. var tags = tagsString.split(" ");
  79091. for (var t in tags) {
  79092. Tags._RemoveTagFrom(obj, tags[t]);
  79093. }
  79094. };
  79095. /**
  79096. * @hidden
  79097. */
  79098. Tags._RemoveTagFrom = function (obj, tag) {
  79099. delete obj._tags[tag];
  79100. };
  79101. /**
  79102. * Defines if tags hosted on an object match a given query
  79103. * @param obj defines the object to use
  79104. * @param tagsQuery defines the tag query
  79105. * @returns a boolean
  79106. */
  79107. Tags.MatchesQuery = function (obj, tagsQuery) {
  79108. if (tagsQuery === undefined) {
  79109. return true;
  79110. }
  79111. if (tagsQuery === "") {
  79112. return Tags.HasTags(obj);
  79113. }
  79114. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  79115. };
  79116. return Tags;
  79117. }());
  79118. BABYLON.Tags = Tags;
  79119. })(BABYLON || (BABYLON = {}));
  79120. //# sourceMappingURL=babylon.tags.js.map
  79121. var BABYLON;
  79122. (function (BABYLON) {
  79123. /**
  79124. * Class used to evalaute queries containing `and` and `or` operators
  79125. */
  79126. var AndOrNotEvaluator = /** @class */ (function () {
  79127. function AndOrNotEvaluator() {
  79128. }
  79129. /**
  79130. * Evaluate a query
  79131. * @param query defines the query to evaluate
  79132. * @param evaluateCallback defines the callback used to filter result
  79133. * @returns true if the query matches
  79134. */
  79135. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  79136. if (!query.match(/\([^\(\)]*\)/g)) {
  79137. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  79138. }
  79139. else {
  79140. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  79141. // remove parenthesis
  79142. r = r.slice(1, r.length - 1);
  79143. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  79144. });
  79145. }
  79146. if (query === "true") {
  79147. return true;
  79148. }
  79149. if (query === "false") {
  79150. return false;
  79151. }
  79152. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  79153. };
  79154. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  79155. evaluateCallback = evaluateCallback || (function (r) {
  79156. return r === "true" ? true : false;
  79157. });
  79158. var result;
  79159. var or = parenthesisContent.split("||");
  79160. for (var i in or) {
  79161. if (or.hasOwnProperty(i)) {
  79162. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  79163. var and = ori.split("&&");
  79164. if (and.length > 1) {
  79165. for (var j = 0; j < and.length; ++j) {
  79166. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  79167. if (andj !== "true" && andj !== "false") {
  79168. if (andj[0] === "!") {
  79169. result = !evaluateCallback(andj.substring(1));
  79170. }
  79171. else {
  79172. result = evaluateCallback(andj);
  79173. }
  79174. }
  79175. else {
  79176. result = andj === "true" ? true : false;
  79177. }
  79178. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  79179. ori = "false";
  79180. break;
  79181. }
  79182. }
  79183. }
  79184. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  79185. result = true;
  79186. break;
  79187. }
  79188. // result equals false (or undefined)
  79189. if (ori !== "true" && ori !== "false") {
  79190. if (ori[0] === "!") {
  79191. result = !evaluateCallback(ori.substring(1));
  79192. }
  79193. else {
  79194. result = evaluateCallback(ori);
  79195. }
  79196. }
  79197. else {
  79198. result = ori === "true" ? true : false;
  79199. }
  79200. }
  79201. }
  79202. // the whole parenthesis scope is replaced by 'true' or 'false'
  79203. return result ? "true" : "false";
  79204. };
  79205. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  79206. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  79207. // remove whitespaces
  79208. r = r.replace(/[\s]/g, function () { return ""; });
  79209. return r.length % 2 ? "!" : "";
  79210. });
  79211. booleanString = booleanString.trim();
  79212. if (booleanString === "!true") {
  79213. booleanString = "false";
  79214. }
  79215. else if (booleanString === "!false") {
  79216. booleanString = "true";
  79217. }
  79218. return booleanString;
  79219. };
  79220. return AndOrNotEvaluator;
  79221. }());
  79222. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  79223. })(BABYLON || (BABYLON = {}));
  79224. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  79225. var BABYLON;
  79226. (function (BABYLON) {
  79227. // Sets the default offline provider to Babylon.js
  79228. BABYLON.Engine.OfflineProviderFactory = function (urlToScene, callbackManifestChecked, disableManifestCheck) {
  79229. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79230. return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
  79231. };
  79232. /**
  79233. * Class used to enable access to IndexedDB
  79234. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  79235. */
  79236. var Database = /** @class */ (function () {
  79237. /**
  79238. * Creates a new Database
  79239. * @param urlToScene defines the url to load the scene
  79240. * @param callbackManifestChecked defines the callback to use when manifest is checked
  79241. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  79242. */
  79243. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  79244. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79245. var _this = this;
  79246. // Handling various flavors of prefixed version of IndexedDB
  79247. this._idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  79248. this._callbackManifestChecked = callbackManifestChecked;
  79249. this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  79250. this._db = null;
  79251. this._enableSceneOffline = false;
  79252. this._enableTexturesOffline = false;
  79253. this._manifestVersionFound = 0;
  79254. this._mustUpdateRessources = false;
  79255. this._hasReachedQuota = false;
  79256. if (!Database.IDBStorageEnabled) {
  79257. this._callbackManifestChecked(true);
  79258. }
  79259. else {
  79260. if (disableManifestCheck) {
  79261. this._enableSceneOffline = true;
  79262. this._enableTexturesOffline = true;
  79263. this._manifestVersionFound = 1;
  79264. BABYLON.Tools.SetImmediate(function () {
  79265. _this._callbackManifestChecked(true);
  79266. });
  79267. }
  79268. else {
  79269. this._checkManifestFile();
  79270. }
  79271. }
  79272. }
  79273. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  79274. /**
  79275. * Gets a boolean indicating if scene must be saved in the database
  79276. */
  79277. get: function () {
  79278. return this._enableSceneOffline;
  79279. },
  79280. enumerable: true,
  79281. configurable: true
  79282. });
  79283. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  79284. /**
  79285. * Gets a boolean indicating if textures must be saved in the database
  79286. */
  79287. get: function () {
  79288. return this._enableTexturesOffline;
  79289. },
  79290. enumerable: true,
  79291. configurable: true
  79292. });
  79293. Database.prototype._checkManifestFile = function () {
  79294. var _this = this;
  79295. var noManifestFile = function () {
  79296. _this._enableSceneOffline = false;
  79297. _this._enableTexturesOffline = false;
  79298. _this._callbackManifestChecked(false);
  79299. };
  79300. var timeStampUsed = false;
  79301. var manifestURL = this._currentSceneUrl + ".manifest";
  79302. var xhr = new XMLHttpRequest();
  79303. if (navigator.onLine) {
  79304. // Adding a timestamp to by-pass browsers' cache
  79305. timeStampUsed = true;
  79306. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  79307. }
  79308. xhr.open("GET", manifestURL, true);
  79309. xhr.addEventListener("load", function () {
  79310. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79311. try {
  79312. var manifestFile = JSON.parse(xhr.response);
  79313. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  79314. _this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database.IsUASupportingBlobStorage;
  79315. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  79316. _this._manifestVersionFound = manifestFile.version;
  79317. }
  79318. if (_this._callbackManifestChecked) {
  79319. _this._callbackManifestChecked(true);
  79320. }
  79321. }
  79322. catch (ex) {
  79323. noManifestFile();
  79324. }
  79325. }
  79326. else {
  79327. noManifestFile();
  79328. }
  79329. }, false);
  79330. xhr.addEventListener("error", function (event) {
  79331. if (timeStampUsed) {
  79332. timeStampUsed = false;
  79333. // Let's retry without the timeStamp
  79334. // It could fail when coupled with HTML5 Offline API
  79335. var retryManifestURL = _this._currentSceneUrl + ".manifest";
  79336. xhr.open("GET", retryManifestURL, true);
  79337. xhr.send();
  79338. }
  79339. else {
  79340. noManifestFile();
  79341. }
  79342. }, false);
  79343. try {
  79344. xhr.send();
  79345. }
  79346. catch (ex) {
  79347. BABYLON.Tools.Error("Error on XHR send request.");
  79348. this._callbackManifestChecked(false);
  79349. }
  79350. };
  79351. /**
  79352. * Open the database and make it available
  79353. * @param successCallback defines the callback to call on success
  79354. * @param errorCallback defines the callback to call on error
  79355. */
  79356. Database.prototype.open = function (successCallback, errorCallback) {
  79357. var _this = this;
  79358. var handleError = function () {
  79359. _this._isSupported = false;
  79360. if (errorCallback) {
  79361. errorCallback();
  79362. }
  79363. };
  79364. if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  79365. // Your browser doesn't support IndexedDB
  79366. this._isSupported = false;
  79367. if (errorCallback) {
  79368. errorCallback();
  79369. }
  79370. }
  79371. else {
  79372. // If the DB hasn't been opened or created yet
  79373. if (!this._db) {
  79374. this._hasReachedQuota = false;
  79375. this._isSupported = true;
  79376. var request = this._idbFactory.open("babylonjs", 1);
  79377. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  79378. request.onerror = function (event) {
  79379. handleError();
  79380. };
  79381. // executes when a version change transaction cannot complete due to other active transactions
  79382. request.onblocked = function (event) {
  79383. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  79384. handleError();
  79385. };
  79386. // DB has been opened successfully
  79387. request.onsuccess = function (event) {
  79388. _this._db = request.result;
  79389. successCallback();
  79390. };
  79391. // Initialization of the DB. Creating Scenes & Textures stores
  79392. request.onupgradeneeded = function (event) {
  79393. _this._db = (event.target).result;
  79394. if (_this._db) {
  79395. try {
  79396. _this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  79397. _this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
  79398. _this._db.createObjectStore("textures", { keyPath: "textureUrl" });
  79399. }
  79400. catch (ex) {
  79401. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  79402. handleError();
  79403. }
  79404. }
  79405. };
  79406. }
  79407. // DB has already been created and opened
  79408. else {
  79409. if (successCallback) {
  79410. successCallback();
  79411. }
  79412. }
  79413. }
  79414. };
  79415. /**
  79416. * Loads an image from the database
  79417. * @param url defines the url to load from
  79418. * @param image defines the target DOM image
  79419. */
  79420. Database.prototype.loadImage = function (url, image) {
  79421. var _this = this;
  79422. var completeURL = Database._ReturnFullUrlLocation(url);
  79423. var saveAndLoadImage = function () {
  79424. if (!_this._hasReachedQuota && _this._db !== null) {
  79425. // the texture is not yet in the DB, let's try to save it
  79426. _this._saveImageIntoDBAsync(completeURL, image);
  79427. }
  79428. // If the texture is not in the DB and we've reached the DB quota limit
  79429. // let's load it directly from the web
  79430. else {
  79431. image.src = url;
  79432. }
  79433. };
  79434. if (!this._mustUpdateRessources) {
  79435. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  79436. }
  79437. // First time we're download the images or update requested in the manifest file by a version change
  79438. else {
  79439. saveAndLoadImage();
  79440. }
  79441. };
  79442. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  79443. if (this._isSupported && this._db !== null) {
  79444. var texture;
  79445. var transaction = this._db.transaction(["textures"]);
  79446. transaction.onabort = function (event) {
  79447. image.src = url;
  79448. };
  79449. transaction.oncomplete = function (event) {
  79450. var blobTextureURL;
  79451. if (texture) {
  79452. var URL = window.URL || window.webkitURL;
  79453. blobTextureURL = URL.createObjectURL(texture.data);
  79454. image.onerror = function () {
  79455. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  79456. image.src = url;
  79457. };
  79458. image.src = blobTextureURL;
  79459. }
  79460. else {
  79461. notInDBCallback();
  79462. }
  79463. };
  79464. var getRequest = transaction.objectStore("textures").get(url);
  79465. getRequest.onsuccess = function (event) {
  79466. texture = (event.target).result;
  79467. };
  79468. getRequest.onerror = function (event) {
  79469. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  79470. image.src = url;
  79471. };
  79472. }
  79473. else {
  79474. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79475. image.src = url;
  79476. }
  79477. };
  79478. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  79479. var _this = this;
  79480. if (this._isSupported) {
  79481. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  79482. var generateBlobUrl = function () {
  79483. var blobTextureURL;
  79484. if (blob) {
  79485. var URL = window.URL || window.webkitURL;
  79486. try {
  79487. blobTextureURL = URL.createObjectURL(blob);
  79488. }
  79489. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  79490. catch (ex) {
  79491. blobTextureURL = URL.createObjectURL(blob);
  79492. }
  79493. }
  79494. if (blobTextureURL) {
  79495. image.src = blobTextureURL;
  79496. }
  79497. };
  79498. if (Database.IsUASupportingBlobStorage) { // Create XHR
  79499. var xhr = new XMLHttpRequest(), blob;
  79500. xhr.open("GET", url, true);
  79501. xhr.responseType = "blob";
  79502. xhr.addEventListener("load", function () {
  79503. if (xhr.status === 200 && _this._db) {
  79504. // Blob as response (XHR2)
  79505. blob = xhr.response;
  79506. var transaction = _this._db.transaction(["textures"], "readwrite");
  79507. // the transaction could abort because of a QuotaExceededError error
  79508. transaction.onabort = function (event) {
  79509. try {
  79510. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79511. var srcElement = (event.srcElement || event.target);
  79512. var error = srcElement.error;
  79513. if (error && error.name === "QuotaExceededError") {
  79514. _this._hasReachedQuota = true;
  79515. }
  79516. }
  79517. catch (ex) { }
  79518. generateBlobUrl();
  79519. };
  79520. transaction.oncomplete = function (event) {
  79521. generateBlobUrl();
  79522. };
  79523. var newTexture = { textureUrl: url, data: blob };
  79524. try {
  79525. // Put the blob into the dabase
  79526. var addRequest = transaction.objectStore("textures").put(newTexture);
  79527. addRequest.onsuccess = function (event) {
  79528. };
  79529. addRequest.onerror = function (event) {
  79530. generateBlobUrl();
  79531. };
  79532. }
  79533. catch (ex) {
  79534. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  79535. if (ex.code === 25) {
  79536. Database.IsUASupportingBlobStorage = false;
  79537. _this._enableTexturesOffline = false;
  79538. }
  79539. image.src = url;
  79540. }
  79541. }
  79542. else {
  79543. image.src = url;
  79544. }
  79545. }, false);
  79546. xhr.addEventListener("error", function (event) {
  79547. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  79548. image.src = url;
  79549. }, false);
  79550. xhr.send();
  79551. }
  79552. else {
  79553. image.src = url;
  79554. }
  79555. }
  79556. else {
  79557. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79558. image.src = url;
  79559. }
  79560. };
  79561. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  79562. var _this = this;
  79563. var updateVersion = function () {
  79564. // the version is not yet in the DB or we need to update it
  79565. _this._saveVersionIntoDBAsync(url, versionLoaded);
  79566. };
  79567. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  79568. };
  79569. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  79570. var _this = this;
  79571. if (this._isSupported && this._db) {
  79572. var version;
  79573. try {
  79574. var transaction = this._db.transaction(["versions"]);
  79575. transaction.oncomplete = function (event) {
  79576. if (version) {
  79577. // If the version in the JSON file is different from the version in DB
  79578. if (_this._manifestVersionFound !== version.data) {
  79579. _this._mustUpdateRessources = true;
  79580. updateInDBCallback();
  79581. }
  79582. else {
  79583. callback(version.data);
  79584. }
  79585. }
  79586. // version was not found in DB
  79587. else {
  79588. _this._mustUpdateRessources = true;
  79589. updateInDBCallback();
  79590. }
  79591. };
  79592. transaction.onabort = function (event) {
  79593. callback(-1);
  79594. };
  79595. var getRequest = transaction.objectStore("versions").get(url);
  79596. getRequest.onsuccess = function (event) {
  79597. version = (event.target).result;
  79598. };
  79599. getRequest.onerror = function (event) {
  79600. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  79601. callback(-1);
  79602. };
  79603. }
  79604. catch (ex) {
  79605. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  79606. callback(-1);
  79607. }
  79608. }
  79609. else {
  79610. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79611. callback(-1);
  79612. }
  79613. };
  79614. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  79615. var _this = this;
  79616. if (this._isSupported && !this._hasReachedQuota && this._db) {
  79617. try {
  79618. // Open a transaction to the database
  79619. var transaction = this._db.transaction(["versions"], "readwrite");
  79620. // the transaction could abort because of a QuotaExceededError error
  79621. transaction.onabort = function (event) {
  79622. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79623. var error = event.srcElement['error'];
  79624. if (error && error.name === "QuotaExceededError") {
  79625. _this._hasReachedQuota = true;
  79626. }
  79627. }
  79628. catch (ex) { }
  79629. callback(-1);
  79630. };
  79631. transaction.oncomplete = function (event) {
  79632. callback(_this._manifestVersionFound);
  79633. };
  79634. var newVersion = { sceneUrl: url, data: this._manifestVersionFound };
  79635. // Put the scene into the database
  79636. var addRequest = transaction.objectStore("versions").put(newVersion);
  79637. addRequest.onsuccess = function (event) {
  79638. };
  79639. addRequest.onerror = function (event) {
  79640. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  79641. };
  79642. }
  79643. catch (ex) {
  79644. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  79645. callback(-1);
  79646. }
  79647. }
  79648. else {
  79649. callback(-1);
  79650. }
  79651. };
  79652. /**
  79653. * Loads a file from database
  79654. * @param url defines the URL to load from
  79655. * @param sceneLoaded defines a callback to call on success
  79656. * @param progressCallBack defines a callback to call when progress changed
  79657. * @param errorCallback defines a callback to call on error
  79658. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  79659. */
  79660. Database.prototype.loadFile = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  79661. var _this = this;
  79662. var completeUrl = Database._ReturnFullUrlLocation(url);
  79663. var saveAndLoadFile = function () {
  79664. // the scene is not yet in the DB, let's try to save it
  79665. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79666. };
  79667. this._checkVersionFromDB(completeUrl, function (version) {
  79668. if (version !== -1) {
  79669. if (!_this._mustUpdateRessources) {
  79670. _this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  79671. }
  79672. else {
  79673. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79674. }
  79675. }
  79676. else {
  79677. if (errorCallback) {
  79678. errorCallback();
  79679. }
  79680. }
  79681. });
  79682. };
  79683. Database.prototype._loadFileAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  79684. if (this._isSupported && this._db) {
  79685. var targetStore;
  79686. if (url.indexOf(".babylon") !== -1) {
  79687. targetStore = "scenes";
  79688. }
  79689. else {
  79690. targetStore = "textures";
  79691. }
  79692. var file;
  79693. var transaction = this._db.transaction([targetStore]);
  79694. transaction.oncomplete = function (event) {
  79695. if (file) {
  79696. callback(file.data);
  79697. }
  79698. // file was not found in DB
  79699. else {
  79700. notInDBCallback();
  79701. }
  79702. };
  79703. transaction.onabort = function (event) {
  79704. notInDBCallback();
  79705. };
  79706. var getRequest = transaction.objectStore(targetStore).get(url);
  79707. getRequest.onsuccess = function (event) {
  79708. file = (event.target).result;
  79709. };
  79710. getRequest.onerror = function (event) {
  79711. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  79712. notInDBCallback();
  79713. };
  79714. }
  79715. else {
  79716. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79717. callback();
  79718. }
  79719. };
  79720. Database.prototype._saveFileAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  79721. var _this = this;
  79722. if (this._isSupported) {
  79723. var targetStore;
  79724. if (url.indexOf(".babylon") !== -1) {
  79725. targetStore = "scenes";
  79726. }
  79727. else {
  79728. targetStore = "textures";
  79729. }
  79730. // Create XHR
  79731. var xhr = new XMLHttpRequest();
  79732. var fileData;
  79733. xhr.open("GET", url + "?" + Date.now(), true);
  79734. if (useArrayBuffer) {
  79735. xhr.responseType = "arraybuffer";
  79736. }
  79737. if (progressCallback) {
  79738. xhr.onprogress = progressCallback;
  79739. }
  79740. xhr.addEventListener("load", function () {
  79741. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  79742. // Blob as response (XHR2)
  79743. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  79744. if (!_this._hasReachedQuota && _this._db) {
  79745. // Open a transaction to the database
  79746. var transaction = _this._db.transaction([targetStore], "readwrite");
  79747. // the transaction could abort because of a QuotaExceededError error
  79748. transaction.onabort = function (event) {
  79749. try {
  79750. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79751. var error = event.srcElement['error'];
  79752. if (error && error.name === "QuotaExceededError") {
  79753. _this._hasReachedQuota = true;
  79754. }
  79755. }
  79756. catch (ex) { }
  79757. callback(fileData);
  79758. };
  79759. transaction.oncomplete = function (event) {
  79760. callback(fileData);
  79761. };
  79762. var newFile;
  79763. if (targetStore === "scenes") {
  79764. newFile = { sceneUrl: url, data: fileData, version: _this._manifestVersionFound };
  79765. }
  79766. else {
  79767. newFile = { textureUrl: url, data: fileData };
  79768. }
  79769. try {
  79770. // Put the scene into the database
  79771. var addRequest = transaction.objectStore(targetStore).put(newFile);
  79772. addRequest.onsuccess = function (event) {
  79773. };
  79774. addRequest.onerror = function (event) {
  79775. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  79776. };
  79777. }
  79778. catch (ex) {
  79779. callback(fileData);
  79780. }
  79781. }
  79782. else {
  79783. callback(fileData);
  79784. }
  79785. }
  79786. else {
  79787. if (xhr.status >= 400 && errorCallback) {
  79788. errorCallback(xhr);
  79789. }
  79790. else {
  79791. callback();
  79792. }
  79793. }
  79794. }, false);
  79795. xhr.addEventListener("error", function (event) {
  79796. BABYLON.Tools.Error("error on XHR request.");
  79797. callback();
  79798. }, false);
  79799. xhr.send();
  79800. }
  79801. else {
  79802. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open.");
  79803. callback();
  79804. }
  79805. };
  79806. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  79807. Database.IsUASupportingBlobStorage = true;
  79808. /**
  79809. * Gets a boolean indicating if Database storate is enabled (off by default)
  79810. */
  79811. Database.IDBStorageEnabled = false;
  79812. Database._ParseURL = function (url) {
  79813. var a = document.createElement('a');
  79814. a.href = url;
  79815. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  79816. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  79817. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  79818. return absLocation;
  79819. };
  79820. Database._ReturnFullUrlLocation = function (url) {
  79821. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  79822. return (Database._ParseURL(window.location.href) + url);
  79823. }
  79824. else {
  79825. return url;
  79826. }
  79827. };
  79828. return Database;
  79829. }());
  79830. BABYLON.Database = Database;
  79831. })(BABYLON || (BABYLON = {}));
  79832. //# sourceMappingURL=babylon.database.js.map
  79833. var BABYLON;
  79834. (function (BABYLON) {
  79835. /**
  79836. * This represents all the required information to add a fresnel effect on a material:
  79837. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  79838. */
  79839. var FresnelParameters = /** @class */ (function () {
  79840. function FresnelParameters() {
  79841. this._isEnabled = true;
  79842. /**
  79843. * Define the color used on edges (grazing angle)
  79844. */
  79845. this.leftColor = BABYLON.Color3.White();
  79846. /**
  79847. * Define the color used on center
  79848. */
  79849. this.rightColor = BABYLON.Color3.Black();
  79850. /**
  79851. * Define bias applied to computed fresnel term
  79852. */
  79853. this.bias = 0;
  79854. /**
  79855. * Defined the power exponent applied to fresnel term
  79856. */
  79857. this.power = 1;
  79858. }
  79859. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  79860. /**
  79861. * Define if the fresnel effect is enable or not.
  79862. */
  79863. get: function () {
  79864. return this._isEnabled;
  79865. },
  79866. set: function (value) {
  79867. if (this._isEnabled === value) {
  79868. return;
  79869. }
  79870. this._isEnabled = value;
  79871. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  79872. },
  79873. enumerable: true,
  79874. configurable: true
  79875. });
  79876. /**
  79877. * Clones the current fresnel and its valuues
  79878. * @returns a clone fresnel configuration
  79879. */
  79880. FresnelParameters.prototype.clone = function () {
  79881. var newFresnelParameters = new FresnelParameters();
  79882. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  79883. return newFresnelParameters;
  79884. };
  79885. /**
  79886. * Serializes the current fresnel parameters to a JSON representation.
  79887. * @return the JSON serialization
  79888. */
  79889. FresnelParameters.prototype.serialize = function () {
  79890. var serializationObject = {};
  79891. serializationObject.isEnabled = this.isEnabled;
  79892. serializationObject.leftColor = this.leftColor.asArray();
  79893. serializationObject.rightColor = this.rightColor.asArray();
  79894. serializationObject.bias = this.bias;
  79895. serializationObject.power = this.power;
  79896. return serializationObject;
  79897. };
  79898. /**
  79899. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  79900. * @param parsedFresnelParameters Define the JSON representation
  79901. * @returns the parsed parameters
  79902. */
  79903. FresnelParameters.Parse = function (parsedFresnelParameters) {
  79904. var fresnelParameters = new FresnelParameters();
  79905. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  79906. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  79907. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  79908. fresnelParameters.bias = parsedFresnelParameters.bias;
  79909. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  79910. return fresnelParameters;
  79911. };
  79912. return FresnelParameters;
  79913. }());
  79914. BABYLON.FresnelParameters = FresnelParameters;
  79915. })(BABYLON || (BABYLON = {}));
  79916. //# sourceMappingURL=babylon.fresnelParameters.js.map
  79917. var BABYLON;
  79918. (function (BABYLON) {
  79919. /**
  79920. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79921. * separate meshes. This can be use to improve performances.
  79922. * @see http://doc.babylonjs.com/how_to/multi_materials
  79923. */
  79924. var MultiMaterial = /** @class */ (function (_super) {
  79925. __extends(MultiMaterial, _super);
  79926. /**
  79927. * Instantiates a new Multi Material
  79928. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79929. * separate meshes. This can be use to improve performances.
  79930. * @see http://doc.babylonjs.com/how_to/multi_materials
  79931. * @param name Define the name in the scene
  79932. * @param scene Define the scene the material belongs to
  79933. */
  79934. function MultiMaterial(name, scene) {
  79935. var _this = _super.call(this, name, scene, true) || this;
  79936. scene.multiMaterials.push(_this);
  79937. _this.subMaterials = new Array();
  79938. _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  79939. return _this;
  79940. }
  79941. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  79942. /**
  79943. * Gets or Sets the list of Materials used within the multi material.
  79944. * They need to be ordered according to the submeshes order in the associated mesh
  79945. */
  79946. get: function () {
  79947. return this._subMaterials;
  79948. },
  79949. set: function (value) {
  79950. this._subMaterials = value;
  79951. this._hookArray(value);
  79952. },
  79953. enumerable: true,
  79954. configurable: true
  79955. });
  79956. MultiMaterial.prototype._hookArray = function (array) {
  79957. var _this = this;
  79958. var oldPush = array.push;
  79959. array.push = function () {
  79960. var items = [];
  79961. for (var _i = 0; _i < arguments.length; _i++) {
  79962. items[_i] = arguments[_i];
  79963. }
  79964. var result = oldPush.apply(array, items);
  79965. _this._markAllSubMeshesAsTexturesDirty();
  79966. return result;
  79967. };
  79968. var oldSplice = array.splice;
  79969. array.splice = function (index, deleteCount) {
  79970. var deleted = oldSplice.apply(array, [index, deleteCount]);
  79971. _this._markAllSubMeshesAsTexturesDirty();
  79972. return deleted;
  79973. };
  79974. };
  79975. /**
  79976. * Get one of the submaterial by its index in the submaterials array
  79977. * @param index The index to look the sub material at
  79978. * @returns The Material if the index has been defined
  79979. */
  79980. MultiMaterial.prototype.getSubMaterial = function (index) {
  79981. if (index < 0 || index >= this.subMaterials.length) {
  79982. return this.getScene().defaultMaterial;
  79983. }
  79984. return this.subMaterials[index];
  79985. };
  79986. /**
  79987. * Get the list of active textures for the whole sub materials list.
  79988. * @returns All the textures that will be used during the rendering
  79989. */
  79990. MultiMaterial.prototype.getActiveTextures = function () {
  79991. var _a;
  79992. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  79993. if (subMaterial) {
  79994. return subMaterial.getActiveTextures();
  79995. }
  79996. else {
  79997. return [];
  79998. }
  79999. }));
  80000. };
  80001. /**
  80002. * Gets the current class name of the material e.g. "MultiMaterial"
  80003. * Mainly use in serialization.
  80004. * @returns the class name
  80005. */
  80006. MultiMaterial.prototype.getClassName = function () {
  80007. return "MultiMaterial";
  80008. };
  80009. /**
  80010. * Checks if the material is ready to render the requested sub mesh
  80011. * @param mesh Define the mesh the submesh belongs to
  80012. * @param subMesh Define the sub mesh to look readyness for
  80013. * @param useInstances Define whether or not the material is used with instances
  80014. * @returns true if ready, otherwise false
  80015. */
  80016. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80017. for (var index = 0; index < this.subMaterials.length; index++) {
  80018. var subMaterial = this.subMaterials[index];
  80019. if (subMaterial) {
  80020. if (subMaterial._storeEffectOnSubMeshes) {
  80021. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  80022. return false;
  80023. }
  80024. continue;
  80025. }
  80026. if (!subMaterial.isReady(mesh)) {
  80027. return false;
  80028. }
  80029. }
  80030. }
  80031. return true;
  80032. };
  80033. /**
  80034. * Clones the current material and its related sub materials
  80035. * @param name Define the name of the newly cloned material
  80036. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  80037. * @returns the cloned material
  80038. */
  80039. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  80040. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  80041. for (var index = 0; index < this.subMaterials.length; index++) {
  80042. var subMaterial = null;
  80043. var current = this.subMaterials[index];
  80044. if (cloneChildren && current) {
  80045. subMaterial = current.clone(name + "-" + current.name);
  80046. }
  80047. else {
  80048. subMaterial = this.subMaterials[index];
  80049. }
  80050. newMultiMaterial.subMaterials.push(subMaterial);
  80051. }
  80052. return newMultiMaterial;
  80053. };
  80054. /**
  80055. * Serializes the materials into a JSON representation.
  80056. * @returns the JSON representation
  80057. */
  80058. MultiMaterial.prototype.serialize = function () {
  80059. var serializationObject = {};
  80060. serializationObject.name = this.name;
  80061. serializationObject.id = this.id;
  80062. if (BABYLON.Tags) {
  80063. serializationObject.tags = BABYLON.Tags.GetTags(this);
  80064. }
  80065. serializationObject.materials = [];
  80066. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  80067. var subMat = this.subMaterials[matIndex];
  80068. if (subMat) {
  80069. serializationObject.materials.push(subMat.id);
  80070. }
  80071. else {
  80072. serializationObject.materials.push(null);
  80073. }
  80074. }
  80075. return serializationObject;
  80076. };
  80077. /**
  80078. * Dispose the material and release its associated resources
  80079. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  80080. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  80081. */
  80082. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80083. var scene = this.getScene();
  80084. if (!scene) {
  80085. return;
  80086. }
  80087. var index = scene.multiMaterials.indexOf(this);
  80088. if (index >= 0) {
  80089. scene.multiMaterials.splice(index, 1);
  80090. }
  80091. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  80092. };
  80093. return MultiMaterial;
  80094. }(BABYLON.Material));
  80095. BABYLON.MultiMaterial = MultiMaterial;
  80096. })(BABYLON || (BABYLON = {}));
  80097. //# sourceMappingURL=babylon.multiMaterial.js.map
  80098. var BABYLON;
  80099. (function (BABYLON) {
  80100. /**
  80101. * Manage the touch inputs to control the movement of a free camera.
  80102. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80103. */
  80104. var FreeCameraTouchInput = /** @class */ (function () {
  80105. function FreeCameraTouchInput() {
  80106. /**
  80107. * Defines the touch sensibility for rotation.
  80108. * The higher the faster.
  80109. */
  80110. this.touchAngularSensibility = 200000.0;
  80111. /**
  80112. * Defines the touch sensibility for move.
  80113. * The higher the faster.
  80114. */
  80115. this.touchMoveSensibility = 250.0;
  80116. this._offsetX = null;
  80117. this._offsetY = null;
  80118. this._pointerPressed = new Array();
  80119. }
  80120. /**
  80121. * Attach the input controls to a specific dom element to get the input from.
  80122. * @param element Defines the element the controls should be listened from
  80123. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80124. */
  80125. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  80126. var _this = this;
  80127. var previousPosition = null;
  80128. if (this._pointerInput === undefined) {
  80129. this._onLostFocus = function (evt) {
  80130. _this._offsetX = null;
  80131. _this._offsetY = null;
  80132. };
  80133. this._pointerInput = function (p, s) {
  80134. var evt = p.event;
  80135. if (evt.pointerType === "mouse") {
  80136. return;
  80137. }
  80138. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80139. if (!noPreventDefault) {
  80140. evt.preventDefault();
  80141. }
  80142. _this._pointerPressed.push(evt.pointerId);
  80143. if (_this._pointerPressed.length !== 1) {
  80144. return;
  80145. }
  80146. previousPosition = {
  80147. x: evt.clientX,
  80148. y: evt.clientY
  80149. };
  80150. }
  80151. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  80152. if (!noPreventDefault) {
  80153. evt.preventDefault();
  80154. }
  80155. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80156. if (index === -1) {
  80157. return;
  80158. }
  80159. _this._pointerPressed.splice(index, 1);
  80160. if (index != 0) {
  80161. return;
  80162. }
  80163. previousPosition = null;
  80164. _this._offsetX = null;
  80165. _this._offsetY = null;
  80166. }
  80167. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  80168. if (!noPreventDefault) {
  80169. evt.preventDefault();
  80170. }
  80171. if (!previousPosition) {
  80172. return;
  80173. }
  80174. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80175. if (index != 0) {
  80176. return;
  80177. }
  80178. _this._offsetX = evt.clientX - previousPosition.x;
  80179. _this._offsetY = -(evt.clientY - previousPosition.y);
  80180. }
  80181. };
  80182. }
  80183. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  80184. if (this._onLostFocus) {
  80185. element.addEventListener("blur", this._onLostFocus);
  80186. }
  80187. };
  80188. /**
  80189. * Detach the current controls from the specified dom element.
  80190. * @param element Defines the element to stop listening the inputs from
  80191. */
  80192. FreeCameraTouchInput.prototype.detachControl = function (element) {
  80193. if (this._pointerInput && element) {
  80194. if (this._observer) {
  80195. this.camera.getScene().onPointerObservable.remove(this._observer);
  80196. this._observer = null;
  80197. }
  80198. if (this._onLostFocus) {
  80199. element.removeEventListener("blur", this._onLostFocus);
  80200. this._onLostFocus = null;
  80201. }
  80202. this._pointerPressed = [];
  80203. this._offsetX = null;
  80204. this._offsetY = null;
  80205. }
  80206. };
  80207. /**
  80208. * Update the current camera state depending on the inputs that have been used this frame.
  80209. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80210. */
  80211. FreeCameraTouchInput.prototype.checkInputs = function () {
  80212. if (this._offsetX && this._offsetY) {
  80213. var camera = this.camera;
  80214. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  80215. if (this._pointerPressed.length > 1) {
  80216. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  80217. }
  80218. else {
  80219. var speed = camera._computeLocalCameraSpeed();
  80220. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  80221. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  80222. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  80223. }
  80224. }
  80225. };
  80226. /**
  80227. * Gets the class name of the current intput.
  80228. * @returns the class name
  80229. */
  80230. FreeCameraTouchInput.prototype.getClassName = function () {
  80231. return "FreeCameraTouchInput";
  80232. };
  80233. /**
  80234. * Get the friendly name associated with the input class.
  80235. * @returns the input friendly name
  80236. */
  80237. FreeCameraTouchInput.prototype.getSimpleName = function () {
  80238. return "touch";
  80239. };
  80240. __decorate([
  80241. BABYLON.serialize()
  80242. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  80243. __decorate([
  80244. BABYLON.serialize()
  80245. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  80246. return FreeCameraTouchInput;
  80247. }());
  80248. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  80249. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  80250. })(BABYLON || (BABYLON = {}));
  80251. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  80252. var BABYLON;
  80253. (function (BABYLON) {
  80254. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  80255. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  80256. });
  80257. /**
  80258. * This represents a FPS type of camera controlled by touch.
  80259. * This is like a universal camera minus the Gamepad controls.
  80260. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80261. */
  80262. var TouchCamera = /** @class */ (function (_super) {
  80263. __extends(TouchCamera, _super);
  80264. /**
  80265. * Instantiates a new touch camera.
  80266. * This represents a FPS type of camera controlled by touch.
  80267. * This is like a universal camera minus the Gamepad controls.
  80268. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80269. * @param name Define the name of the camera in the scene
  80270. * @param position Define the start position of the camera in the scene
  80271. * @param scene Define the scene the camera belongs to
  80272. */
  80273. function TouchCamera(name, position, scene) {
  80274. var _this = _super.call(this, name, position, scene) || this;
  80275. _this.inputs.addTouch();
  80276. _this._setupInputs();
  80277. return _this;
  80278. }
  80279. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  80280. /**
  80281. * Defines the touch sensibility for rotation.
  80282. * The higher the faster.
  80283. */
  80284. get: function () {
  80285. var touch = this.inputs.attached["touch"];
  80286. if (touch) {
  80287. return touch.touchAngularSensibility;
  80288. }
  80289. return 0;
  80290. },
  80291. set: function (value) {
  80292. var touch = this.inputs.attached["touch"];
  80293. if (touch) {
  80294. touch.touchAngularSensibility = value;
  80295. }
  80296. },
  80297. enumerable: true,
  80298. configurable: true
  80299. });
  80300. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  80301. /**
  80302. * Defines the touch sensibility for move.
  80303. * The higher the faster.
  80304. */
  80305. get: function () {
  80306. var touch = this.inputs.attached["touch"];
  80307. if (touch) {
  80308. return touch.touchMoveSensibility;
  80309. }
  80310. return 0;
  80311. },
  80312. set: function (value) {
  80313. var touch = this.inputs.attached["touch"];
  80314. if (touch) {
  80315. touch.touchMoveSensibility = value;
  80316. }
  80317. },
  80318. enumerable: true,
  80319. configurable: true
  80320. });
  80321. /**
  80322. * Gets the current object class name.
  80323. * @return the class name
  80324. */
  80325. TouchCamera.prototype.getClassName = function () {
  80326. return "TouchCamera";
  80327. };
  80328. /** @hidden */
  80329. TouchCamera.prototype._setupInputs = function () {
  80330. var mouse = this.inputs.attached["mouse"];
  80331. if (mouse) {
  80332. mouse.touchEnabled = false;
  80333. }
  80334. };
  80335. return TouchCamera;
  80336. }(BABYLON.FreeCamera));
  80337. BABYLON.TouchCamera = TouchCamera;
  80338. })(BABYLON || (BABYLON = {}));
  80339. //# sourceMappingURL=babylon.touchCamera.js.map
  80340. var BABYLON;
  80341. (function (BABYLON) {
  80342. /**
  80343. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80344. * This is the base class of any Procedural texture and contains most of the shareable code.
  80345. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80346. */
  80347. var ProceduralTexture = /** @class */ (function (_super) {
  80348. __extends(ProceduralTexture, _super);
  80349. /**
  80350. * Instantiates a new procedural texture.
  80351. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80352. * This is the base class of any Procedural texture and contains most of the shareable code.
  80353. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80354. * @param name Define the name of the texture
  80355. * @param size Define the size of the texture to create
  80356. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  80357. * @param scene Define the scene the texture belongs to
  80358. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80359. * @param generateMipMaps Define if the texture should creates mip maps or not
  80360. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  80361. */
  80362. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  80363. if (fallbackTexture === void 0) { fallbackTexture = null; }
  80364. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80365. if (isCube === void 0) { isCube = false; }
  80366. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  80367. _this.isCube = isCube;
  80368. /**
  80369. * Define if the texture is enabled or not (disabled texture will not render)
  80370. */
  80371. _this.isEnabled = true;
  80372. /**
  80373. * Define if the texture must be cleared before rendering (default is true)
  80374. */
  80375. _this.autoClear = true;
  80376. /**
  80377. * Event raised when the texture is generated
  80378. */
  80379. _this.onGeneratedObservable = new BABYLON.Observable();
  80380. /** @hidden */
  80381. _this._textures = {};
  80382. _this._currentRefreshId = -1;
  80383. _this._refreshRate = 1;
  80384. _this._vertexBuffers = {};
  80385. _this._uniforms = new Array();
  80386. _this._samplers = new Array();
  80387. _this._floats = {};
  80388. _this._ints = {};
  80389. _this._floatsArrays = {};
  80390. _this._colors3 = {};
  80391. _this._colors4 = {};
  80392. _this._vectors2 = {};
  80393. _this._vectors3 = {};
  80394. _this._matrices = {};
  80395. _this._fallbackTextureUsed = false;
  80396. _this._cachedDefines = "";
  80397. _this._contentUpdateId = -1;
  80398. scene = _this.getScene();
  80399. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  80400. if (!component) {
  80401. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  80402. scene._addComponent(component);
  80403. }
  80404. scene.proceduralTextures.push(_this);
  80405. _this._engine = scene.getEngine();
  80406. _this.name = name;
  80407. _this.isRenderTarget = true;
  80408. _this._size = size;
  80409. _this._generateMipMaps = generateMipMaps;
  80410. _this.setFragment(fragment);
  80411. _this._fallbackTexture = fallbackTexture;
  80412. if (isCube) {
  80413. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80414. _this.setFloat("face", 0);
  80415. }
  80416. else {
  80417. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80418. }
  80419. // VBO
  80420. var vertices = [];
  80421. vertices.push(1, 1);
  80422. vertices.push(-1, 1);
  80423. vertices.push(-1, -1);
  80424. vertices.push(1, -1);
  80425. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80426. _this._createIndexBuffer();
  80427. return _this;
  80428. }
  80429. /**
  80430. * The effect that is created when initializing the post process.
  80431. * @returns The created effect corrisponding the the postprocess.
  80432. */
  80433. ProceduralTexture.prototype.getEffect = function () {
  80434. return this._effect;
  80435. };
  80436. /**
  80437. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  80438. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  80439. */
  80440. ProceduralTexture.prototype.getContent = function () {
  80441. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  80442. return this._contentData;
  80443. }
  80444. this._contentData = this.readPixels(0, 0, this._contentData);
  80445. this._contentUpdateId = this._currentRefreshId;
  80446. return this._contentData;
  80447. };
  80448. ProceduralTexture.prototype._createIndexBuffer = function () {
  80449. var engine = this._engine;
  80450. // Indices
  80451. var indices = [];
  80452. indices.push(0);
  80453. indices.push(1);
  80454. indices.push(2);
  80455. indices.push(0);
  80456. indices.push(2);
  80457. indices.push(3);
  80458. this._indexBuffer = engine.createIndexBuffer(indices);
  80459. };
  80460. /** @hidden */
  80461. ProceduralTexture.prototype._rebuild = function () {
  80462. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80463. if (vb) {
  80464. vb._rebuild();
  80465. }
  80466. this._createIndexBuffer();
  80467. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  80468. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  80469. }
  80470. };
  80471. /**
  80472. * Resets the texture in order to recreate its associated resources.
  80473. * This can be called in case of context loss
  80474. */
  80475. ProceduralTexture.prototype.reset = function () {
  80476. if (this._effect === undefined) {
  80477. return;
  80478. }
  80479. var engine = this._engine;
  80480. engine._releaseEffect(this._effect);
  80481. };
  80482. ProceduralTexture.prototype._getDefines = function () {
  80483. return "";
  80484. };
  80485. /**
  80486. * Is the texture ready to be used ? (rendered at least once)
  80487. * @returns true if ready, otherwise, false.
  80488. */
  80489. ProceduralTexture.prototype.isReady = function () {
  80490. var _this = this;
  80491. var engine = this._engine;
  80492. var shaders;
  80493. if (!this._fragment) {
  80494. return false;
  80495. }
  80496. if (this._fallbackTextureUsed) {
  80497. return true;
  80498. }
  80499. var defines = this._getDefines();
  80500. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  80501. return true;
  80502. }
  80503. if (this._fragment.fragmentElement !== undefined) {
  80504. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  80505. }
  80506. else {
  80507. shaders = { vertex: "procedural", fragment: this._fragment };
  80508. }
  80509. this._cachedDefines = defines;
  80510. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  80511. _this.releaseInternalTexture();
  80512. if (_this._fallbackTexture) {
  80513. _this._texture = _this._fallbackTexture._texture;
  80514. if (_this._texture) {
  80515. _this._texture.incrementReferences();
  80516. }
  80517. }
  80518. _this._fallbackTextureUsed = true;
  80519. });
  80520. return this._effect.isReady();
  80521. };
  80522. /**
  80523. * Resets the refresh counter of the texture and start bak from scratch.
  80524. * Could be usefull to regenerate the texture if it is setup to render only once.
  80525. */
  80526. ProceduralTexture.prototype.resetRefreshCounter = function () {
  80527. this._currentRefreshId = -1;
  80528. };
  80529. /**
  80530. * Set the fragment shader to use in order to render the texture.
  80531. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  80532. */
  80533. ProceduralTexture.prototype.setFragment = function (fragment) {
  80534. this._fragment = fragment;
  80535. };
  80536. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  80537. /**
  80538. * Define the refresh rate of the texture or the rendering frequency.
  80539. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  80540. */
  80541. get: function () {
  80542. return this._refreshRate;
  80543. },
  80544. set: function (value) {
  80545. this._refreshRate = value;
  80546. this.resetRefreshCounter();
  80547. },
  80548. enumerable: true,
  80549. configurable: true
  80550. });
  80551. /** @hidden */
  80552. ProceduralTexture.prototype._shouldRender = function () {
  80553. if (!this.isEnabled || !this.isReady() || !this._texture) {
  80554. if (this._texture) {
  80555. this._texture.isReady = false;
  80556. }
  80557. return false;
  80558. }
  80559. if (this._fallbackTextureUsed) {
  80560. return false;
  80561. }
  80562. if (this._currentRefreshId === -1) { // At least render once
  80563. this._currentRefreshId = 1;
  80564. return true;
  80565. }
  80566. if (this.refreshRate === this._currentRefreshId) {
  80567. this._currentRefreshId = 1;
  80568. return true;
  80569. }
  80570. this._currentRefreshId++;
  80571. return false;
  80572. };
  80573. /**
  80574. * Get the size the texture is rendering at.
  80575. * @returns the size (texture is always squared)
  80576. */
  80577. ProceduralTexture.prototype.getRenderSize = function () {
  80578. return this._size;
  80579. };
  80580. /**
  80581. * Resize the texture to new value.
  80582. * @param size Define the new size the texture should have
  80583. * @param generateMipMaps Define whether the new texture should create mip maps
  80584. */
  80585. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  80586. if (this._fallbackTextureUsed) {
  80587. return;
  80588. }
  80589. this.releaseInternalTexture();
  80590. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  80591. // Update properties
  80592. this._size = size;
  80593. this._generateMipMaps = generateMipMaps;
  80594. };
  80595. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  80596. if (this._uniforms.indexOf(uniformName) === -1) {
  80597. this._uniforms.push(uniformName);
  80598. }
  80599. };
  80600. /**
  80601. * Set a texture in the shader program used to render.
  80602. * @param name Define the name of the uniform samplers as defined in the shader
  80603. * @param texture Define the texture to bind to this sampler
  80604. * @return the texture itself allowing "fluent" like uniform updates
  80605. */
  80606. ProceduralTexture.prototype.setTexture = function (name, texture) {
  80607. if (this._samplers.indexOf(name) === -1) {
  80608. this._samplers.push(name);
  80609. }
  80610. this._textures[name] = texture;
  80611. return this;
  80612. };
  80613. /**
  80614. * Set a float in the shader.
  80615. * @param name Define the name of the uniform as defined in the shader
  80616. * @param value Define the value to give to the uniform
  80617. * @return the texture itself allowing "fluent" like uniform updates
  80618. */
  80619. ProceduralTexture.prototype.setFloat = function (name, value) {
  80620. this._checkUniform(name);
  80621. this._floats[name] = value;
  80622. return this;
  80623. };
  80624. /**
  80625. * Set a int in the shader.
  80626. * @param name Define the name of the uniform as defined in the shader
  80627. * @param value Define the value to give to the uniform
  80628. * @return the texture itself allowing "fluent" like uniform updates
  80629. */
  80630. ProceduralTexture.prototype.setInt = function (name, value) {
  80631. this._checkUniform(name);
  80632. this._ints[name] = value;
  80633. return this;
  80634. };
  80635. /**
  80636. * Set an array of floats in the shader.
  80637. * @param name Define the name of the uniform as defined in the shader
  80638. * @param value Define the value to give to the uniform
  80639. * @return the texture itself allowing "fluent" like uniform updates
  80640. */
  80641. ProceduralTexture.prototype.setFloats = function (name, value) {
  80642. this._checkUniform(name);
  80643. this._floatsArrays[name] = value;
  80644. return this;
  80645. };
  80646. /**
  80647. * Set a vec3 in the shader from a Color3.
  80648. * @param name Define the name of the uniform as defined in the shader
  80649. * @param value Define the value to give to the uniform
  80650. * @return the texture itself allowing "fluent" like uniform updates
  80651. */
  80652. ProceduralTexture.prototype.setColor3 = function (name, value) {
  80653. this._checkUniform(name);
  80654. this._colors3[name] = value;
  80655. return this;
  80656. };
  80657. /**
  80658. * Set a vec4 in the shader from a Color4.
  80659. * @param name Define the name of the uniform as defined in the shader
  80660. * @param value Define the value to give to the uniform
  80661. * @return the texture itself allowing "fluent" like uniform updates
  80662. */
  80663. ProceduralTexture.prototype.setColor4 = function (name, value) {
  80664. this._checkUniform(name);
  80665. this._colors4[name] = value;
  80666. return this;
  80667. };
  80668. /**
  80669. * Set a vec2 in the shader from a Vector2.
  80670. * @param name Define the name of the uniform as defined in the shader
  80671. * @param value Define the value to give to the uniform
  80672. * @return the texture itself allowing "fluent" like uniform updates
  80673. */
  80674. ProceduralTexture.prototype.setVector2 = function (name, value) {
  80675. this._checkUniform(name);
  80676. this._vectors2[name] = value;
  80677. return this;
  80678. };
  80679. /**
  80680. * Set a vec3 in the shader from a Vector3.
  80681. * @param name Define the name of the uniform as defined in the shader
  80682. * @param value Define the value to give to the uniform
  80683. * @return the texture itself allowing "fluent" like uniform updates
  80684. */
  80685. ProceduralTexture.prototype.setVector3 = function (name, value) {
  80686. this._checkUniform(name);
  80687. this._vectors3[name] = value;
  80688. return this;
  80689. };
  80690. /**
  80691. * Set a mat4 in the shader from a MAtrix.
  80692. * @param name Define the name of the uniform as defined in the shader
  80693. * @param value Define the value to give to the uniform
  80694. * @return the texture itself allowing "fluent" like uniform updates
  80695. */
  80696. ProceduralTexture.prototype.setMatrix = function (name, value) {
  80697. this._checkUniform(name);
  80698. this._matrices[name] = value;
  80699. return this;
  80700. };
  80701. /**
  80702. * Render the texture to its associated render target.
  80703. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80704. */
  80705. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80706. var scene = this.getScene();
  80707. if (!scene) {
  80708. return;
  80709. }
  80710. var engine = this._engine;
  80711. // Render
  80712. engine.enableEffect(this._effect);
  80713. engine.setState(false);
  80714. // Texture
  80715. for (var name in this._textures) {
  80716. this._effect.setTexture(name, this._textures[name]);
  80717. }
  80718. // Float
  80719. for (name in this._ints) {
  80720. this._effect.setInt(name, this._ints[name]);
  80721. }
  80722. // Float
  80723. for (name in this._floats) {
  80724. this._effect.setFloat(name, this._floats[name]);
  80725. }
  80726. // Floats
  80727. for (name in this._floatsArrays) {
  80728. this._effect.setArray(name, this._floatsArrays[name]);
  80729. }
  80730. // Color3
  80731. for (name in this._colors3) {
  80732. this._effect.setColor3(name, this._colors3[name]);
  80733. }
  80734. // Color4
  80735. for (name in this._colors4) {
  80736. var color = this._colors4[name];
  80737. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  80738. }
  80739. // Vector2
  80740. for (name in this._vectors2) {
  80741. this._effect.setVector2(name, this._vectors2[name]);
  80742. }
  80743. // Vector3
  80744. for (name in this._vectors3) {
  80745. this._effect.setVector3(name, this._vectors3[name]);
  80746. }
  80747. // Matrix
  80748. for (name in this._matrices) {
  80749. this._effect.setMatrix(name, this._matrices[name]);
  80750. }
  80751. if (!this._texture) {
  80752. return;
  80753. }
  80754. if (this.isCube) {
  80755. for (var face = 0; face < 6; face++) {
  80756. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  80757. // VBOs
  80758. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80759. this._effect.setFloat("face", face);
  80760. // Clear
  80761. if (this.autoClear) {
  80762. engine.clear(scene.clearColor, true, false, false);
  80763. }
  80764. // Draw order
  80765. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80766. // Mipmaps
  80767. if (face === 5) {
  80768. engine.generateMipMapsForCubemap(this._texture);
  80769. }
  80770. }
  80771. }
  80772. else {
  80773. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  80774. // VBOs
  80775. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80776. // Clear
  80777. if (this.autoClear) {
  80778. engine.clear(scene.clearColor, true, false, false);
  80779. }
  80780. // Draw order
  80781. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80782. }
  80783. // Unbind
  80784. engine.unBindFramebuffer(this._texture, this.isCube);
  80785. if (this.onGenerated) {
  80786. this.onGenerated();
  80787. }
  80788. this.onGeneratedObservable.notifyObservers(this);
  80789. };
  80790. /**
  80791. * Clone the texture.
  80792. * @returns the cloned texture
  80793. */
  80794. ProceduralTexture.prototype.clone = function () {
  80795. var textureSize = this.getSize();
  80796. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  80797. // Base texture
  80798. newTexture.hasAlpha = this.hasAlpha;
  80799. newTexture.level = this.level;
  80800. // RenderTarget Texture
  80801. newTexture.coordinatesMode = this.coordinatesMode;
  80802. return newTexture;
  80803. };
  80804. /**
  80805. * Dispose the texture and release its asoociated resources.
  80806. */
  80807. ProceduralTexture.prototype.dispose = function () {
  80808. var scene = this.getScene();
  80809. if (!scene) {
  80810. return;
  80811. }
  80812. var index = scene.proceduralTextures.indexOf(this);
  80813. if (index >= 0) {
  80814. scene.proceduralTextures.splice(index, 1);
  80815. }
  80816. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80817. if (vertexBuffer) {
  80818. vertexBuffer.dispose();
  80819. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80820. }
  80821. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  80822. this._indexBuffer = null;
  80823. }
  80824. _super.prototype.dispose.call(this);
  80825. };
  80826. __decorate([
  80827. BABYLON.serialize()
  80828. ], ProceduralTexture.prototype, "isEnabled", void 0);
  80829. __decorate([
  80830. BABYLON.serialize()
  80831. ], ProceduralTexture.prototype, "autoClear", void 0);
  80832. __decorate([
  80833. BABYLON.serialize()
  80834. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  80835. __decorate([
  80836. BABYLON.serialize()
  80837. ], ProceduralTexture.prototype, "_size", void 0);
  80838. __decorate([
  80839. BABYLON.serialize()
  80840. ], ProceduralTexture.prototype, "refreshRate", null);
  80841. return ProceduralTexture;
  80842. }(BABYLON.Texture));
  80843. BABYLON.ProceduralTexture = ProceduralTexture;
  80844. })(BABYLON || (BABYLON = {}));
  80845. //# sourceMappingURL=babylon.proceduralTexture.js.map
  80846. var BABYLON;
  80847. (function (BABYLON) {
  80848. /**
  80849. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  80850. * in a given scene.
  80851. */
  80852. var ProceduralTextureSceneComponent = /** @class */ (function () {
  80853. /**
  80854. * Creates a new instance of the component for the given scene
  80855. * @param scene Defines the scene to register the component in
  80856. */
  80857. function ProceduralTextureSceneComponent(scene) {
  80858. /**
  80859. * The component name helpfull to identify the component in the list of scene components.
  80860. */
  80861. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  80862. this.scene = scene;
  80863. this.scene.proceduralTextures = new Array();
  80864. scene.layers = new Array();
  80865. }
  80866. /**
  80867. * Registers the component in a given scene
  80868. */
  80869. ProceduralTextureSceneComponent.prototype.register = function () {
  80870. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  80871. };
  80872. /**
  80873. * Rebuilds the elements related to this component in case of
  80874. * context lost for instance.
  80875. */
  80876. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  80877. // Nothing to do here.
  80878. };
  80879. /**
  80880. * Disposes the component and the associated ressources.
  80881. */
  80882. ProceduralTextureSceneComponent.prototype.dispose = function () {
  80883. // Nothing to do here.
  80884. };
  80885. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  80886. if (this.scene.proceduralTexturesEnabled) {
  80887. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80888. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  80889. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  80890. if (proceduralTexture._shouldRender()) {
  80891. proceduralTexture.render();
  80892. }
  80893. }
  80894. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80895. }
  80896. };
  80897. return ProceduralTextureSceneComponent;
  80898. }());
  80899. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  80900. })(BABYLON || (BABYLON = {}));
  80901. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  80902. var BABYLON;
  80903. (function (BABYLON) {
  80904. /**
  80905. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80906. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80907. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80908. */
  80909. var CustomProceduralTexture = /** @class */ (function (_super) {
  80910. __extends(CustomProceduralTexture, _super);
  80911. /**
  80912. * Instantiates a new Custom Procedural Texture.
  80913. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80914. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80915. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80916. * @param name Define the name of the texture
  80917. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  80918. * @param size Define the size of the texture to create
  80919. * @param scene Define the scene the texture belongs to
  80920. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80921. * @param generateMipMaps Define if the texture should creates mip maps or not
  80922. */
  80923. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  80924. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  80925. _this._animate = true;
  80926. _this._time = 0;
  80927. _this._texturePath = texturePath;
  80928. //Try to load json
  80929. _this._loadJson(texturePath);
  80930. _this.refreshRate = 1;
  80931. return _this;
  80932. }
  80933. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  80934. var _this = this;
  80935. var noConfigFile = function () {
  80936. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  80937. try {
  80938. _this.setFragment(_this._texturePath);
  80939. }
  80940. catch (ex) {
  80941. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  80942. }
  80943. };
  80944. var configFileUrl = jsonUrl + "/config.json";
  80945. var xhr = new XMLHttpRequest();
  80946. xhr.open("GET", configFileUrl, true);
  80947. xhr.addEventListener("load", function () {
  80948. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  80949. try {
  80950. _this._config = JSON.parse(xhr.response);
  80951. _this.updateShaderUniforms();
  80952. _this.updateTextures();
  80953. _this.setFragment(_this._texturePath + "/custom");
  80954. _this._animate = _this._config.animate;
  80955. _this.refreshRate = _this._config.refreshrate;
  80956. }
  80957. catch (ex) {
  80958. noConfigFile();
  80959. }
  80960. }
  80961. else {
  80962. noConfigFile();
  80963. }
  80964. }, false);
  80965. xhr.addEventListener("error", function () {
  80966. noConfigFile();
  80967. }, false);
  80968. try {
  80969. xhr.send();
  80970. }
  80971. catch (ex) {
  80972. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  80973. }
  80974. };
  80975. /**
  80976. * Is the texture ready to be used ? (rendered at least once)
  80977. * @returns true if ready, otherwise, false.
  80978. */
  80979. CustomProceduralTexture.prototype.isReady = function () {
  80980. if (!_super.prototype.isReady.call(this)) {
  80981. return false;
  80982. }
  80983. for (var name in this._textures) {
  80984. var texture = this._textures[name];
  80985. if (!texture.isReady()) {
  80986. return false;
  80987. }
  80988. }
  80989. return true;
  80990. };
  80991. /**
  80992. * Render the texture to its associated render target.
  80993. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80994. */
  80995. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80996. var scene = this.getScene();
  80997. if (this._animate && scene) {
  80998. this._time += scene.getAnimationRatio() * 0.03;
  80999. this.updateShaderUniforms();
  81000. }
  81001. _super.prototype.render.call(this, useCameraPostProcess);
  81002. };
  81003. /**
  81004. * Update the list of dependant textures samplers in the shader.
  81005. */
  81006. CustomProceduralTexture.prototype.updateTextures = function () {
  81007. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  81008. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  81009. }
  81010. };
  81011. /**
  81012. * Update the uniform values of the procedural texture in the shader.
  81013. */
  81014. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  81015. if (this._config) {
  81016. for (var j = 0; j < this._config.uniforms.length; j++) {
  81017. var uniform = this._config.uniforms[j];
  81018. switch (uniform.type) {
  81019. case "float":
  81020. this.setFloat(uniform.name, uniform.value);
  81021. break;
  81022. case "color3":
  81023. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  81024. break;
  81025. case "color4":
  81026. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  81027. break;
  81028. case "vector2":
  81029. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  81030. break;
  81031. case "vector3":
  81032. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  81033. break;
  81034. }
  81035. }
  81036. }
  81037. this.setFloat("time", this._time);
  81038. };
  81039. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  81040. /**
  81041. * Define if the texture animates or not.
  81042. */
  81043. get: function () {
  81044. return this._animate;
  81045. },
  81046. set: function (value) {
  81047. this._animate = value;
  81048. },
  81049. enumerable: true,
  81050. configurable: true
  81051. });
  81052. return CustomProceduralTexture;
  81053. }(BABYLON.ProceduralTexture));
  81054. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  81055. })(BABYLON || (BABYLON = {}));
  81056. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  81057. var BABYLON;
  81058. (function (BABYLON) {
  81059. /**
  81060. * Manage the gamepad inputs to control a free camera.
  81061. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81062. */
  81063. var FreeCameraGamepadInput = /** @class */ (function () {
  81064. function FreeCameraGamepadInput() {
  81065. /**
  81066. * Defines the gamepad rotation sensiblity.
  81067. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81068. */
  81069. this.gamepadAngularSensibility = 200;
  81070. /**
  81071. * Defines the gamepad move sensiblity.
  81072. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81073. */
  81074. this.gamepadMoveSensibility = 40;
  81075. this._cameraTransform = BABYLON.Matrix.Identity();
  81076. this._deltaTransform = BABYLON.Vector3.Zero();
  81077. this._vector3 = BABYLON.Vector3.Zero();
  81078. this._vector2 = BABYLON.Vector2.Zero();
  81079. }
  81080. /**
  81081. * Attach the input controls to a specific dom element to get the input from.
  81082. * @param element Defines the element the controls should be listened from
  81083. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81084. */
  81085. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81086. var _this = this;
  81087. var manager = this.camera.getScene().gamepadManager;
  81088. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81089. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81090. // prioritize XBOX gamepads.
  81091. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81092. _this.gamepad = gamepad;
  81093. }
  81094. }
  81095. });
  81096. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81097. if (_this.gamepad === gamepad) {
  81098. _this.gamepad = null;
  81099. }
  81100. });
  81101. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81102. };
  81103. /**
  81104. * Detach the current controls from the specified dom element.
  81105. * @param element Defines the element to stop listening the inputs from
  81106. */
  81107. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  81108. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81109. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81110. this.gamepad = null;
  81111. };
  81112. /**
  81113. * Update the current camera state depending on the inputs that have been used this frame.
  81114. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81115. */
  81116. FreeCameraGamepadInput.prototype.checkInputs = function () {
  81117. if (this.gamepad && this.gamepad.leftStick) {
  81118. var camera = this.camera;
  81119. var LSValues = this.gamepad.leftStick;
  81120. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  81121. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81122. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  81123. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  81124. var RSValues = this.gamepad.rightStick;
  81125. if (RSValues) {
  81126. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  81127. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  81128. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  81129. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  81130. }
  81131. else {
  81132. RSValues = { x: 0, y: 0 };
  81133. }
  81134. if (!camera.rotationQuaternion) {
  81135. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  81136. }
  81137. else {
  81138. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  81139. }
  81140. var speed = camera._computeLocalCameraSpeed() * 50.0;
  81141. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  81142. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  81143. camera.cameraDirection.addInPlace(this._deltaTransform);
  81144. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  81145. camera.cameraRotation.addInPlace(this._vector2);
  81146. }
  81147. };
  81148. /**
  81149. * Gets the class name of the current intput.
  81150. * @returns the class name
  81151. */
  81152. FreeCameraGamepadInput.prototype.getClassName = function () {
  81153. return "FreeCameraGamepadInput";
  81154. };
  81155. /**
  81156. * Get the friendly name associated with the input class.
  81157. * @returns the input friendly name
  81158. */
  81159. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  81160. return "gamepad";
  81161. };
  81162. __decorate([
  81163. BABYLON.serialize()
  81164. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  81165. __decorate([
  81166. BABYLON.serialize()
  81167. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81168. return FreeCameraGamepadInput;
  81169. }());
  81170. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  81171. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  81172. })(BABYLON || (BABYLON = {}));
  81173. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  81174. var BABYLON;
  81175. (function (BABYLON) {
  81176. /**
  81177. * Manage the gamepad inputs to control an arc rotate camera.
  81178. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81179. */
  81180. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  81181. function ArcRotateCameraGamepadInput() {
  81182. /**
  81183. * Defines the gamepad rotation sensiblity.
  81184. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81185. */
  81186. this.gamepadRotationSensibility = 80;
  81187. /**
  81188. * Defines the gamepad move sensiblity.
  81189. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81190. */
  81191. this.gamepadMoveSensibility = 40;
  81192. }
  81193. /**
  81194. * Attach the input controls to a specific dom element to get the input from.
  81195. * @param element Defines the element the controls should be listened from
  81196. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81197. */
  81198. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81199. var _this = this;
  81200. var manager = this.camera.getScene().gamepadManager;
  81201. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81202. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81203. // prioritize XBOX gamepads.
  81204. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81205. _this.gamepad = gamepad;
  81206. }
  81207. }
  81208. });
  81209. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81210. if (_this.gamepad === gamepad) {
  81211. _this.gamepad = null;
  81212. }
  81213. });
  81214. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81215. };
  81216. /**
  81217. * Detach the current controls from the specified dom element.
  81218. * @param element Defines the element to stop listening the inputs from
  81219. */
  81220. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  81221. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81222. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81223. this.gamepad = null;
  81224. };
  81225. /**
  81226. * Update the current camera state depending on the inputs that have been used this frame.
  81227. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81228. */
  81229. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  81230. if (this.gamepad) {
  81231. var camera = this.camera;
  81232. var RSValues = this.gamepad.rightStick;
  81233. if (RSValues) {
  81234. if (RSValues.x != 0) {
  81235. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  81236. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  81237. camera.inertialAlphaOffset += normalizedRX;
  81238. }
  81239. }
  81240. if (RSValues.y != 0) {
  81241. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  81242. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  81243. camera.inertialBetaOffset += normalizedRY;
  81244. }
  81245. }
  81246. }
  81247. var LSValues = this.gamepad.leftStick;
  81248. if (LSValues && LSValues.y != 0) {
  81249. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81250. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  81251. this.camera.inertialRadiusOffset -= normalizedLY;
  81252. }
  81253. }
  81254. }
  81255. };
  81256. /**
  81257. * Gets the class name of the current intput.
  81258. * @returns the class name
  81259. */
  81260. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  81261. return "ArcRotateCameraGamepadInput";
  81262. };
  81263. /**
  81264. * Get the friendly name associated with the input class.
  81265. * @returns the input friendly name
  81266. */
  81267. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  81268. return "gamepad";
  81269. };
  81270. __decorate([
  81271. BABYLON.serialize()
  81272. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  81273. __decorate([
  81274. BABYLON.serialize()
  81275. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81276. return ArcRotateCameraGamepadInput;
  81277. }());
  81278. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  81279. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  81280. })(BABYLON || (BABYLON = {}));
  81281. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  81282. var BABYLON;
  81283. (function (BABYLON) {
  81284. /**
  81285. * Manager for handling gamepads
  81286. */
  81287. var GamepadManager = /** @class */ (function () {
  81288. /**
  81289. * Initializes the gamepad manager
  81290. * @param _scene BabylonJS scene
  81291. */
  81292. function GamepadManager(_scene) {
  81293. var _this = this;
  81294. this._scene = _scene;
  81295. this._babylonGamepads = [];
  81296. this._oneGamepadConnected = false;
  81297. /** @hidden */
  81298. this._isMonitoring = false;
  81299. /**
  81300. * observable to be triggered when the gamepad controller has been disconnected
  81301. */
  81302. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  81303. if (!BABYLON.Tools.IsWindowObjectExist()) {
  81304. this._gamepadEventSupported = false;
  81305. }
  81306. else {
  81307. this._gamepadEventSupported = 'GamepadEvent' in window;
  81308. this._gamepadSupport = (navigator.getGamepads ||
  81309. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  81310. }
  81311. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  81312. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  81313. for (var i in _this._babylonGamepads) {
  81314. var gamepad = _this._babylonGamepads[i];
  81315. if (gamepad && gamepad._isConnected) {
  81316. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  81317. }
  81318. }
  81319. });
  81320. this._onGamepadConnectedEvent = function (evt) {
  81321. var gamepad = evt.gamepad;
  81322. if (gamepad.index in _this._babylonGamepads) {
  81323. if (_this._babylonGamepads[gamepad.index].isConnected) {
  81324. return;
  81325. }
  81326. }
  81327. var newGamepad;
  81328. if (_this._babylonGamepads[gamepad.index]) {
  81329. newGamepad = _this._babylonGamepads[gamepad.index];
  81330. newGamepad.browserGamepad = gamepad;
  81331. newGamepad._isConnected = true;
  81332. }
  81333. else {
  81334. newGamepad = _this._addNewGamepad(gamepad);
  81335. }
  81336. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81337. _this._startMonitoringGamepads();
  81338. };
  81339. this._onGamepadDisconnectedEvent = function (evt) {
  81340. var gamepad = evt.gamepad;
  81341. // Remove the gamepad from the list of gamepads to monitor.
  81342. for (var i in _this._babylonGamepads) {
  81343. if (_this._babylonGamepads[i].index === gamepad.index) {
  81344. var disconnectedGamepad = _this._babylonGamepads[i];
  81345. disconnectedGamepad._isConnected = false;
  81346. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  81347. break;
  81348. }
  81349. }
  81350. };
  81351. if (this._gamepadSupport) {
  81352. //first add already-connected gamepads
  81353. this._updateGamepadObjects();
  81354. if (this._babylonGamepads.length) {
  81355. this._startMonitoringGamepads();
  81356. }
  81357. // Checking if the gamepad connected event is supported (like in Firefox)
  81358. if (this._gamepadEventSupported) {
  81359. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  81360. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  81361. }
  81362. else {
  81363. this._startMonitoringGamepads();
  81364. }
  81365. }
  81366. }
  81367. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  81368. /**
  81369. * The gamepads in the game pad manager
  81370. */
  81371. get: function () {
  81372. return this._babylonGamepads;
  81373. },
  81374. enumerable: true,
  81375. configurable: true
  81376. });
  81377. /**
  81378. * Get the gamepad controllers based on type
  81379. * @param type The type of gamepad controller
  81380. * @returns Nullable gamepad
  81381. */
  81382. GamepadManager.prototype.getGamepadByType = function (type) {
  81383. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  81384. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  81385. var gamepad = _a[_i];
  81386. if (gamepad && gamepad.type === type) {
  81387. return gamepad;
  81388. }
  81389. }
  81390. return null;
  81391. };
  81392. /**
  81393. * Disposes the gamepad manager
  81394. */
  81395. GamepadManager.prototype.dispose = function () {
  81396. if (this._gamepadEventSupported) {
  81397. if (this._onGamepadConnectedEvent) {
  81398. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  81399. }
  81400. if (this._onGamepadDisconnectedEvent) {
  81401. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  81402. }
  81403. this._onGamepadConnectedEvent = null;
  81404. this._onGamepadDisconnectedEvent = null;
  81405. }
  81406. this._babylonGamepads.forEach(function (gamepad) {
  81407. gamepad.dispose();
  81408. });
  81409. this.onGamepadConnectedObservable.clear();
  81410. this.onGamepadDisconnectedObservable.clear();
  81411. this._oneGamepadConnected = false;
  81412. this._stopMonitoringGamepads();
  81413. this._babylonGamepads = [];
  81414. };
  81415. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  81416. if (!this._oneGamepadConnected) {
  81417. this._oneGamepadConnected = true;
  81418. }
  81419. var newGamepad;
  81420. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  81421. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  81422. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  81423. }
  81424. // if pose is supported, use the (WebVR) pose enabled controller
  81425. else if (gamepad.pose) {
  81426. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  81427. }
  81428. else {
  81429. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  81430. }
  81431. this._babylonGamepads[newGamepad.index] = newGamepad;
  81432. return newGamepad;
  81433. };
  81434. GamepadManager.prototype._startMonitoringGamepads = function () {
  81435. if (!this._isMonitoring) {
  81436. this._isMonitoring = true;
  81437. //back-comp
  81438. if (!this._scene) {
  81439. this._checkGamepadsStatus();
  81440. }
  81441. }
  81442. };
  81443. GamepadManager.prototype._stopMonitoringGamepads = function () {
  81444. this._isMonitoring = false;
  81445. };
  81446. /** @hidden */
  81447. GamepadManager.prototype._checkGamepadsStatus = function () {
  81448. var _this = this;
  81449. // Hack to be compatible Chrome
  81450. this._updateGamepadObjects();
  81451. for (var i in this._babylonGamepads) {
  81452. var gamepad = this._babylonGamepads[i];
  81453. if (!gamepad || !gamepad.isConnected) {
  81454. continue;
  81455. }
  81456. gamepad.update();
  81457. }
  81458. if (this._isMonitoring && !this._scene) {
  81459. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  81460. }
  81461. };
  81462. // This function is called only on Chrome, which does not properly support
  81463. // connection/disconnection events and forces you to recopy again the gamepad object
  81464. GamepadManager.prototype._updateGamepadObjects = function () {
  81465. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  81466. for (var i = 0; i < gamepads.length; i++) {
  81467. var gamepad = gamepads[i];
  81468. if (gamepad) {
  81469. if (!this._babylonGamepads[gamepad.index]) {
  81470. var newGamepad = this._addNewGamepad(gamepad);
  81471. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81472. }
  81473. else {
  81474. // Forced to copy again this object for Chrome for unknown reason
  81475. this._babylonGamepads[i].browserGamepad = gamepad;
  81476. if (!this._babylonGamepads[i].isConnected) {
  81477. this._babylonGamepads[i]._isConnected = true;
  81478. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  81479. }
  81480. }
  81481. }
  81482. }
  81483. };
  81484. return GamepadManager;
  81485. }());
  81486. BABYLON.GamepadManager = GamepadManager;
  81487. })(BABYLON || (BABYLON = {}));
  81488. //# sourceMappingURL=babylon.gamepadManager.js.map
  81489. var BABYLON;
  81490. (function (BABYLON) {
  81491. /**
  81492. * Represents a gamepad control stick position
  81493. */
  81494. var StickValues = /** @class */ (function () {
  81495. /**
  81496. * Initializes the gamepad x and y control stick values
  81497. * @param x The x component of the gamepad control stick value
  81498. * @param y The y component of the gamepad control stick value
  81499. */
  81500. function StickValues(
  81501. /**
  81502. * The x component of the control stick
  81503. */
  81504. x,
  81505. /**
  81506. * The y component of the control stick
  81507. */
  81508. y) {
  81509. this.x = x;
  81510. this.y = y;
  81511. }
  81512. return StickValues;
  81513. }());
  81514. BABYLON.StickValues = StickValues;
  81515. /**
  81516. * Represents a gamepad
  81517. */
  81518. var Gamepad = /** @class */ (function () {
  81519. /**
  81520. * Initializes the gamepad
  81521. * @param id The id of the gamepad
  81522. * @param index The index of the gamepad
  81523. * @param browserGamepad The browser gamepad
  81524. * @param leftStickX The x component of the left joystick
  81525. * @param leftStickY The y component of the left joystick
  81526. * @param rightStickX The x component of the right joystick
  81527. * @param rightStickY The y component of the right joystick
  81528. */
  81529. function Gamepad(
  81530. /**
  81531. * The id of the gamepad
  81532. */
  81533. id,
  81534. /**
  81535. * The index of the gamepad
  81536. */
  81537. index,
  81538. /**
  81539. * The browser gamepad
  81540. */
  81541. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  81542. if (leftStickX === void 0) { leftStickX = 0; }
  81543. if (leftStickY === void 0) { leftStickY = 1; }
  81544. if (rightStickX === void 0) { rightStickX = 2; }
  81545. if (rightStickY === void 0) { rightStickY = 3; }
  81546. this.id = id;
  81547. this.index = index;
  81548. this.browserGamepad = browserGamepad;
  81549. this._leftStick = { x: 0, y: 0 };
  81550. this._rightStick = { x: 0, y: 0 };
  81551. /** @hidden */
  81552. this._isConnected = true;
  81553. /**
  81554. * Specifies whether the left control stick should be Y-inverted
  81555. */
  81556. this._invertLeftStickY = false;
  81557. this.type = Gamepad.GAMEPAD;
  81558. this._leftStickAxisX = leftStickX;
  81559. this._leftStickAxisY = leftStickY;
  81560. this._rightStickAxisX = rightStickX;
  81561. this._rightStickAxisY = rightStickY;
  81562. if (this.browserGamepad.axes.length >= 2) {
  81563. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81564. }
  81565. if (this.browserGamepad.axes.length >= 4) {
  81566. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81567. }
  81568. }
  81569. Object.defineProperty(Gamepad.prototype, "isConnected", {
  81570. /**
  81571. * Specifies if the gamepad has been connected
  81572. */
  81573. get: function () {
  81574. return this._isConnected;
  81575. },
  81576. enumerable: true,
  81577. configurable: true
  81578. });
  81579. /**
  81580. * Callback triggered when the left joystick has changed
  81581. * @param callback
  81582. */
  81583. Gamepad.prototype.onleftstickchanged = function (callback) {
  81584. this._onleftstickchanged = callback;
  81585. };
  81586. /**
  81587. * Callback triggered when the right joystick has changed
  81588. * @param callback
  81589. */
  81590. Gamepad.prototype.onrightstickchanged = function (callback) {
  81591. this._onrightstickchanged = callback;
  81592. };
  81593. Object.defineProperty(Gamepad.prototype, "leftStick", {
  81594. /**
  81595. * Gets the left joystick
  81596. */
  81597. get: function () {
  81598. return this._leftStick;
  81599. },
  81600. /**
  81601. * Sets the left joystick values
  81602. */
  81603. set: function (newValues) {
  81604. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  81605. this._onleftstickchanged(newValues);
  81606. }
  81607. this._leftStick = newValues;
  81608. },
  81609. enumerable: true,
  81610. configurable: true
  81611. });
  81612. Object.defineProperty(Gamepad.prototype, "rightStick", {
  81613. /**
  81614. * Gets the right joystick
  81615. */
  81616. get: function () {
  81617. return this._rightStick;
  81618. },
  81619. /**
  81620. * Sets the right joystick value
  81621. */
  81622. set: function (newValues) {
  81623. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  81624. this._onrightstickchanged(newValues);
  81625. }
  81626. this._rightStick = newValues;
  81627. },
  81628. enumerable: true,
  81629. configurable: true
  81630. });
  81631. /**
  81632. * Updates the gamepad joystick positions
  81633. */
  81634. Gamepad.prototype.update = function () {
  81635. if (this._leftStick) {
  81636. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81637. if (this._invertLeftStickY) {
  81638. this.leftStick.y *= -1;
  81639. }
  81640. }
  81641. if (this._rightStick) {
  81642. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81643. }
  81644. };
  81645. /**
  81646. * Disposes the gamepad
  81647. */
  81648. Gamepad.prototype.dispose = function () {
  81649. };
  81650. /**
  81651. * Represents a gamepad controller
  81652. */
  81653. Gamepad.GAMEPAD = 0;
  81654. /**
  81655. * Represents a generic controller
  81656. */
  81657. Gamepad.GENERIC = 1;
  81658. /**
  81659. * Represents an XBox controller
  81660. */
  81661. Gamepad.XBOX = 2;
  81662. /**
  81663. * Represents a pose-enabled controller
  81664. */
  81665. Gamepad.POSE_ENABLED = 3;
  81666. return Gamepad;
  81667. }());
  81668. BABYLON.Gamepad = Gamepad;
  81669. /**
  81670. * Represents a generic gamepad
  81671. */
  81672. var GenericPad = /** @class */ (function (_super) {
  81673. __extends(GenericPad, _super);
  81674. /**
  81675. * Initializes the generic gamepad
  81676. * @param id The id of the generic gamepad
  81677. * @param index The index of the generic gamepad
  81678. * @param browserGamepad The browser gamepad
  81679. */
  81680. function GenericPad(id, index, browserGamepad) {
  81681. var _this = _super.call(this, id, index, browserGamepad) || this;
  81682. /**
  81683. * Observable triggered when a button has been pressed
  81684. */
  81685. _this.onButtonDownObservable = new BABYLON.Observable();
  81686. /**
  81687. * Observable triggered when a button has been released
  81688. */
  81689. _this.onButtonUpObservable = new BABYLON.Observable();
  81690. _this.type = Gamepad.GENERIC;
  81691. _this._buttons = new Array(browserGamepad.buttons.length);
  81692. return _this;
  81693. }
  81694. /**
  81695. * Callback triggered when a button has been pressed
  81696. * @param callback Called when a button has been pressed
  81697. */
  81698. GenericPad.prototype.onbuttondown = function (callback) {
  81699. this._onbuttondown = callback;
  81700. };
  81701. /**
  81702. * Callback triggered when a button has been released
  81703. * @param callback Called when a button has been released
  81704. */
  81705. GenericPad.prototype.onbuttonup = function (callback) {
  81706. this._onbuttonup = callback;
  81707. };
  81708. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  81709. if (newValue !== currentValue) {
  81710. if (newValue === 1) {
  81711. if (this._onbuttondown) {
  81712. this._onbuttondown(buttonIndex);
  81713. }
  81714. this.onButtonDownObservable.notifyObservers(buttonIndex);
  81715. }
  81716. if (newValue === 0) {
  81717. if (this._onbuttonup) {
  81718. this._onbuttonup(buttonIndex);
  81719. }
  81720. this.onButtonUpObservable.notifyObservers(buttonIndex);
  81721. }
  81722. }
  81723. return newValue;
  81724. };
  81725. /**
  81726. * Updates the generic gamepad
  81727. */
  81728. GenericPad.prototype.update = function () {
  81729. _super.prototype.update.call(this);
  81730. for (var index = 0; index < this._buttons.length; index++) {
  81731. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  81732. }
  81733. };
  81734. /**
  81735. * Disposes the generic gamepad
  81736. */
  81737. GenericPad.prototype.dispose = function () {
  81738. _super.prototype.dispose.call(this);
  81739. this.onButtonDownObservable.clear();
  81740. this.onButtonUpObservable.clear();
  81741. };
  81742. return GenericPad;
  81743. }(Gamepad));
  81744. BABYLON.GenericPad = GenericPad;
  81745. })(BABYLON || (BABYLON = {}));
  81746. //# sourceMappingURL=babylon.gamepad.js.map
  81747. var BABYLON;
  81748. (function (BABYLON) {
  81749. /**
  81750. * Defines supported buttons for XBox360 compatible gamepads
  81751. */
  81752. var Xbox360Button;
  81753. (function (Xbox360Button) {
  81754. /** A */
  81755. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  81756. /** B */
  81757. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  81758. /** X */
  81759. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  81760. /** Y */
  81761. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  81762. /** Start */
  81763. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  81764. /** Back */
  81765. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  81766. /** Left button */
  81767. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  81768. /** Right button */
  81769. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  81770. /** Left stick */
  81771. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  81772. /** Right stick */
  81773. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  81774. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  81775. /** Defines values for XBox360 DPad */
  81776. var Xbox360Dpad;
  81777. (function (Xbox360Dpad) {
  81778. /** Up */
  81779. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  81780. /** Down */
  81781. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  81782. /** Left */
  81783. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  81784. /** Right */
  81785. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  81786. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  81787. /**
  81788. * Defines a XBox360 gamepad
  81789. */
  81790. var Xbox360Pad = /** @class */ (function (_super) {
  81791. __extends(Xbox360Pad, _super);
  81792. /**
  81793. * Creates a new XBox360 gamepad object
  81794. * @param id defines the id of this gamepad
  81795. * @param index defines its index
  81796. * @param gamepad defines the internal HTML gamepad object
  81797. * @param xboxOne defines if it is a XBox One gamepad
  81798. */
  81799. function Xbox360Pad(id, index, gamepad, xboxOne) {
  81800. if (xboxOne === void 0) { xboxOne = false; }
  81801. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  81802. _this._leftTrigger = 0;
  81803. _this._rightTrigger = 0;
  81804. /** Observable raised when a button is pressed */
  81805. _this.onButtonDownObservable = new BABYLON.Observable();
  81806. /** Observable raised when a button is released */
  81807. _this.onButtonUpObservable = new BABYLON.Observable();
  81808. /** Observable raised when a pad is pressed */
  81809. _this.onPadDownObservable = new BABYLON.Observable();
  81810. /** Observable raised when a pad is released */
  81811. _this.onPadUpObservable = new BABYLON.Observable();
  81812. _this._buttonA = 0;
  81813. _this._buttonB = 0;
  81814. _this._buttonX = 0;
  81815. _this._buttonY = 0;
  81816. _this._buttonBack = 0;
  81817. _this._buttonStart = 0;
  81818. _this._buttonLB = 0;
  81819. _this._buttonRB = 0;
  81820. _this._buttonLeftStick = 0;
  81821. _this._buttonRightStick = 0;
  81822. _this._dPadUp = 0;
  81823. _this._dPadDown = 0;
  81824. _this._dPadLeft = 0;
  81825. _this._dPadRight = 0;
  81826. _this._isXboxOnePad = false;
  81827. _this.type = BABYLON.Gamepad.XBOX;
  81828. _this._isXboxOnePad = xboxOne;
  81829. return _this;
  81830. }
  81831. /**
  81832. * Defines the callback to call when left trigger is pressed
  81833. * @param callback defines the callback to use
  81834. */
  81835. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  81836. this._onlefttriggerchanged = callback;
  81837. };
  81838. /**
  81839. * Defines the callback to call when right trigger is pressed
  81840. * @param callback defines the callback to use
  81841. */
  81842. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  81843. this._onrighttriggerchanged = callback;
  81844. };
  81845. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  81846. /**
  81847. * Gets the left trigger value
  81848. */
  81849. get: function () {
  81850. return this._leftTrigger;
  81851. },
  81852. /**
  81853. * Sets the left trigger value
  81854. */
  81855. set: function (newValue) {
  81856. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  81857. this._onlefttriggerchanged(newValue);
  81858. }
  81859. this._leftTrigger = newValue;
  81860. },
  81861. enumerable: true,
  81862. configurable: true
  81863. });
  81864. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  81865. /**
  81866. * Gets the right trigger value
  81867. */
  81868. get: function () {
  81869. return this._rightTrigger;
  81870. },
  81871. /**
  81872. * Sets the right trigger value
  81873. */
  81874. set: function (newValue) {
  81875. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  81876. this._onrighttriggerchanged(newValue);
  81877. }
  81878. this._rightTrigger = newValue;
  81879. },
  81880. enumerable: true,
  81881. configurable: true
  81882. });
  81883. /**
  81884. * Defines the callback to call when a button is pressed
  81885. * @param callback defines the callback to use
  81886. */
  81887. Xbox360Pad.prototype.onbuttondown = function (callback) {
  81888. this._onbuttondown = callback;
  81889. };
  81890. /**
  81891. * Defines the callback to call when a button is released
  81892. * @param callback defines the callback to use
  81893. */
  81894. Xbox360Pad.prototype.onbuttonup = function (callback) {
  81895. this._onbuttonup = callback;
  81896. };
  81897. /**
  81898. * Defines the callback to call when a pad is pressed
  81899. * @param callback defines the callback to use
  81900. */
  81901. Xbox360Pad.prototype.ondpaddown = function (callback) {
  81902. this._ondpaddown = callback;
  81903. };
  81904. /**
  81905. * Defines the callback to call when a pad is released
  81906. * @param callback defines the callback to use
  81907. */
  81908. Xbox360Pad.prototype.ondpadup = function (callback) {
  81909. this._ondpadup = callback;
  81910. };
  81911. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  81912. if (newValue !== currentValue) {
  81913. if (newValue === 1) {
  81914. if (this._onbuttondown) {
  81915. this._onbuttondown(buttonType);
  81916. }
  81917. this.onButtonDownObservable.notifyObservers(buttonType);
  81918. }
  81919. if (newValue === 0) {
  81920. if (this._onbuttonup) {
  81921. this._onbuttonup(buttonType);
  81922. }
  81923. this.onButtonUpObservable.notifyObservers(buttonType);
  81924. }
  81925. }
  81926. return newValue;
  81927. };
  81928. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  81929. if (newValue !== currentValue) {
  81930. if (newValue === 1) {
  81931. if (this._ondpaddown) {
  81932. this._ondpaddown(buttonType);
  81933. }
  81934. this.onPadDownObservable.notifyObservers(buttonType);
  81935. }
  81936. if (newValue === 0) {
  81937. if (this._ondpadup) {
  81938. this._ondpadup(buttonType);
  81939. }
  81940. this.onPadUpObservable.notifyObservers(buttonType);
  81941. }
  81942. }
  81943. return newValue;
  81944. };
  81945. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  81946. /**
  81947. * Gets the value of the `A` button
  81948. */
  81949. get: function () {
  81950. return this._buttonA;
  81951. },
  81952. /**
  81953. * Sets the value of the `A` button
  81954. */
  81955. set: function (value) {
  81956. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  81957. },
  81958. enumerable: true,
  81959. configurable: true
  81960. });
  81961. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  81962. /**
  81963. * Gets the value of the `B` button
  81964. */
  81965. get: function () {
  81966. return this._buttonB;
  81967. },
  81968. /**
  81969. * Sets the value of the `B` button
  81970. */
  81971. set: function (value) {
  81972. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  81973. },
  81974. enumerable: true,
  81975. configurable: true
  81976. });
  81977. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  81978. /**
  81979. * Gets the value of the `X` button
  81980. */
  81981. get: function () {
  81982. return this._buttonX;
  81983. },
  81984. /**
  81985. * Sets the value of the `X` button
  81986. */
  81987. set: function (value) {
  81988. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  81989. },
  81990. enumerable: true,
  81991. configurable: true
  81992. });
  81993. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  81994. /**
  81995. * Gets the value of the `Y` button
  81996. */
  81997. get: function () {
  81998. return this._buttonY;
  81999. },
  82000. /**
  82001. * Sets the value of the `Y` button
  82002. */
  82003. set: function (value) {
  82004. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  82005. },
  82006. enumerable: true,
  82007. configurable: true
  82008. });
  82009. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  82010. /**
  82011. * Gets the value of the `Start` button
  82012. */
  82013. get: function () {
  82014. return this._buttonStart;
  82015. },
  82016. /**
  82017. * Sets the value of the `Start` button
  82018. */
  82019. set: function (value) {
  82020. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  82021. },
  82022. enumerable: true,
  82023. configurable: true
  82024. });
  82025. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  82026. /**
  82027. * Gets the value of the `Back` button
  82028. */
  82029. get: function () {
  82030. return this._buttonBack;
  82031. },
  82032. /**
  82033. * Sets the value of the `Back` button
  82034. */
  82035. set: function (value) {
  82036. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  82037. },
  82038. enumerable: true,
  82039. configurable: true
  82040. });
  82041. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  82042. /**
  82043. * Gets the value of the `Left` button
  82044. */
  82045. get: function () {
  82046. return this._buttonLB;
  82047. },
  82048. /**
  82049. * Sets the value of the `Left` button
  82050. */
  82051. set: function (value) {
  82052. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  82053. },
  82054. enumerable: true,
  82055. configurable: true
  82056. });
  82057. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  82058. /**
  82059. * Gets the value of the `Right` button
  82060. */
  82061. get: function () {
  82062. return this._buttonRB;
  82063. },
  82064. /**
  82065. * Sets the value of the `Right` button
  82066. */
  82067. set: function (value) {
  82068. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  82069. },
  82070. enumerable: true,
  82071. configurable: true
  82072. });
  82073. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  82074. /**
  82075. * Gets the value of the Left joystick
  82076. */
  82077. get: function () {
  82078. return this._buttonLeftStick;
  82079. },
  82080. /**
  82081. * Sets the value of the Left joystick
  82082. */
  82083. set: function (value) {
  82084. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  82085. },
  82086. enumerable: true,
  82087. configurable: true
  82088. });
  82089. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  82090. /**
  82091. * Gets the value of the Right joystick
  82092. */
  82093. get: function () {
  82094. return this._buttonRightStick;
  82095. },
  82096. /**
  82097. * Sets the value of the Right joystick
  82098. */
  82099. set: function (value) {
  82100. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  82101. },
  82102. enumerable: true,
  82103. configurable: true
  82104. });
  82105. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  82106. /**
  82107. * Gets the value of D-pad up
  82108. */
  82109. get: function () {
  82110. return this._dPadUp;
  82111. },
  82112. /**
  82113. * Sets the value of D-pad up
  82114. */
  82115. set: function (value) {
  82116. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  82117. },
  82118. enumerable: true,
  82119. configurable: true
  82120. });
  82121. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  82122. /**
  82123. * Gets the value of D-pad down
  82124. */
  82125. get: function () {
  82126. return this._dPadDown;
  82127. },
  82128. /**
  82129. * Sets the value of D-pad down
  82130. */
  82131. set: function (value) {
  82132. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  82133. },
  82134. enumerable: true,
  82135. configurable: true
  82136. });
  82137. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  82138. /**
  82139. * Gets the value of D-pad left
  82140. */
  82141. get: function () {
  82142. return this._dPadLeft;
  82143. },
  82144. /**
  82145. * Sets the value of D-pad left
  82146. */
  82147. set: function (value) {
  82148. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  82149. },
  82150. enumerable: true,
  82151. configurable: true
  82152. });
  82153. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  82154. /**
  82155. * Gets the value of D-pad right
  82156. */
  82157. get: function () {
  82158. return this._dPadRight;
  82159. },
  82160. /**
  82161. * Sets the value of D-pad right
  82162. */
  82163. set: function (value) {
  82164. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  82165. },
  82166. enumerable: true,
  82167. configurable: true
  82168. });
  82169. /**
  82170. * Force the gamepad to synchronize with device values
  82171. */
  82172. Xbox360Pad.prototype.update = function () {
  82173. _super.prototype.update.call(this);
  82174. if (this._isXboxOnePad) {
  82175. this.buttonA = this.browserGamepad.buttons[0].value;
  82176. this.buttonB = this.browserGamepad.buttons[1].value;
  82177. this.buttonX = this.browserGamepad.buttons[2].value;
  82178. this.buttonY = this.browserGamepad.buttons[3].value;
  82179. this.buttonLB = this.browserGamepad.buttons[4].value;
  82180. this.buttonRB = this.browserGamepad.buttons[5].value;
  82181. this.leftTrigger = this.browserGamepad.axes[2];
  82182. this.rightTrigger = this.browserGamepad.axes[5];
  82183. this.buttonBack = this.browserGamepad.buttons[9].value;
  82184. this.buttonStart = this.browserGamepad.buttons[8].value;
  82185. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  82186. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  82187. this.dPadUp = this.browserGamepad.buttons[11].value;
  82188. this.dPadDown = this.browserGamepad.buttons[12].value;
  82189. this.dPadLeft = this.browserGamepad.buttons[13].value;
  82190. this.dPadRight = this.browserGamepad.buttons[14].value;
  82191. }
  82192. else {
  82193. this.buttonA = this.browserGamepad.buttons[0].value;
  82194. this.buttonB = this.browserGamepad.buttons[1].value;
  82195. this.buttonX = this.browserGamepad.buttons[2].value;
  82196. this.buttonY = this.browserGamepad.buttons[3].value;
  82197. this.buttonLB = this.browserGamepad.buttons[4].value;
  82198. this.buttonRB = this.browserGamepad.buttons[5].value;
  82199. this.leftTrigger = this.browserGamepad.buttons[6].value;
  82200. this.rightTrigger = this.browserGamepad.buttons[7].value;
  82201. this.buttonBack = this.browserGamepad.buttons[8].value;
  82202. this.buttonStart = this.browserGamepad.buttons[9].value;
  82203. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  82204. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  82205. this.dPadUp = this.browserGamepad.buttons[12].value;
  82206. this.dPadDown = this.browserGamepad.buttons[13].value;
  82207. this.dPadLeft = this.browserGamepad.buttons[14].value;
  82208. this.dPadRight = this.browserGamepad.buttons[15].value;
  82209. }
  82210. };
  82211. /**
  82212. * Disposes the gamepad
  82213. */
  82214. Xbox360Pad.prototype.dispose = function () {
  82215. _super.prototype.dispose.call(this);
  82216. this.onButtonDownObservable.clear();
  82217. this.onButtonUpObservable.clear();
  82218. this.onPadDownObservable.clear();
  82219. this.onPadUpObservable.clear();
  82220. };
  82221. return Xbox360Pad;
  82222. }(BABYLON.Gamepad));
  82223. BABYLON.Xbox360Pad = Xbox360Pad;
  82224. })(BABYLON || (BABYLON = {}));
  82225. //# sourceMappingURL=babylon.xboxGamepad.js.map
  82226. var BABYLON;
  82227. (function (BABYLON) {
  82228. /**
  82229. * Defines the types of pose enabled controllers that are supported
  82230. */
  82231. var PoseEnabledControllerType;
  82232. (function (PoseEnabledControllerType) {
  82233. /**
  82234. * HTC Vive
  82235. */
  82236. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  82237. /**
  82238. * Oculus Rift
  82239. */
  82240. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  82241. /**
  82242. * Windows mixed reality
  82243. */
  82244. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  82245. /**
  82246. * Samsung gear VR
  82247. */
  82248. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  82249. /**
  82250. * Google Daydream
  82251. */
  82252. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  82253. /**
  82254. * Generic
  82255. */
  82256. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  82257. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  82258. /**
  82259. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82260. */
  82261. var PoseEnabledControllerHelper = /** @class */ (function () {
  82262. function PoseEnabledControllerHelper() {
  82263. }
  82264. /**
  82265. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82266. * @param vrGamepad the gamepad to initialized
  82267. * @returns a vr controller of the type the gamepad identified as
  82268. */
  82269. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  82270. // Oculus Touch
  82271. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  82272. return new BABYLON.OculusTouchController(vrGamepad);
  82273. }
  82274. // Windows Mixed Reality controllers
  82275. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  82276. return new BABYLON.WindowsMotionController(vrGamepad);
  82277. }
  82278. // HTC Vive
  82279. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  82280. return new BABYLON.ViveController(vrGamepad);
  82281. }
  82282. // Samsung/Oculus Gear VR or Oculus Go
  82283. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  82284. return new BABYLON.GearVRController(vrGamepad);
  82285. }
  82286. // Google Daydream
  82287. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  82288. return new BABYLON.DaydreamController(vrGamepad);
  82289. }
  82290. // Generic
  82291. else {
  82292. return new BABYLON.GenericController(vrGamepad);
  82293. }
  82294. };
  82295. return PoseEnabledControllerHelper;
  82296. }());
  82297. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  82298. /**
  82299. * Defines the PoseEnabledController object that contains state of a vr capable controller
  82300. */
  82301. var PoseEnabledController = /** @class */ (function (_super) {
  82302. __extends(PoseEnabledController, _super);
  82303. /**
  82304. * Creates a new PoseEnabledController from a gamepad
  82305. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  82306. */
  82307. function PoseEnabledController(browserGamepad) {
  82308. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  82309. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82310. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82311. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  82312. /**
  82313. * The device position in babylon space
  82314. */
  82315. _this.devicePosition = BABYLON.Vector3.Zero();
  82316. /**
  82317. * The device rotation in babylon space
  82318. */
  82319. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  82320. /**
  82321. * The scale factor of the device in babylon space
  82322. */
  82323. _this.deviceScaleFactor = 1;
  82324. // Used to convert 6dof controllers to 3dof
  82325. _this._trackPosition = true;
  82326. _this._maxRotationDistFromHeadset = Math.PI / 5;
  82327. _this._draggedRoomRotation = 0;
  82328. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  82329. /**
  82330. * Internal, matrix used to convert room space to babylon space
  82331. * @hidden
  82332. */
  82333. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82334. /**
  82335. * Node to be used when casting a ray from the controller
  82336. * @hidden
  82337. */
  82338. _this._pointingPoseNode = null;
  82339. _this._workingMatrix = BABYLON.Matrix.Identity();
  82340. /**
  82341. * @hidden
  82342. */
  82343. _this._meshAttachedObservable = new BABYLON.Observable();
  82344. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  82345. _this.controllerType = PoseEnabledControllerType.GENERIC;
  82346. _this.position = BABYLON.Vector3.Zero();
  82347. _this.rotationQuaternion = new BABYLON.Quaternion();
  82348. _this._calculatedPosition = BABYLON.Vector3.Zero();
  82349. _this._calculatedRotation = new BABYLON.Quaternion();
  82350. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  82351. return _this;
  82352. }
  82353. /**
  82354. * @hidden
  82355. */
  82356. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  82357. if (this._trackPosition) {
  82358. this._calculatedPosition.copyFrom(fixedPosition);
  82359. this._trackPosition = false;
  82360. }
  82361. };
  82362. /**
  82363. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  82364. */
  82365. PoseEnabledController.prototype.update = function () {
  82366. _super.prototype.update.call(this);
  82367. this._updatePoseAndMesh();
  82368. };
  82369. /**
  82370. * Updates only the pose device and mesh without doing any button event checking
  82371. */
  82372. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  82373. var pose = this.browserGamepad.pose;
  82374. this.updateFromDevice(pose);
  82375. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  82376. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  82377. camera._computeDevicePosition();
  82378. this._deviceToWorld.setTranslation(camera.devicePosition);
  82379. if (camera.deviceRotationQuaternion) {
  82380. var camera = camera;
  82381. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  82382. // Find the radian distance away that the headset is from the controllers rotation
  82383. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  82384. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  82385. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  82386. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  82387. this._draggedRoomRotation += rotationAmount;
  82388. // Rotate controller around headset
  82389. var sin = Math.sin(-rotationAmount);
  82390. var cos = Math.cos(-rotationAmount);
  82391. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  82392. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  82393. }
  82394. }
  82395. }
  82396. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  82397. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  82398. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82399. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  82400. if (this._mesh) {
  82401. this._mesh.position.copyFrom(this.devicePosition);
  82402. if (this._mesh.rotationQuaternion) {
  82403. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  82404. }
  82405. }
  82406. };
  82407. /**
  82408. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  82409. * @param poseData raw pose fromthe device
  82410. */
  82411. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  82412. if (poseData) {
  82413. this.rawPose = poseData;
  82414. if (poseData.position) {
  82415. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  82416. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  82417. this._deviceRoomPosition.z *= -1;
  82418. }
  82419. if (this._trackPosition) {
  82420. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  82421. }
  82422. this._calculatedPosition.addInPlace(this.position);
  82423. }
  82424. var pose = this.rawPose;
  82425. if (poseData.orientation && pose.orientation) {
  82426. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  82427. if (this._mesh) {
  82428. if (this._mesh.getScene().useRightHandedSystem) {
  82429. this._deviceRoomRotationQuaternion.z *= -1;
  82430. this._deviceRoomRotationQuaternion.w *= -1;
  82431. }
  82432. else {
  82433. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  82434. }
  82435. }
  82436. // if the camera is set, rotate to the camera's rotation
  82437. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  82438. }
  82439. }
  82440. };
  82441. /**
  82442. * Attaches a mesh to the controller
  82443. * @param mesh the mesh to be attached
  82444. */
  82445. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  82446. if (this._mesh) {
  82447. this._mesh.parent = null;
  82448. }
  82449. this._mesh = mesh;
  82450. if (this._poseControlledCamera) {
  82451. this._mesh.parent = this._poseControlledCamera;
  82452. }
  82453. if (!this._mesh.rotationQuaternion) {
  82454. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  82455. }
  82456. // 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
  82457. this._updatePoseAndMesh();
  82458. if (this._pointingPoseNode) {
  82459. var parents = [];
  82460. var obj = this._pointingPoseNode;
  82461. while (obj.parent) {
  82462. parents.push(obj.parent);
  82463. obj = obj.parent;
  82464. }
  82465. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  82466. }
  82467. this._meshAttachedObservable.notifyObservers(mesh);
  82468. };
  82469. /**
  82470. * Attaches the controllers mesh to a camera
  82471. * @param camera the camera the mesh should be attached to
  82472. */
  82473. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  82474. this._poseControlledCamera = camera;
  82475. if (this._mesh) {
  82476. this._mesh.parent = this._poseControlledCamera;
  82477. }
  82478. };
  82479. /**
  82480. * Disposes of the controller
  82481. */
  82482. PoseEnabledController.prototype.dispose = function () {
  82483. if (this._mesh) {
  82484. this._mesh.dispose();
  82485. }
  82486. this._mesh = null;
  82487. _super.prototype.dispose.call(this);
  82488. };
  82489. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  82490. /**
  82491. * The mesh that is attached to the controller
  82492. */
  82493. get: function () {
  82494. return this._mesh;
  82495. },
  82496. enumerable: true,
  82497. configurable: true
  82498. });
  82499. /**
  82500. * Gets the ray of the controller in the direction the controller is pointing
  82501. * @param length the length the resulting ray should be
  82502. * @returns a ray in the direction the controller is pointing
  82503. */
  82504. PoseEnabledController.prototype.getForwardRay = function (length) {
  82505. if (length === void 0) { length = 100; }
  82506. if (!this.mesh) {
  82507. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  82508. }
  82509. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  82510. var origin = m.getTranslation();
  82511. var forward = new BABYLON.Vector3(0, 0, -1);
  82512. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82513. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82514. return new BABYLON.Ray(origin, direction, length);
  82515. };
  82516. /**
  82517. * Name of the child mesh that can be used to cast a ray from the controller
  82518. */
  82519. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  82520. return PoseEnabledController;
  82521. }(BABYLON.Gamepad));
  82522. BABYLON.PoseEnabledController = PoseEnabledController;
  82523. })(BABYLON || (BABYLON = {}));
  82524. //# sourceMappingURL=babylon.poseEnabledController.js.map
  82525. var BABYLON;
  82526. (function (BABYLON) {
  82527. /**
  82528. * Defines the WebVRController object that represents controllers tracked in 3D space
  82529. */
  82530. var WebVRController = /** @class */ (function (_super) {
  82531. __extends(WebVRController, _super);
  82532. /**
  82533. * Creates a new WebVRController from a gamepad
  82534. * @param vrGamepad the gamepad that the WebVRController should be created from
  82535. */
  82536. function WebVRController(vrGamepad) {
  82537. var _this = _super.call(this, vrGamepad) || this;
  82538. // Observables
  82539. /**
  82540. * Fired when the trigger state has changed
  82541. */
  82542. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  82543. /**
  82544. * Fired when the main button state has changed
  82545. */
  82546. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  82547. /**
  82548. * Fired when the secondary button state has changed
  82549. */
  82550. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  82551. /**
  82552. * Fired when the pad state has changed
  82553. */
  82554. _this.onPadStateChangedObservable = new BABYLON.Observable();
  82555. /**
  82556. * Fired when controllers stick values have changed
  82557. */
  82558. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  82559. /**
  82560. * X and Y axis corrisponding to the controllers joystick
  82561. */
  82562. _this.pad = { x: 0, y: 0 };
  82563. // avoid GC, store state in a tmp object
  82564. _this._changes = {
  82565. pressChanged: false,
  82566. touchChanged: false,
  82567. valueChanged: false,
  82568. changed: false
  82569. };
  82570. _this._buttons = new Array(vrGamepad.buttons.length);
  82571. _this.hand = vrGamepad.hand;
  82572. return _this;
  82573. }
  82574. /**
  82575. * Fired when a controller button's state has changed
  82576. * @param callback the callback containing the button that was modified
  82577. */
  82578. WebVRController.prototype.onButtonStateChange = function (callback) {
  82579. this._onButtonStateChange = callback;
  82580. };
  82581. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  82582. /**
  82583. * The default controller model for the controller
  82584. */
  82585. get: function () {
  82586. return this._defaultModel;
  82587. },
  82588. enumerable: true,
  82589. configurable: true
  82590. });
  82591. /**
  82592. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  82593. */
  82594. WebVRController.prototype.update = function () {
  82595. _super.prototype.update.call(this);
  82596. for (var index = 0; index < this._buttons.length; index++) {
  82597. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  82598. }
  82599. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  82600. this.pad.x = this.leftStick.x;
  82601. this.pad.y = this.leftStick.y;
  82602. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  82603. }
  82604. };
  82605. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  82606. if (!newState) {
  82607. newState = {
  82608. pressed: false,
  82609. touched: false,
  82610. value: 0
  82611. };
  82612. }
  82613. if (!currentState) {
  82614. this._buttons[buttonIndex] = {
  82615. pressed: newState.pressed,
  82616. touched: newState.touched,
  82617. value: newState.value
  82618. };
  82619. return;
  82620. }
  82621. this._checkChanges(newState, currentState);
  82622. if (this._changes.changed) {
  82623. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  82624. this._handleButtonChange(buttonIndex, newState, this._changes);
  82625. }
  82626. this._buttons[buttonIndex].pressed = newState.pressed;
  82627. this._buttons[buttonIndex].touched = newState.touched;
  82628. // oculus triggers are never 0, thou not touched.
  82629. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  82630. };
  82631. WebVRController.prototype._checkChanges = function (newState, currentState) {
  82632. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  82633. this._changes.touchChanged = newState.touched !== currentState.touched;
  82634. this._changes.valueChanged = newState.value !== currentState.value;
  82635. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  82636. return this._changes;
  82637. };
  82638. /**
  82639. * Disposes of th webVRCOntroller
  82640. */
  82641. WebVRController.prototype.dispose = function () {
  82642. _super.prototype.dispose.call(this);
  82643. this.onTriggerStateChangedObservable.clear();
  82644. this.onMainButtonStateChangedObservable.clear();
  82645. this.onSecondaryButtonStateChangedObservable.clear();
  82646. this.onPadStateChangedObservable.clear();
  82647. this.onPadValuesChangedObservable.clear();
  82648. };
  82649. return WebVRController;
  82650. }(BABYLON.PoseEnabledController));
  82651. BABYLON.WebVRController = WebVRController;
  82652. })(BABYLON || (BABYLON = {}));
  82653. //# sourceMappingURL=babylon.webVRController.js.map
  82654. var BABYLON;
  82655. (function (BABYLON) {
  82656. /**
  82657. * Oculus Touch Controller
  82658. */
  82659. var OculusTouchController = /** @class */ (function (_super) {
  82660. __extends(OculusTouchController, _super);
  82661. /**
  82662. * Creates a new OculusTouchController from a gamepad
  82663. * @param vrGamepad the gamepad that the controller should be created from
  82664. */
  82665. function OculusTouchController(vrGamepad) {
  82666. var _this = _super.call(this, vrGamepad) || this;
  82667. /**
  82668. * Fired when the secondary trigger on this controller is modified
  82669. */
  82670. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  82671. /**
  82672. * Fired when the thumb rest on this controller is modified
  82673. */
  82674. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  82675. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  82676. return _this;
  82677. }
  82678. /**
  82679. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82680. * @param scene scene in which to add meshes
  82681. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82682. */
  82683. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82684. var _this = this;
  82685. var meshName;
  82686. // Hand
  82687. if (this.hand === 'left') {
  82688. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  82689. }
  82690. else { // Right is the default if no hand is specified
  82691. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  82692. }
  82693. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  82694. /*
  82695. Parent Mesh name: oculus_touch_left
  82696. - body
  82697. - trigger
  82698. - thumbstick
  82699. - grip
  82700. - button_y
  82701. - button_x
  82702. - button_enter
  82703. */
  82704. _this._defaultModel = newMeshes[1];
  82705. _this.attachToMesh(_this._defaultModel);
  82706. if (meshLoaded) {
  82707. meshLoaded(_this._defaultModel);
  82708. }
  82709. });
  82710. };
  82711. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  82712. /**
  82713. * Fired when the A button on this controller is modified
  82714. */
  82715. get: function () {
  82716. if (this.hand === 'right') {
  82717. return this.onMainButtonStateChangedObservable;
  82718. }
  82719. else {
  82720. throw new Error('No A button on left hand');
  82721. }
  82722. },
  82723. enumerable: true,
  82724. configurable: true
  82725. });
  82726. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  82727. /**
  82728. * Fired when the B button on this controller is modified
  82729. */
  82730. get: function () {
  82731. if (this.hand === 'right') {
  82732. return this.onSecondaryButtonStateChangedObservable;
  82733. }
  82734. else {
  82735. throw new Error('No B button on left hand');
  82736. }
  82737. },
  82738. enumerable: true,
  82739. configurable: true
  82740. });
  82741. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  82742. /**
  82743. * Fired when the X button on this controller is modified
  82744. */
  82745. get: function () {
  82746. if (this.hand === 'left') {
  82747. return this.onMainButtonStateChangedObservable;
  82748. }
  82749. else {
  82750. throw new Error('No X button on right hand');
  82751. }
  82752. },
  82753. enumerable: true,
  82754. configurable: true
  82755. });
  82756. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  82757. /**
  82758. * Fired when the Y button on this controller is modified
  82759. */
  82760. get: function () {
  82761. if (this.hand === 'left') {
  82762. return this.onSecondaryButtonStateChangedObservable;
  82763. }
  82764. else {
  82765. throw new Error('No Y button on right hand');
  82766. }
  82767. },
  82768. enumerable: true,
  82769. configurable: true
  82770. });
  82771. /**
  82772. * Called once for each button that changed state since the last frame
  82773. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  82774. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  82775. * 2) secondary trigger (same)
  82776. * 3) A (right) X (left), touch, pressed = value
  82777. * 4) B / Y
  82778. * 5) thumb rest
  82779. * @param buttonIdx Which button index changed
  82780. * @param state New state of the button
  82781. * @param changes Which properties on the state changed since last frame
  82782. */
  82783. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82784. var notifyObject = state; //{ state: state, changes: changes };
  82785. var triggerDirection = this.hand === 'right' ? -1 : 1;
  82786. switch (buttonIdx) {
  82787. case 0:
  82788. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82789. return;
  82790. case 1: // index trigger
  82791. if (this._defaultModel) {
  82792. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  82793. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  82794. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  82795. }
  82796. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82797. return;
  82798. case 2: // secondary trigger
  82799. if (this._defaultModel) {
  82800. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  82801. }
  82802. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  82803. return;
  82804. case 3:
  82805. if (this._defaultModel) {
  82806. if (notifyObject.pressed) {
  82807. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  82808. }
  82809. else {
  82810. (this._defaultModel.getChildren()[1]).position.y = 0;
  82811. }
  82812. }
  82813. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82814. return;
  82815. case 4:
  82816. if (this._defaultModel) {
  82817. if (notifyObject.pressed) {
  82818. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82819. }
  82820. else {
  82821. (this._defaultModel.getChildren()[2]).position.y = 0;
  82822. }
  82823. }
  82824. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82825. return;
  82826. case 5:
  82827. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  82828. return;
  82829. }
  82830. };
  82831. /**
  82832. * Base Url for the controller model.
  82833. */
  82834. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  82835. /**
  82836. * File name for the left controller model.
  82837. */
  82838. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  82839. /**
  82840. * File name for the right controller model.
  82841. */
  82842. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  82843. return OculusTouchController;
  82844. }(BABYLON.WebVRController));
  82845. BABYLON.OculusTouchController = OculusTouchController;
  82846. })(BABYLON || (BABYLON = {}));
  82847. //# sourceMappingURL=babylon.oculusTouchController.js.map
  82848. var BABYLON;
  82849. (function (BABYLON) {
  82850. /**
  82851. * Vive Controller
  82852. */
  82853. var ViveController = /** @class */ (function (_super) {
  82854. __extends(ViveController, _super);
  82855. /**
  82856. * Creates a new ViveController from a gamepad
  82857. * @param vrGamepad the gamepad that the controller should be created from
  82858. */
  82859. function ViveController(vrGamepad) {
  82860. var _this = _super.call(this, vrGamepad) || this;
  82861. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  82862. _this._invertLeftStickY = true;
  82863. return _this;
  82864. }
  82865. /**
  82866. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82867. * @param scene scene in which to add meshes
  82868. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82869. */
  82870. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82871. var _this = this;
  82872. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  82873. /*
  82874. Parent Mesh name: ViveWand
  82875. - body
  82876. - r_gripper
  82877. - l_gripper
  82878. - menu_button
  82879. - system_button
  82880. - trackpad
  82881. - trigger
  82882. - LED
  82883. */
  82884. _this._defaultModel = newMeshes[1];
  82885. _this.attachToMesh(_this._defaultModel);
  82886. if (meshLoaded) {
  82887. meshLoaded(_this._defaultModel);
  82888. }
  82889. });
  82890. };
  82891. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  82892. /**
  82893. * Fired when the left button on this controller is modified
  82894. */
  82895. get: function () {
  82896. return this.onMainButtonStateChangedObservable;
  82897. },
  82898. enumerable: true,
  82899. configurable: true
  82900. });
  82901. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  82902. /**
  82903. * Fired when the right button on this controller is modified
  82904. */
  82905. get: function () {
  82906. return this.onMainButtonStateChangedObservable;
  82907. },
  82908. enumerable: true,
  82909. configurable: true
  82910. });
  82911. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  82912. /**
  82913. * Fired when the menu button on this controller is modified
  82914. */
  82915. get: function () {
  82916. return this.onSecondaryButtonStateChangedObservable;
  82917. },
  82918. enumerable: true,
  82919. configurable: true
  82920. });
  82921. /**
  82922. * Called once for each button that changed state since the last frame
  82923. * Vive mapping:
  82924. * 0: touchpad
  82925. * 1: trigger
  82926. * 2: left AND right buttons
  82927. * 3: menu button
  82928. * @param buttonIdx Which button index changed
  82929. * @param state New state of the button
  82930. * @param changes Which properties on the state changed since last frame
  82931. */
  82932. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82933. var notifyObject = state; //{ state: state, changes: changes };
  82934. switch (buttonIdx) {
  82935. case 0:
  82936. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82937. return;
  82938. case 1: // index trigger
  82939. if (this._defaultModel) {
  82940. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  82941. }
  82942. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82943. return;
  82944. case 2: // left AND right button
  82945. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82946. return;
  82947. case 3:
  82948. if (this._defaultModel) {
  82949. if (notifyObject.pressed) {
  82950. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82951. }
  82952. else {
  82953. (this._defaultModel.getChildren()[2]).position.y = 0;
  82954. }
  82955. }
  82956. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82957. return;
  82958. }
  82959. };
  82960. /**
  82961. * Base Url for the controller model.
  82962. */
  82963. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  82964. /**
  82965. * File name for the controller model.
  82966. */
  82967. ViveController.MODEL_FILENAME = 'wand.babylon';
  82968. return ViveController;
  82969. }(BABYLON.WebVRController));
  82970. BABYLON.ViveController = ViveController;
  82971. })(BABYLON || (BABYLON = {}));
  82972. //# sourceMappingURL=babylon.viveController.js.map
  82973. var BABYLON;
  82974. (function (BABYLON) {
  82975. /**
  82976. * Generic Controller
  82977. */
  82978. var GenericController = /** @class */ (function (_super) {
  82979. __extends(GenericController, _super);
  82980. /**
  82981. * Creates a new GenericController from a gamepad
  82982. * @param vrGamepad the gamepad that the controller should be created from
  82983. */
  82984. function GenericController(vrGamepad) {
  82985. return _super.call(this, vrGamepad) || this;
  82986. }
  82987. /**
  82988. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82989. * @param scene scene in which to add meshes
  82990. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82991. */
  82992. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82993. var _this = this;
  82994. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  82995. _this._defaultModel = newMeshes[1];
  82996. _this.attachToMesh(_this._defaultModel);
  82997. if (meshLoaded) {
  82998. meshLoaded(_this._defaultModel);
  82999. }
  83000. });
  83001. };
  83002. /**
  83003. * Called once for each button that changed state since the last frame
  83004. * @param buttonIdx Which button index changed
  83005. * @param state New state of the button
  83006. * @param changes Which properties on the state changed since last frame
  83007. */
  83008. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83009. console.log("Button id: " + buttonIdx + "state: ");
  83010. console.dir(state);
  83011. };
  83012. /**
  83013. * Base Url for the controller model.
  83014. */
  83015. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83016. /**
  83017. * File name for the controller model.
  83018. */
  83019. GenericController.MODEL_FILENAME = 'generic.babylon';
  83020. return GenericController;
  83021. }(BABYLON.WebVRController));
  83022. BABYLON.GenericController = GenericController;
  83023. })(BABYLON || (BABYLON = {}));
  83024. //# sourceMappingURL=babylon.genericController.js.map
  83025. var BABYLON;
  83026. (function (BABYLON) {
  83027. /**
  83028. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  83029. */
  83030. var LoadedMeshInfo = /** @class */ (function () {
  83031. function LoadedMeshInfo() {
  83032. /**
  83033. * Map of the button meshes contained in the controller
  83034. */
  83035. this.buttonMeshes = {};
  83036. /**
  83037. * Map of the axis meshes contained in the controller
  83038. */
  83039. this.axisMeshes = {};
  83040. }
  83041. return LoadedMeshInfo;
  83042. }());
  83043. /**
  83044. * Defines the WindowsMotionController object that the state of the windows motion controller
  83045. */
  83046. var WindowsMotionController = /** @class */ (function (_super) {
  83047. __extends(WindowsMotionController, _super);
  83048. /**
  83049. * Creates a new WindowsMotionController from a gamepad
  83050. * @param vrGamepad the gamepad that the controller should be created from
  83051. */
  83052. function WindowsMotionController(vrGamepad) {
  83053. var _this = _super.call(this, vrGamepad) || this;
  83054. _this._mapping = {
  83055. // Semantic button names
  83056. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  83057. // A mapping of the button name to glTF model node name
  83058. // that should be transformed by button value.
  83059. buttonMeshNames: {
  83060. 'trigger': 'SELECT',
  83061. 'menu': 'MENU',
  83062. 'grip': 'GRASP',
  83063. 'thumbstick': 'THUMBSTICK_PRESS',
  83064. 'trackpad': 'TOUCHPAD_PRESS'
  83065. },
  83066. // This mapping is used to translate from the Motion Controller to Babylon semantics
  83067. buttonObservableNames: {
  83068. 'trigger': 'onTriggerStateChangedObservable',
  83069. 'menu': 'onSecondaryButtonStateChangedObservable',
  83070. 'grip': 'onMainButtonStateChangedObservable',
  83071. 'thumbstick': 'onPadStateChangedObservable',
  83072. 'trackpad': 'onTrackpadChangedObservable'
  83073. },
  83074. // A mapping of the axis name to glTF model node name
  83075. // that should be transformed by axis value.
  83076. // This array mirrors the browserGamepad.axes array, such that
  83077. // the mesh corresponding to axis 0 is in this array index 0.
  83078. axisMeshNames: [
  83079. 'THUMBSTICK_X',
  83080. 'THUMBSTICK_Y',
  83081. 'TOUCHPAD_TOUCH_X',
  83082. 'TOUCHPAD_TOUCH_Y'
  83083. ],
  83084. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  83085. };
  83086. /**
  83087. * Fired when the trackpad on this controller is clicked
  83088. */
  83089. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  83090. /**
  83091. * Fired when the trackpad on this controller is modified
  83092. */
  83093. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  83094. /**
  83095. * The current x and y values of this controller's trackpad
  83096. */
  83097. _this.trackpad = { x: 0, y: 0 };
  83098. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  83099. _this._loadedMeshInfo = null;
  83100. return _this;
  83101. }
  83102. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  83103. /**
  83104. * Fired when the trigger on this controller is modified
  83105. */
  83106. get: function () {
  83107. return this.onTriggerStateChangedObservable;
  83108. },
  83109. enumerable: true,
  83110. configurable: true
  83111. });
  83112. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  83113. /**
  83114. * Fired when the menu button on this controller is modified
  83115. */
  83116. get: function () {
  83117. return this.onSecondaryButtonStateChangedObservable;
  83118. },
  83119. enumerable: true,
  83120. configurable: true
  83121. });
  83122. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  83123. /**
  83124. * Fired when the grip button on this controller is modified
  83125. */
  83126. get: function () {
  83127. return this.onMainButtonStateChangedObservable;
  83128. },
  83129. enumerable: true,
  83130. configurable: true
  83131. });
  83132. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  83133. /**
  83134. * Fired when the thumbstick button on this controller is modified
  83135. */
  83136. get: function () {
  83137. return this.onPadStateChangedObservable;
  83138. },
  83139. enumerable: true,
  83140. configurable: true
  83141. });
  83142. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  83143. /**
  83144. * Fired when the touchpad button on this controller is modified
  83145. */
  83146. get: function () {
  83147. return this.onTrackpadChangedObservable;
  83148. },
  83149. enumerable: true,
  83150. configurable: true
  83151. });
  83152. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  83153. /**
  83154. * Fired when the touchpad values on this controller are modified
  83155. */
  83156. get: function () {
  83157. return this.onTrackpadValuesChangedObservable;
  83158. },
  83159. enumerable: true,
  83160. configurable: true
  83161. });
  83162. WindowsMotionController.prototype._updateTrackpad = function () {
  83163. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  83164. this.trackpad.x = this.browserGamepad["axes"][2];
  83165. this.trackpad.y = this.browserGamepad["axes"][3];
  83166. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  83167. }
  83168. };
  83169. /**
  83170. * Called once per frame by the engine.
  83171. */
  83172. WindowsMotionController.prototype.update = function () {
  83173. _super.prototype.update.call(this);
  83174. if (this.browserGamepad.axes) {
  83175. this._updateTrackpad();
  83176. // Only need to animate axes if there is a loaded mesh
  83177. if (this._loadedMeshInfo) {
  83178. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  83179. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  83180. }
  83181. }
  83182. }
  83183. };
  83184. /**
  83185. * Called once for each button that changed state since the last frame
  83186. * @param buttonIdx Which button index changed
  83187. * @param state New state of the button
  83188. * @param changes Which properties on the state changed since last frame
  83189. */
  83190. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83191. var buttonName = this._mapping.buttons[buttonIdx];
  83192. if (!buttonName) {
  83193. return;
  83194. }
  83195. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  83196. this._updateTrackpad();
  83197. // Only emit events for buttons that we know how to map from index to name
  83198. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  83199. if (observable) {
  83200. observable.notifyObservers(state);
  83201. }
  83202. this._lerpButtonTransform(buttonName, state.value);
  83203. };
  83204. /**
  83205. * Moves the buttons on the controller mesh based on their current state
  83206. * @param buttonName the name of the button to move
  83207. * @param buttonValue the value of the button which determines the buttons new position
  83208. */
  83209. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  83210. // If there is no loaded mesh, there is nothing to transform.
  83211. if (!this._loadedMeshInfo) {
  83212. return;
  83213. }
  83214. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  83215. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83216. return;
  83217. }
  83218. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  83219. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  83220. };
  83221. /**
  83222. * Moves the axis on the controller mesh based on its current state
  83223. * @param axis the index of the axis
  83224. * @param axisValue the value of the axis which determines the meshes new position
  83225. * @hidden
  83226. */
  83227. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  83228. if (!this._loadedMeshInfo) {
  83229. return;
  83230. }
  83231. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  83232. if (!meshInfo) {
  83233. return;
  83234. }
  83235. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83236. return;
  83237. }
  83238. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  83239. var lerpValue = axisValue * 0.5 + 0.5;
  83240. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  83241. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  83242. };
  83243. /**
  83244. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83245. * @param scene scene in which to add meshes
  83246. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83247. */
  83248. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  83249. var _this = this;
  83250. if (forceDefault === void 0) { forceDefault = false; }
  83251. var path;
  83252. var filename;
  83253. // Checking if GLB loader is present
  83254. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  83255. // Determine the device specific folder based on the ID suffix
  83256. var device = 'default';
  83257. if (this.id && !forceDefault) {
  83258. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  83259. device = ((match && match[0]) || device);
  83260. }
  83261. // Hand
  83262. if (this.hand === 'left') {
  83263. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  83264. }
  83265. else { // Right is the default if no hand is specified
  83266. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  83267. }
  83268. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  83269. }
  83270. else {
  83271. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  83272. path = BABYLON.GenericController.MODEL_BASE_URL;
  83273. filename = BABYLON.GenericController.MODEL_FILENAME;
  83274. }
  83275. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  83276. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  83277. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  83278. if (!_this._loadedMeshInfo) {
  83279. return;
  83280. }
  83281. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  83282. _this.attachToMesh(_this._defaultModel);
  83283. if (meshLoaded) {
  83284. meshLoaded(_this._defaultModel);
  83285. }
  83286. }, null, function (scene, message) {
  83287. BABYLON.Tools.Log(message);
  83288. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  83289. if (!forceDefault) {
  83290. _this.initControllerMesh(scene, meshLoaded, true);
  83291. }
  83292. });
  83293. };
  83294. /**
  83295. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  83296. * can be transformed by button presses and axes values, based on this._mapping.
  83297. *
  83298. * @param scene scene in which the meshes exist
  83299. * @param meshes list of meshes that make up the controller model to process
  83300. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  83301. */
  83302. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  83303. var loadedMeshInfo = null;
  83304. // Create a new mesh to contain the glTF hierarchy
  83305. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  83306. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  83307. var childMesh = null;
  83308. for (var i = 0; i < meshes.length; i++) {
  83309. var mesh = meshes[i];
  83310. if (!mesh.parent) {
  83311. // Exclude controller meshes from picking results
  83312. mesh.isPickable = false;
  83313. // Handle root node, attach to the new parentMesh
  83314. childMesh = mesh;
  83315. break;
  83316. }
  83317. }
  83318. if (childMesh) {
  83319. childMesh.setParent(parentMesh);
  83320. // Create our mesh info. Note that this method will always return non-null.
  83321. loadedMeshInfo = this.createMeshInfo(parentMesh);
  83322. }
  83323. else {
  83324. BABYLON.Tools.Warn('Could not find root node in model file.');
  83325. }
  83326. return loadedMeshInfo;
  83327. };
  83328. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  83329. var loadedMeshInfo = new LoadedMeshInfo();
  83330. var i;
  83331. loadedMeshInfo.rootNode = rootNode;
  83332. // Reset the caches
  83333. loadedMeshInfo.buttonMeshes = {};
  83334. loadedMeshInfo.axisMeshes = {};
  83335. // Button Meshes
  83336. for (i = 0; i < this._mapping.buttons.length; i++) {
  83337. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  83338. if (!buttonMeshName) {
  83339. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  83340. continue;
  83341. }
  83342. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  83343. if (!buttonMesh) {
  83344. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  83345. continue;
  83346. }
  83347. var buttonMeshInfo = {
  83348. index: i,
  83349. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  83350. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  83351. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  83352. };
  83353. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  83354. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  83355. }
  83356. else {
  83357. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  83358. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  83359. '(VALUE: ' + !!buttonMeshInfo.value +
  83360. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  83361. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  83362. ')');
  83363. }
  83364. }
  83365. // Axis Meshes
  83366. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  83367. var axisMeshName = this._mapping.axisMeshNames[i];
  83368. if (!axisMeshName) {
  83369. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  83370. continue;
  83371. }
  83372. var axisMesh = getChildByName(rootNode, axisMeshName);
  83373. if (!axisMesh) {
  83374. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  83375. continue;
  83376. }
  83377. var axisMeshInfo = {
  83378. index: i,
  83379. value: getImmediateChildByName(axisMesh, 'VALUE'),
  83380. min: getImmediateChildByName(axisMesh, 'MIN'),
  83381. max: getImmediateChildByName(axisMesh, 'MAX')
  83382. };
  83383. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  83384. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  83385. }
  83386. else {
  83387. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  83388. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  83389. '(VALUE: ' + !!axisMeshInfo.value +
  83390. ', MIN: ' + !!axisMeshInfo.min +
  83391. ', MAX:' + !!axisMeshInfo.max +
  83392. ')');
  83393. }
  83394. }
  83395. // Pointing Ray
  83396. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  83397. if (!loadedMeshInfo.pointingPoseNode) {
  83398. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  83399. }
  83400. else {
  83401. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  83402. }
  83403. return loadedMeshInfo;
  83404. // Look through all children recursively. This will return null if no mesh exists with the given name.
  83405. function getChildByName(node, name) {
  83406. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  83407. }
  83408. // Look through only immediate children. This will return null if no mesh exists with the given name.
  83409. function getImmediateChildByName(node, name) {
  83410. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  83411. }
  83412. };
  83413. /**
  83414. * Gets the ray of the controller in the direction the controller is pointing
  83415. * @param length the length the resulting ray should be
  83416. * @returns a ray in the direction the controller is pointing
  83417. */
  83418. WindowsMotionController.prototype.getForwardRay = function (length) {
  83419. if (length === void 0) { length = 100; }
  83420. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  83421. return _super.prototype.getForwardRay.call(this, length);
  83422. }
  83423. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  83424. var origin = m.getTranslation();
  83425. var forward = new BABYLON.Vector3(0, 0, -1);
  83426. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83427. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83428. return new BABYLON.Ray(origin, direction, length);
  83429. };
  83430. /**
  83431. * Disposes of the controller
  83432. */
  83433. WindowsMotionController.prototype.dispose = function () {
  83434. _super.prototype.dispose.call(this);
  83435. this.onTrackpadChangedObservable.clear();
  83436. };
  83437. /**
  83438. * The base url used to load the left and right controller models
  83439. */
  83440. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  83441. /**
  83442. * The name of the left controller model file
  83443. */
  83444. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  83445. /**
  83446. * The name of the right controller model file
  83447. */
  83448. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  83449. /**
  83450. * The controller name prefix for this controller type
  83451. */
  83452. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  83453. /**
  83454. * The controller id pattern for this controller type
  83455. */
  83456. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  83457. return WindowsMotionController;
  83458. }(BABYLON.WebVRController));
  83459. BABYLON.WindowsMotionController = WindowsMotionController;
  83460. })(BABYLON || (BABYLON = {}));
  83461. //# sourceMappingURL=babylon.windowsMotionController.js.map
  83462. var BABYLON;
  83463. (function (BABYLON) {
  83464. /**
  83465. * Gear VR Controller
  83466. */
  83467. var GearVRController = /** @class */ (function (_super) {
  83468. __extends(GearVRController, _super);
  83469. /**
  83470. * Creates a new GearVRController from a gamepad
  83471. * @param vrGamepad the gamepad that the controller should be created from
  83472. */
  83473. function GearVRController(vrGamepad) {
  83474. var _this = _super.call(this, vrGamepad) || this;
  83475. _this._buttonIndexToObservableNameMap = [
  83476. 'onTrackpadChangedObservable',
  83477. 'onTriggerStateChangedObservable' // Trigger
  83478. ];
  83479. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  83480. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  83481. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  83482. _this._disableTrackPosition(_this._calculatedPosition);
  83483. return _this;
  83484. }
  83485. /**
  83486. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83487. * @param scene scene in which to add meshes
  83488. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83489. */
  83490. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83491. var _this = this;
  83492. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  83493. // Offset the controller so it will rotate around the users wrist
  83494. var mesh = new BABYLON.Mesh("", scene);
  83495. newMeshes[1].parent = mesh;
  83496. newMeshes[1].position.z = -0.15;
  83497. _this._defaultModel = mesh;
  83498. _this.attachToMesh(_this._defaultModel);
  83499. if (meshLoaded) {
  83500. meshLoaded(_this._defaultModel);
  83501. }
  83502. });
  83503. };
  83504. /**
  83505. * Called once for each button that changed state since the last frame
  83506. * @param buttonIdx Which button index changed
  83507. * @param state New state of the button
  83508. * @param changes Which properties on the state changed since last frame
  83509. */
  83510. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83511. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  83512. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  83513. // Only emit events for buttons that we know how to map from index to observable
  83514. var observable = this[observableName];
  83515. if (observable) {
  83516. observable.notifyObservers(state);
  83517. }
  83518. }
  83519. };
  83520. /**
  83521. * Base Url for the controller model.
  83522. */
  83523. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83524. /**
  83525. * File name for the controller model.
  83526. */
  83527. GearVRController.MODEL_FILENAME = 'generic.babylon';
  83528. /**
  83529. * Gamepad Id prefix used to identify this controller.
  83530. */
  83531. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  83532. return GearVRController;
  83533. }(BABYLON.WebVRController));
  83534. BABYLON.GearVRController = GearVRController;
  83535. })(BABYLON || (BABYLON = {}));
  83536. //# sourceMappingURL=babylon.gearVRController.js.map
  83537. var BABYLON;
  83538. (function (BABYLON) {
  83539. /**
  83540. * Google Daydream controller
  83541. */
  83542. var DaydreamController = /** @class */ (function (_super) {
  83543. __extends(DaydreamController, _super);
  83544. /**
  83545. * Creates a new DaydreamController from a gamepad
  83546. * @param vrGamepad the gamepad that the controller should be created from
  83547. */
  83548. function DaydreamController(vrGamepad) {
  83549. var _this = _super.call(this, vrGamepad) || this;
  83550. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  83551. return _this;
  83552. }
  83553. /**
  83554. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83555. * @param scene scene in which to add meshes
  83556. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83557. */
  83558. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83559. var _this = this;
  83560. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  83561. _this._defaultModel = newMeshes[1];
  83562. _this.attachToMesh(_this._defaultModel);
  83563. if (meshLoaded) {
  83564. meshLoaded(_this._defaultModel);
  83565. }
  83566. });
  83567. };
  83568. /**
  83569. * Called once for each button that changed state since the last frame
  83570. * @param buttonIdx Which button index changed
  83571. * @param state New state of the button
  83572. * @param changes Which properties on the state changed since last frame
  83573. */
  83574. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83575. // Daydream controller only has 1 GamepadButton (on the trackpad).
  83576. if (buttonIdx === 0) {
  83577. var observable = this.onTriggerStateChangedObservable;
  83578. if (observable) {
  83579. observable.notifyObservers(state);
  83580. }
  83581. }
  83582. else {
  83583. // If the app or home buttons are ever made available
  83584. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  83585. }
  83586. };
  83587. /**
  83588. * Base Url for the controller model.
  83589. */
  83590. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83591. /**
  83592. * File name for the controller model.
  83593. */
  83594. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  83595. /**
  83596. * Gamepad Id prefix used to identify Daydream Controller.
  83597. */
  83598. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  83599. return DaydreamController;
  83600. }(BABYLON.WebVRController));
  83601. BABYLON.DaydreamController = DaydreamController;
  83602. })(BABYLON || (BABYLON = {}));
  83603. //# sourceMappingURL=babylon.daydreamController.js.map
  83604. var BABYLON;
  83605. (function (BABYLON) {
  83606. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  83607. get: function () {
  83608. if (!this._gamepadManager) {
  83609. this._gamepadManager = new BABYLON.GamepadManager(this);
  83610. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  83611. if (!component) {
  83612. component = new GamepadSystemSceneComponent(this);
  83613. this._addComponent(component);
  83614. }
  83615. }
  83616. return this._gamepadManager;
  83617. },
  83618. enumerable: true,
  83619. configurable: true
  83620. });
  83621. /**
  83622. * Adds a gamepad to the free camera inputs manager
  83623. */
  83624. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  83625. this.add(new BABYLON.FreeCameraGamepadInput());
  83626. return this;
  83627. };
  83628. /**
  83629. * Adds a gamepad to the arc rotate camera inputs manager
  83630. */
  83631. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  83632. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  83633. return this;
  83634. };
  83635. /**
  83636. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  83637. */
  83638. var GamepadSystemSceneComponent = /** @class */ (function () {
  83639. /**
  83640. * Creates a new instance of the component for the given scene
  83641. * @param scene Defines the scene to register the component in
  83642. */
  83643. function GamepadSystemSceneComponent(scene) {
  83644. /**
  83645. * The component name helpfull to identify the component in the list of scene components.
  83646. */
  83647. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  83648. this.scene = scene;
  83649. }
  83650. /**
  83651. * Registers the component in a given scene
  83652. */
  83653. GamepadSystemSceneComponent.prototype.register = function () {
  83654. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  83655. };
  83656. /**
  83657. * Rebuilds the elements related to this component in case of
  83658. * context lost for instance.
  83659. */
  83660. GamepadSystemSceneComponent.prototype.rebuild = function () {
  83661. // Nothing to do for gamepads
  83662. };
  83663. /**
  83664. * Disposes the component and the associated ressources
  83665. */
  83666. GamepadSystemSceneComponent.prototype.dispose = function () {
  83667. var gamepadManager = this.scene._gamepadManager;
  83668. if (gamepadManager) {
  83669. gamepadManager.dispose();
  83670. this.scene._gamepadManager = null;
  83671. }
  83672. };
  83673. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  83674. var gamepadManager = this.scene._gamepadManager;
  83675. if (gamepadManager && gamepadManager._isMonitoring) {
  83676. gamepadManager._checkGamepadsStatus();
  83677. }
  83678. };
  83679. return GamepadSystemSceneComponent;
  83680. }());
  83681. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  83682. })(BABYLON || (BABYLON = {}));
  83683. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  83684. var BABYLON;
  83685. (function (BABYLON) {
  83686. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  83687. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  83688. });
  83689. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  83690. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  83691. });
  83692. /**
  83693. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  83694. * an arc rotate version arcFollowCamera are available.
  83695. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83696. */
  83697. var FollowCamera = /** @class */ (function (_super) {
  83698. __extends(FollowCamera, _super);
  83699. /**
  83700. * Instantiates the follow camera.
  83701. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83702. * @param name Define the name of the camera in the scene
  83703. * @param position Define the position of the camera
  83704. * @param scene Define the scene the camera belong to
  83705. * @param lockedTarget Define the target of the camera
  83706. */
  83707. function FollowCamera(name, position, scene, lockedTarget) {
  83708. if (lockedTarget === void 0) { lockedTarget = null; }
  83709. var _this = _super.call(this, name, position, scene) || this;
  83710. /**
  83711. * Distance the follow camera should follow an object at
  83712. */
  83713. _this.radius = 12;
  83714. /**
  83715. * Define a rotation offset between the camera and the object it follows
  83716. */
  83717. _this.rotationOffset = 0;
  83718. /**
  83719. * Define a height offset between the camera and the object it follows.
  83720. * It can help following an object from the top (like a car chaing a plane)
  83721. */
  83722. _this.heightOffset = 4;
  83723. /**
  83724. * Define how fast the camera can accelerate to follow it s target.
  83725. */
  83726. _this.cameraAcceleration = 0.05;
  83727. /**
  83728. * Define the speed limit of the camera following an object.
  83729. */
  83730. _this.maxCameraSpeed = 20;
  83731. _this.lockedTarget = lockedTarget;
  83732. return _this;
  83733. }
  83734. FollowCamera.prototype._follow = function (cameraTarget) {
  83735. if (!cameraTarget) {
  83736. return;
  83737. }
  83738. var yRotation;
  83739. if (cameraTarget.rotationQuaternion) {
  83740. var rotMatrix = new BABYLON.Matrix();
  83741. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  83742. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  83743. }
  83744. else {
  83745. yRotation = cameraTarget.rotation.y;
  83746. }
  83747. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  83748. var targetPosition = cameraTarget.getAbsolutePosition();
  83749. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  83750. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  83751. var dx = targetX - this.position.x;
  83752. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  83753. var dz = (targetZ) - this.position.z;
  83754. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  83755. var vy = dy * this.cameraAcceleration;
  83756. var vz = dz * this.cameraAcceleration * 2;
  83757. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  83758. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83759. }
  83760. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  83761. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83762. }
  83763. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  83764. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83765. }
  83766. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  83767. this.setTarget(targetPosition);
  83768. };
  83769. /** @hidden */
  83770. FollowCamera.prototype._checkInputs = function () {
  83771. _super.prototype._checkInputs.call(this);
  83772. if (this.lockedTarget) {
  83773. this._follow(this.lockedTarget);
  83774. }
  83775. };
  83776. /**
  83777. * Gets the camera class name.
  83778. * @returns the class name
  83779. */
  83780. FollowCamera.prototype.getClassName = function () {
  83781. return "FollowCamera";
  83782. };
  83783. __decorate([
  83784. BABYLON.serialize()
  83785. ], FollowCamera.prototype, "radius", void 0);
  83786. __decorate([
  83787. BABYLON.serialize()
  83788. ], FollowCamera.prototype, "rotationOffset", void 0);
  83789. __decorate([
  83790. BABYLON.serialize()
  83791. ], FollowCamera.prototype, "heightOffset", void 0);
  83792. __decorate([
  83793. BABYLON.serialize()
  83794. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  83795. __decorate([
  83796. BABYLON.serialize()
  83797. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  83798. __decorate([
  83799. BABYLON.serializeAsMeshReference("lockedTargetId")
  83800. ], FollowCamera.prototype, "lockedTarget", void 0);
  83801. return FollowCamera;
  83802. }(BABYLON.TargetCamera));
  83803. BABYLON.FollowCamera = FollowCamera;
  83804. /**
  83805. * Arc Rotate version of the follow camera.
  83806. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  83807. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83808. */
  83809. var ArcFollowCamera = /** @class */ (function (_super) {
  83810. __extends(ArcFollowCamera, _super);
  83811. /**
  83812. * Instantiates a new ArcFollowCamera
  83813. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83814. * @param name Define the name of the camera
  83815. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  83816. * @param beta Define the rotation angle of the camera around the elevation axis
  83817. * @param radius Define the radius of the camera from its target point
  83818. * @param target Define the target of the camera
  83819. * @param scene Define the scene the camera belongs to
  83820. */
  83821. function ArcFollowCamera(name,
  83822. /** The longitudinal angle of the camera */
  83823. alpha,
  83824. /** The latitudinal angle of the camera */
  83825. beta,
  83826. /** The radius of the camera from its target */
  83827. radius,
  83828. /** Define the camera target (the messh it should follow) */
  83829. target, scene) {
  83830. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  83831. _this.alpha = alpha;
  83832. _this.beta = beta;
  83833. _this.radius = radius;
  83834. _this.target = target;
  83835. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  83836. _this._follow();
  83837. return _this;
  83838. }
  83839. ArcFollowCamera.prototype._follow = function () {
  83840. if (!this.target) {
  83841. return;
  83842. }
  83843. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  83844. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  83845. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  83846. var targetPosition = this.target.getAbsolutePosition();
  83847. this.position = targetPosition.add(this._cartesianCoordinates);
  83848. this.setTarget(targetPosition);
  83849. };
  83850. /** @hidden */
  83851. ArcFollowCamera.prototype._checkInputs = function () {
  83852. _super.prototype._checkInputs.call(this);
  83853. this._follow();
  83854. };
  83855. /**
  83856. * Returns the class name of the object.
  83857. * It is mostly used internally for serialization purposes.
  83858. */
  83859. ArcFollowCamera.prototype.getClassName = function () {
  83860. return "ArcFollowCamera";
  83861. };
  83862. return ArcFollowCamera;
  83863. }(BABYLON.TargetCamera));
  83864. BABYLON.ArcFollowCamera = ArcFollowCamera;
  83865. })(BABYLON || (BABYLON = {}));
  83866. //# sourceMappingURL=babylon.followCamera.js.map
  83867. var BABYLON;
  83868. (function (BABYLON) {
  83869. /**
  83870. * 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,
  83871. * which still works and will still be found in many Playgrounds.
  83872. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83873. */
  83874. var UniversalCamera = /** @class */ (function (_super) {
  83875. __extends(UniversalCamera, _super);
  83876. /**
  83877. * 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,
  83878. * which still works and will still be found in many Playgrounds.
  83879. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83880. * @param name Define the name of the camera in the scene
  83881. * @param position Define the start position of the camera in the scene
  83882. * @param scene Define the scene the camera belongs to
  83883. */
  83884. function UniversalCamera(name, position, scene) {
  83885. var _this = _super.call(this, name, position, scene) || this;
  83886. _this.inputs.addGamepad();
  83887. return _this;
  83888. }
  83889. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  83890. /**
  83891. * Defines the gamepad rotation sensiblity.
  83892. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  83893. */
  83894. get: function () {
  83895. var gamepad = this.inputs.attached["gamepad"];
  83896. if (gamepad) {
  83897. return gamepad.gamepadAngularSensibility;
  83898. }
  83899. return 0;
  83900. },
  83901. set: function (value) {
  83902. var gamepad = this.inputs.attached["gamepad"];
  83903. if (gamepad) {
  83904. gamepad.gamepadAngularSensibility = value;
  83905. }
  83906. },
  83907. enumerable: true,
  83908. configurable: true
  83909. });
  83910. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  83911. /**
  83912. * Defines the gamepad move sensiblity.
  83913. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  83914. */
  83915. get: function () {
  83916. var gamepad = this.inputs.attached["gamepad"];
  83917. if (gamepad) {
  83918. return gamepad.gamepadMoveSensibility;
  83919. }
  83920. return 0;
  83921. },
  83922. set: function (value) {
  83923. var gamepad = this.inputs.attached["gamepad"];
  83924. if (gamepad) {
  83925. gamepad.gamepadMoveSensibility = value;
  83926. }
  83927. },
  83928. enumerable: true,
  83929. configurable: true
  83930. });
  83931. /**
  83932. * Gets the current object class name.
  83933. * @return the class name
  83934. */
  83935. UniversalCamera.prototype.getClassName = function () {
  83936. return "UniversalCamera";
  83937. };
  83938. return UniversalCamera;
  83939. }(BABYLON.TouchCamera));
  83940. BABYLON.UniversalCamera = UniversalCamera;
  83941. })(BABYLON || (BABYLON = {}));
  83942. //# sourceMappingURL=babylon.universalCamera.js.map
  83943. var BABYLON;
  83944. (function (BABYLON) {
  83945. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  83946. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  83947. });
  83948. /**
  83949. * This represents a FPS type of camera. This is only here for back compat purpose.
  83950. * Please use the UniversalCamera instead as both are identical.
  83951. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83952. */
  83953. var GamepadCamera = /** @class */ (function (_super) {
  83954. __extends(GamepadCamera, _super);
  83955. /**
  83956. * Instantiates a new Gamepad Camera
  83957. * This represents a FPS type of camera. This is only here for back compat purpose.
  83958. * Please use the UniversalCamera instead as both are identical.
  83959. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83960. * @param name Define the name of the camera in the scene
  83961. * @param position Define the start position of the camera in the scene
  83962. * @param scene Define the scene the camera belongs to
  83963. */
  83964. function GamepadCamera(name, position, scene) {
  83965. return _super.call(this, name, position, scene) || this;
  83966. }
  83967. /**
  83968. * Gets the current object class name.
  83969. * @return the class name
  83970. */
  83971. GamepadCamera.prototype.getClassName = function () {
  83972. return "GamepadCamera";
  83973. };
  83974. return GamepadCamera;
  83975. }(BABYLON.UniversalCamera));
  83976. BABYLON.GamepadCamera = GamepadCamera;
  83977. })(BABYLON || (BABYLON = {}));
  83978. //# sourceMappingURL=babylon.gamepadCamera.js.map
  83979. var BABYLON;
  83980. (function (BABYLON) {
  83981. /**
  83982. * PostProcessRenderPipelineManager class
  83983. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83984. */
  83985. var PostProcessRenderPipelineManager = /** @class */ (function () {
  83986. /**
  83987. * Initializes a PostProcessRenderPipelineManager
  83988. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83989. */
  83990. function PostProcessRenderPipelineManager() {
  83991. this._renderPipelines = {};
  83992. }
  83993. /**
  83994. * Adds a pipeline to the manager
  83995. * @param renderPipeline The pipeline to add
  83996. */
  83997. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  83998. this._renderPipelines[renderPipeline._name] = renderPipeline;
  83999. };
  84000. /**
  84001. * Attaches a camera to the pipeline
  84002. * @param renderPipelineName The name of the pipeline to attach to
  84003. * @param cameras the camera to attach
  84004. * @param unique if the camera can be attached multiple times to the pipeline
  84005. */
  84006. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  84007. if (unique === void 0) { unique = false; }
  84008. var renderPipeline = this._renderPipelines[renderPipelineName];
  84009. if (!renderPipeline) {
  84010. return;
  84011. }
  84012. renderPipeline._attachCameras(cameras, unique);
  84013. };
  84014. /**
  84015. * Detaches a camera from the pipeline
  84016. * @param renderPipelineName The name of the pipeline to detach from
  84017. * @param cameras the camera to detach
  84018. */
  84019. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  84020. var renderPipeline = this._renderPipelines[renderPipelineName];
  84021. if (!renderPipeline) {
  84022. return;
  84023. }
  84024. renderPipeline._detachCameras(cameras);
  84025. };
  84026. /**
  84027. * Enables an effect by name on a pipeline
  84028. * @param renderPipelineName the name of the pipeline to enable the effect in
  84029. * @param renderEffectName the name of the effect to enable
  84030. * @param cameras the cameras that the effect should be enabled on
  84031. */
  84032. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  84033. var renderPipeline = this._renderPipelines[renderPipelineName];
  84034. if (!renderPipeline) {
  84035. return;
  84036. }
  84037. renderPipeline._enableEffect(renderEffectName, cameras);
  84038. };
  84039. /**
  84040. * Disables an effect by name on a pipeline
  84041. * @param renderPipelineName the name of the pipeline to disable the effect in
  84042. * @param renderEffectName the name of the effect to disable
  84043. * @param cameras the cameras that the effect should be disabled on
  84044. */
  84045. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  84046. var renderPipeline = this._renderPipelines[renderPipelineName];
  84047. if (!renderPipeline) {
  84048. return;
  84049. }
  84050. renderPipeline._disableEffect(renderEffectName, cameras);
  84051. };
  84052. /**
  84053. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  84054. */
  84055. PostProcessRenderPipelineManager.prototype.update = function () {
  84056. for (var renderPipelineName in this._renderPipelines) {
  84057. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84058. var pipeline = this._renderPipelines[renderPipelineName];
  84059. if (!pipeline.isSupported) {
  84060. pipeline.dispose();
  84061. delete this._renderPipelines[renderPipelineName];
  84062. }
  84063. else {
  84064. pipeline._update();
  84065. }
  84066. }
  84067. }
  84068. };
  84069. /** @hidden */
  84070. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  84071. for (var renderPipelineName in this._renderPipelines) {
  84072. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84073. var pipeline = this._renderPipelines[renderPipelineName];
  84074. pipeline._rebuild();
  84075. }
  84076. }
  84077. };
  84078. /**
  84079. * Disposes of the manager and pipelines
  84080. */
  84081. PostProcessRenderPipelineManager.prototype.dispose = function () {
  84082. for (var renderPipelineName in this._renderPipelines) {
  84083. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84084. var pipeline = this._renderPipelines[renderPipelineName];
  84085. pipeline.dispose();
  84086. }
  84087. }
  84088. };
  84089. return PostProcessRenderPipelineManager;
  84090. }());
  84091. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  84092. })(BABYLON || (BABYLON = {}));
  84093. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  84094. var BABYLON;
  84095. (function (BABYLON) {
  84096. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  84097. get: function () {
  84098. if (!this._postProcessRenderPipelineManager) {
  84099. // Register the G Buffer component to the scene.
  84100. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  84101. if (!component) {
  84102. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  84103. this._addComponent(component);
  84104. }
  84105. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  84106. }
  84107. return this._postProcessRenderPipelineManager;
  84108. },
  84109. enumerable: true,
  84110. configurable: true
  84111. });
  84112. /**
  84113. * Defines the Render Pipeline scene component responsible to rendering pipelines
  84114. */
  84115. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  84116. /**
  84117. * Creates a new instance of the component for the given scene
  84118. * @param scene Defines the scene to register the component in
  84119. */
  84120. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  84121. /**
  84122. * The component name helpfull to identify the component in the list of scene components.
  84123. */
  84124. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  84125. this.scene = scene;
  84126. }
  84127. /**
  84128. * Registers the component in a given scene
  84129. */
  84130. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  84131. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  84132. };
  84133. /**
  84134. * Rebuilds the elements related to this component in case of
  84135. * context lost for instance.
  84136. */
  84137. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  84138. if (this.scene._postProcessRenderPipelineManager) {
  84139. this.scene._postProcessRenderPipelineManager._rebuild();
  84140. }
  84141. };
  84142. /**
  84143. * Disposes the component and the associated ressources
  84144. */
  84145. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  84146. if (this.scene._postProcessRenderPipelineManager) {
  84147. this.scene._postProcessRenderPipelineManager.dispose();
  84148. }
  84149. };
  84150. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84151. if (this.scene._postProcessRenderPipelineManager) {
  84152. this.scene._postProcessRenderPipelineManager.update();
  84153. }
  84154. };
  84155. return PostProcessRenderPipelineManagerSceneComponent;
  84156. }());
  84157. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  84158. })(BABYLON || (BABYLON = {}));
  84159. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  84160. var BABYLON;
  84161. (function (BABYLON) {
  84162. /**
  84163. * This represents a set of one or more post processes in Babylon.
  84164. * A post process can be used to apply a shader to a texture after it is rendered.
  84165. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84166. */
  84167. var PostProcessRenderEffect = /** @class */ (function () {
  84168. /**
  84169. * Instantiates a post process render effect.
  84170. * A post process can be used to apply a shader to a texture after it is rendered.
  84171. * @param engine The engine the effect is tied to
  84172. * @param name The name of the effect
  84173. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  84174. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  84175. */
  84176. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  84177. this._name = name;
  84178. this._singleInstance = singleInstance || true;
  84179. this._getPostProcesses = getPostProcesses;
  84180. this._cameras = {};
  84181. this._indicesForCamera = {};
  84182. this._postProcesses = {};
  84183. }
  84184. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  84185. /**
  84186. * Checks if all the post processes in the effect are supported.
  84187. */
  84188. get: function () {
  84189. for (var index in this._postProcesses) {
  84190. if (this._postProcesses.hasOwnProperty(index)) {
  84191. var pps = this._postProcesses[index];
  84192. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  84193. if (!pps[ppIndex].isSupported) {
  84194. return false;
  84195. }
  84196. }
  84197. }
  84198. }
  84199. return true;
  84200. },
  84201. enumerable: true,
  84202. configurable: true
  84203. });
  84204. /**
  84205. * Updates the current state of the effect
  84206. * @hidden
  84207. */
  84208. PostProcessRenderEffect.prototype._update = function () {
  84209. };
  84210. /**
  84211. * Attaches the effect on cameras
  84212. * @param cameras The camera to attach to.
  84213. * @hidden
  84214. */
  84215. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  84216. var _this = this;
  84217. var cameraKey;
  84218. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84219. if (!cams) {
  84220. return;
  84221. }
  84222. for (var i = 0; i < cams.length; i++) {
  84223. var camera = cams[i];
  84224. var cameraName = camera.name;
  84225. if (this._singleInstance) {
  84226. cameraKey = 0;
  84227. }
  84228. else {
  84229. cameraKey = cameraName;
  84230. }
  84231. if (!this._postProcesses[cameraKey]) {
  84232. var postProcess = this._getPostProcesses();
  84233. if (postProcess) {
  84234. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  84235. }
  84236. }
  84237. if (!this._indicesForCamera[cameraName]) {
  84238. this._indicesForCamera[cameraName] = [];
  84239. }
  84240. this._postProcesses[cameraKey].forEach(function (postProcess) {
  84241. var index = camera.attachPostProcess(postProcess);
  84242. _this._indicesForCamera[cameraName].push(index);
  84243. });
  84244. if (!this._cameras[cameraName]) {
  84245. this._cameras[cameraName] = camera;
  84246. }
  84247. }
  84248. };
  84249. /**
  84250. * Detatches the effect on cameras
  84251. * @param cameras The camera to detatch from.
  84252. * @hidden
  84253. */
  84254. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  84255. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84256. if (!cams) {
  84257. return;
  84258. }
  84259. for (var i = 0; i < cams.length; i++) {
  84260. var camera = cams[i];
  84261. var cameraName = camera.name;
  84262. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84263. camera.detachPostProcess(postProcess);
  84264. });
  84265. if (this._cameras[cameraName]) {
  84266. //this._indicesForCamera.splice(index, 1);
  84267. this._cameras[cameraName] = null;
  84268. }
  84269. }
  84270. };
  84271. /**
  84272. * Enables the effect on given cameras
  84273. * @param cameras The camera to enable.
  84274. * @hidden
  84275. */
  84276. PostProcessRenderEffect.prototype._enable = function (cameras) {
  84277. var _this = this;
  84278. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84279. if (!cams) {
  84280. return;
  84281. }
  84282. for (var i = 0; i < cams.length; i++) {
  84283. var camera = cams[i];
  84284. var cameraName = camera.name;
  84285. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  84286. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  84287. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84288. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  84289. });
  84290. }
  84291. }
  84292. }
  84293. };
  84294. /**
  84295. * Disables the effect on the given cameras
  84296. * @param cameras The camera to disable.
  84297. * @hidden
  84298. */
  84299. PostProcessRenderEffect.prototype._disable = function (cameras) {
  84300. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84301. if (!cams) {
  84302. return;
  84303. }
  84304. for (var i = 0; i < cams.length; i++) {
  84305. var camera = cams[i];
  84306. var cameraName = camera.name;
  84307. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84308. camera.detachPostProcess(postProcess);
  84309. });
  84310. }
  84311. };
  84312. /**
  84313. * Gets a list of the post processes contained in the effect.
  84314. * @param camera The camera to get the post processes on.
  84315. * @returns The list of the post processes in the effect.
  84316. */
  84317. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  84318. if (this._singleInstance) {
  84319. return this._postProcesses[0];
  84320. }
  84321. else {
  84322. if (!camera) {
  84323. return null;
  84324. }
  84325. return this._postProcesses[camera.name];
  84326. }
  84327. };
  84328. return PostProcessRenderEffect;
  84329. }());
  84330. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  84331. })(BABYLON || (BABYLON = {}));
  84332. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  84333. var BABYLON;
  84334. (function (BABYLON) {
  84335. /**
  84336. * PostProcessRenderPipeline
  84337. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84338. */
  84339. var PostProcessRenderPipeline = /** @class */ (function () {
  84340. /**
  84341. * Initializes a PostProcessRenderPipeline
  84342. * @param engine engine to add the pipeline to
  84343. * @param name name of the pipeline
  84344. */
  84345. function PostProcessRenderPipeline(engine, name) {
  84346. this.engine = engine;
  84347. this._name = name;
  84348. this._renderEffects = {};
  84349. this._renderEffectsForIsolatedPass = new Array();
  84350. this._cameras = [];
  84351. }
  84352. /**
  84353. * "PostProcessRenderPipeline"
  84354. * @returns "PostProcessRenderPipeline"
  84355. */
  84356. PostProcessRenderPipeline.prototype.getClassName = function () {
  84357. return "PostProcessRenderPipeline";
  84358. };
  84359. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  84360. /**
  84361. * If all the render effects in the pipeline are support
  84362. */
  84363. get: function () {
  84364. for (var renderEffectName in this._renderEffects) {
  84365. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84366. if (!this._renderEffects[renderEffectName].isSupported) {
  84367. return false;
  84368. }
  84369. }
  84370. }
  84371. return true;
  84372. },
  84373. enumerable: true,
  84374. configurable: true
  84375. });
  84376. /**
  84377. * Adds an effect to the pipeline
  84378. * @param renderEffect the effect to add
  84379. */
  84380. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  84381. this._renderEffects[renderEffect._name] = renderEffect;
  84382. };
  84383. // private
  84384. /** @hidden */
  84385. PostProcessRenderPipeline.prototype._rebuild = function () {
  84386. };
  84387. /** @hidden */
  84388. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  84389. var renderEffects = this._renderEffects[renderEffectName];
  84390. if (!renderEffects) {
  84391. return;
  84392. }
  84393. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84394. };
  84395. /** @hidden */
  84396. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  84397. var renderEffects = this._renderEffects[renderEffectName];
  84398. if (!renderEffects) {
  84399. return;
  84400. }
  84401. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84402. };
  84403. /** @hidden */
  84404. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  84405. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84406. if (!cams) {
  84407. return;
  84408. }
  84409. var indicesToDelete = [];
  84410. var i;
  84411. for (i = 0; i < cams.length; i++) {
  84412. var camera = cams[i];
  84413. var cameraName = camera.name;
  84414. if (this._cameras.indexOf(camera) === -1) {
  84415. this._cameras[cameraName] = camera;
  84416. }
  84417. else if (unique) {
  84418. indicesToDelete.push(i);
  84419. }
  84420. }
  84421. for (i = 0; i < indicesToDelete.length; i++) {
  84422. cameras.splice(indicesToDelete[i], 1);
  84423. }
  84424. for (var renderEffectName in this._renderEffects) {
  84425. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84426. this._renderEffects[renderEffectName]._attachCameras(cams);
  84427. }
  84428. }
  84429. };
  84430. /** @hidden */
  84431. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  84432. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84433. if (!cams) {
  84434. return;
  84435. }
  84436. for (var renderEffectName in this._renderEffects) {
  84437. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84438. this._renderEffects[renderEffectName]._detachCameras(cams);
  84439. }
  84440. }
  84441. for (var i = 0; i < cams.length; i++) {
  84442. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  84443. }
  84444. };
  84445. /** @hidden */
  84446. PostProcessRenderPipeline.prototype._update = function () {
  84447. for (var renderEffectName in this._renderEffects) {
  84448. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84449. this._renderEffects[renderEffectName]._update();
  84450. }
  84451. }
  84452. for (var i = 0; i < this._cameras.length; i++) {
  84453. var cameraName = this._cameras[i].name;
  84454. if (this._renderEffectsForIsolatedPass[cameraName]) {
  84455. this._renderEffectsForIsolatedPass[cameraName]._update();
  84456. }
  84457. }
  84458. };
  84459. /** @hidden */
  84460. PostProcessRenderPipeline.prototype._reset = function () {
  84461. this._renderEffects = {};
  84462. this._renderEffectsForIsolatedPass = new Array();
  84463. };
  84464. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  84465. // 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)
  84466. var effectKeys = Object.keys(this._renderEffects);
  84467. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  84468. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  84469. if (postProcesses) {
  84470. postProcesses[0].samples = sampleCount;
  84471. return true;
  84472. }
  84473. }
  84474. return false;
  84475. };
  84476. /**
  84477. * Disposes of the pipeline
  84478. */
  84479. PostProcessRenderPipeline.prototype.dispose = function () {
  84480. // Must be implemented by children
  84481. };
  84482. __decorate([
  84483. BABYLON.serialize()
  84484. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  84485. return PostProcessRenderPipeline;
  84486. }());
  84487. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  84488. })(BABYLON || (BABYLON = {}));
  84489. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  84490. var BABYLON;
  84491. (function (BABYLON) {
  84492. /**
  84493. * This represents a depth renderer in Babylon.
  84494. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  84495. */
  84496. var DepthRenderer = /** @class */ (function () {
  84497. /**
  84498. * Instantiates a depth renderer
  84499. * @param scene The scene the renderer belongs to
  84500. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  84501. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  84502. */
  84503. function DepthRenderer(scene, type, camera) {
  84504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  84505. if (camera === void 0) { camera = null; }
  84506. var _this = this;
  84507. /**
  84508. * Specifiess that the depth renderer will only be used within
  84509. * the camera it is created for.
  84510. * This can help forcing its rendering during the camera processing.
  84511. */
  84512. this.useOnlyInActiveCamera = false;
  84513. this._scene = scene;
  84514. // Register the G Buffer component to the scene.
  84515. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  84516. if (!component) {
  84517. component = new BABYLON.DepthRendererSceneComponent(scene);
  84518. scene._addComponent(component);
  84519. }
  84520. this._camera = camera;
  84521. var engine = scene.getEngine();
  84522. // Render target
  84523. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  84524. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84525. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84526. this._depthMap.refreshRate = 1;
  84527. this._depthMap.renderParticles = false;
  84528. this._depthMap.renderList = null;
  84529. // Camera to get depth map from to support multiple concurrent cameras
  84530. this._depthMap.activeCamera = this._camera;
  84531. this._depthMap.ignoreCameraViewport = true;
  84532. this._depthMap.useCameraPostProcesses = false;
  84533. // set default depth value to 1.0 (far away)
  84534. this._depthMap.onClearObservable.add(function (engine) {
  84535. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  84536. });
  84537. // Custom render function
  84538. var renderSubMesh = function (subMesh) {
  84539. var mesh = subMesh.getRenderingMesh();
  84540. var scene = _this._scene;
  84541. var engine = scene.getEngine();
  84542. var material = subMesh.getMaterial();
  84543. if (!material) {
  84544. return;
  84545. }
  84546. // Culling and reverse (right handed system)
  84547. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84548. // Managing instances
  84549. var batch = mesh._getInstancesRenderList(subMesh._id);
  84550. if (batch.mustReturn) {
  84551. return;
  84552. }
  84553. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84554. var camera = _this._camera || scene.activeCamera;
  84555. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  84556. engine.enableEffect(_this._effect);
  84557. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84558. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84559. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  84560. // Alpha test
  84561. if (material && material.needAlphaTesting()) {
  84562. var alphaTexture = material.getAlphaTestTexture();
  84563. if (alphaTexture) {
  84564. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84565. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84566. }
  84567. }
  84568. // Bones
  84569. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84570. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84571. }
  84572. // Draw
  84573. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  84574. }
  84575. };
  84576. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84577. var index;
  84578. if (depthOnlySubMeshes.length) {
  84579. engine.setColorWrite(false);
  84580. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84581. renderSubMesh(depthOnlySubMeshes.data[index]);
  84582. }
  84583. engine.setColorWrite(true);
  84584. }
  84585. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84586. renderSubMesh(opaqueSubMeshes.data[index]);
  84587. }
  84588. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84589. renderSubMesh(alphaTestSubMeshes.data[index]);
  84590. }
  84591. };
  84592. }
  84593. /**
  84594. * Creates the depth rendering effect and checks if the effect is ready.
  84595. * @param subMesh The submesh to be used to render the depth map of
  84596. * @param useInstances If multiple world instances should be used
  84597. * @returns if the depth renderer is ready to render the depth map
  84598. */
  84599. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  84600. var material = subMesh.getMaterial();
  84601. if (material.disableDepthWrite) {
  84602. return false;
  84603. }
  84604. var defines = [];
  84605. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84606. var mesh = subMesh.getMesh();
  84607. // Alpha test
  84608. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  84609. defines.push("#define ALPHATEST");
  84610. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84611. attribs.push(BABYLON.VertexBuffer.UVKind);
  84612. defines.push("#define UV1");
  84613. }
  84614. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84615. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84616. defines.push("#define UV2");
  84617. }
  84618. }
  84619. // Bones
  84620. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84621. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84622. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84623. if (mesh.numBoneInfluencers > 4) {
  84624. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84625. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84626. }
  84627. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84628. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84629. }
  84630. else {
  84631. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84632. }
  84633. // Instances
  84634. if (useInstances) {
  84635. defines.push("#define INSTANCES");
  84636. attribs.push("world0");
  84637. attribs.push("world1");
  84638. attribs.push("world2");
  84639. attribs.push("world3");
  84640. }
  84641. // Get correct effect
  84642. var join = defines.join("\n");
  84643. if (this._cachedDefines !== join) {
  84644. this._cachedDefines = join;
  84645. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  84646. }
  84647. return this._effect.isReady();
  84648. };
  84649. /**
  84650. * Gets the texture which the depth map will be written to.
  84651. * @returns The depth map texture
  84652. */
  84653. DepthRenderer.prototype.getDepthMap = function () {
  84654. return this._depthMap;
  84655. };
  84656. /**
  84657. * Disposes of the depth renderer.
  84658. */
  84659. DepthRenderer.prototype.dispose = function () {
  84660. this._depthMap.dispose();
  84661. };
  84662. return DepthRenderer;
  84663. }());
  84664. BABYLON.DepthRenderer = DepthRenderer;
  84665. })(BABYLON || (BABYLON = {}));
  84666. //# sourceMappingURL=babylon.depthRenderer.js.map
  84667. var BABYLON;
  84668. (function (BABYLON) {
  84669. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  84670. camera = camera || this.activeCamera;
  84671. if (!camera) {
  84672. throw "No camera available to enable depth renderer";
  84673. }
  84674. if (!this._depthRenderer) {
  84675. this._depthRenderer = {};
  84676. }
  84677. if (!this._depthRenderer[camera.id]) {
  84678. var textureType = 0;
  84679. if (this.getEngine().getCaps().textureHalfFloatRender) {
  84680. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84681. }
  84682. else if (this.getEngine().getCaps().textureFloatRender) {
  84683. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84684. }
  84685. else {
  84686. throw "Depth renderer does not support int texture type";
  84687. }
  84688. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  84689. }
  84690. return this._depthRenderer[camera.id];
  84691. };
  84692. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  84693. camera = camera || this.activeCamera;
  84694. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  84695. return;
  84696. }
  84697. this._depthRenderer[camera.id].dispose();
  84698. delete this._depthRenderer[camera.id];
  84699. };
  84700. /**
  84701. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  84702. * in several rendering techniques.
  84703. */
  84704. var DepthRendererSceneComponent = /** @class */ (function () {
  84705. /**
  84706. * Creates a new instance of the component for the given scene
  84707. * @param scene Defines the scene to register the component in
  84708. */
  84709. function DepthRendererSceneComponent(scene) {
  84710. /**
  84711. * The component name helpfull to identify the component in the list of scene components.
  84712. */
  84713. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  84714. this.scene = scene;
  84715. }
  84716. /**
  84717. * Registers the component in a given scene
  84718. */
  84719. DepthRendererSceneComponent.prototype.register = function () {
  84720. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  84721. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  84722. };
  84723. /**
  84724. * Rebuilds the elements related to this component in case of
  84725. * context lost for instance.
  84726. */
  84727. DepthRendererSceneComponent.prototype.rebuild = function () {
  84728. // Nothing to do for this component
  84729. };
  84730. /**
  84731. * Disposes the component and the associated ressources
  84732. */
  84733. DepthRendererSceneComponent.prototype.dispose = function () {
  84734. for (var key in this.scene._depthRenderer) {
  84735. this.scene._depthRenderer[key].dispose();
  84736. }
  84737. };
  84738. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84739. if (this.scene._depthRenderer) {
  84740. for (var key in this.scene._depthRenderer) {
  84741. var depthRenderer = this.scene._depthRenderer[key];
  84742. if (!depthRenderer.useOnlyInActiveCamera) {
  84743. renderTargets.push(depthRenderer.getDepthMap());
  84744. }
  84745. }
  84746. }
  84747. };
  84748. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  84749. if (this.scene._depthRenderer) {
  84750. for (var key in this.scene._depthRenderer) {
  84751. var depthRenderer = this.scene._depthRenderer[key];
  84752. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  84753. renderTargets.push(depthRenderer.getDepthMap());
  84754. }
  84755. }
  84756. }
  84757. };
  84758. return DepthRendererSceneComponent;
  84759. }());
  84760. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  84761. })(BABYLON || (BABYLON = {}));
  84762. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  84763. var BABYLON;
  84764. (function (BABYLON) {
  84765. /**
  84766. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  84767. */
  84768. var GeometryBufferRenderer = /** @class */ (function () {
  84769. /**
  84770. * Creates a new G Buffer for the scene
  84771. * @param scene The scene the buffer belongs to
  84772. * @param ratio How big is the buffer related to the main canvas.
  84773. */
  84774. function GeometryBufferRenderer(scene, ratio) {
  84775. if (ratio === void 0) { ratio = 1; }
  84776. /**
  84777. * Dictionary used to store the previous transformation matrices of each rendered mesh
  84778. * in order to compute objects velocities when enableVelocity is set to "true"
  84779. * @hidden
  84780. */
  84781. this._previousTransformationMatrices = {};
  84782. this._enablePosition = false;
  84783. this._enableVelocity = false;
  84784. this._positionIndex = -1;
  84785. this._velocityIndex = -1;
  84786. this._scene = scene;
  84787. this._ratio = ratio;
  84788. // Register the G Buffer component to the scene.
  84789. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  84790. if (!component) {
  84791. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  84792. scene._addComponent(component);
  84793. }
  84794. // Render target
  84795. this._createRenderTargets();
  84796. }
  84797. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  84798. /**
  84799. * Set the render list (meshes to be rendered) used in the G buffer.
  84800. */
  84801. set: function (meshes) {
  84802. this._multiRenderTarget.renderList = meshes;
  84803. },
  84804. enumerable: true,
  84805. configurable: true
  84806. });
  84807. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  84808. /**
  84809. * Gets wether or not G buffer are supported by the running hardware.
  84810. * This requires draw buffer supports
  84811. */
  84812. get: function () {
  84813. return this._multiRenderTarget.isSupported;
  84814. },
  84815. enumerable: true,
  84816. configurable: true
  84817. });
  84818. /**
  84819. * Returns the index of the given texture type in the G-Buffer textures array
  84820. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  84821. * @returns the index of the given texture type in the G-Buffer textures array
  84822. */
  84823. GeometryBufferRenderer.prototype.getTextureIndex = function (textureType) {
  84824. switch (textureType) {
  84825. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  84826. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  84827. default: return -1;
  84828. }
  84829. };
  84830. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  84831. /**
  84832. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  84833. */
  84834. get: function () {
  84835. return this._enablePosition;
  84836. },
  84837. /**
  84838. * Sets whether or not objects positions are enabled for the G buffer.
  84839. */
  84840. set: function (enable) {
  84841. this._enablePosition = enable;
  84842. this.dispose();
  84843. this._createRenderTargets();
  84844. },
  84845. enumerable: true,
  84846. configurable: true
  84847. });
  84848. Object.defineProperty(GeometryBufferRenderer.prototype, "enableVelocity", {
  84849. /**
  84850. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  84851. */
  84852. get: function () {
  84853. return this._enableVelocity;
  84854. },
  84855. /**
  84856. * Sets wether or not objects velocities are enabled for the G buffer.
  84857. */
  84858. set: function (enable) {
  84859. this._enableVelocity = enable;
  84860. this.dispose();
  84861. this._createRenderTargets();
  84862. },
  84863. enumerable: true,
  84864. configurable: true
  84865. });
  84866. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  84867. /**
  84868. * Gets the scene associated with the buffer.
  84869. */
  84870. get: function () {
  84871. return this._scene;
  84872. },
  84873. enumerable: true,
  84874. configurable: true
  84875. });
  84876. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  84877. /**
  84878. * Gets the ratio used by the buffer during its creation.
  84879. * How big is the buffer related to the main canvas.
  84880. */
  84881. get: function () {
  84882. return this._ratio;
  84883. },
  84884. enumerable: true,
  84885. configurable: true
  84886. });
  84887. /**
  84888. * Checks wether everything is ready to render a submesh to the G buffer.
  84889. * @param subMesh the submesh to check readiness for
  84890. * @param useInstances is the mesh drawn using instance or not
  84891. * @returns true if ready otherwise false
  84892. */
  84893. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  84894. var material = subMesh.getMaterial();
  84895. if (material && material.disableDepthWrite) {
  84896. return false;
  84897. }
  84898. var defines = [];
  84899. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84900. var mesh = subMesh.getMesh();
  84901. // Alpha test
  84902. if (material && material.needAlphaTesting()) {
  84903. defines.push("#define ALPHATEST");
  84904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84905. attribs.push(BABYLON.VertexBuffer.UVKind);
  84906. defines.push("#define UV1");
  84907. }
  84908. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84909. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84910. defines.push("#define UV2");
  84911. }
  84912. }
  84913. // Buffers
  84914. if (this._enablePosition) {
  84915. defines.push("#define POSITION");
  84916. defines.push("#define POSITION_INDEX " + this._positionIndex);
  84917. }
  84918. if (this._enableVelocity) {
  84919. defines.push("#define VELOCITY");
  84920. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  84921. }
  84922. // Bones
  84923. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84924. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84925. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84926. if (mesh.numBoneInfluencers > 4) {
  84927. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84928. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84929. }
  84930. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84931. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84932. }
  84933. else {
  84934. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84935. }
  84936. // Instances
  84937. if (useInstances) {
  84938. defines.push("#define INSTANCES");
  84939. attribs.push("world0");
  84940. attribs.push("world1");
  84941. attribs.push("world2");
  84942. attribs.push("world3");
  84943. }
  84944. // Setup textures count
  84945. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  84946. // Get correct effect
  84947. var join = defines.join("\n");
  84948. if (this._cachedDefines !== join) {
  84949. this._cachedDefines = join;
  84950. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorldViewProjection"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  84951. }
  84952. return this._effect.isReady();
  84953. };
  84954. /**
  84955. * Gets the current underlying G Buffer.
  84956. * @returns the buffer
  84957. */
  84958. GeometryBufferRenderer.prototype.getGBuffer = function () {
  84959. return this._multiRenderTarget;
  84960. };
  84961. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  84962. /**
  84963. * Gets the number of samples used to render the buffer (anti aliasing).
  84964. */
  84965. get: function () {
  84966. return this._multiRenderTarget.samples;
  84967. },
  84968. /**
  84969. * Sets the number of samples used to render the buffer (anti aliasing).
  84970. */
  84971. set: function (value) {
  84972. this._multiRenderTarget.samples = value;
  84973. },
  84974. enumerable: true,
  84975. configurable: true
  84976. });
  84977. /**
  84978. * Disposes the renderer and frees up associated resources.
  84979. */
  84980. GeometryBufferRenderer.prototype.dispose = function () {
  84981. this.getGBuffer().dispose();
  84982. };
  84983. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  84984. var _this = this;
  84985. var engine = this._scene.getEngine();
  84986. var count = 2;
  84987. if (this._enablePosition) {
  84988. this._positionIndex = count;
  84989. count++;
  84990. }
  84991. if (this._enableVelocity) {
  84992. this._velocityIndex = count;
  84993. count++;
  84994. }
  84995. 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 });
  84996. if (!this.isSupported) {
  84997. return;
  84998. }
  84999. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85000. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85001. this._multiRenderTarget.refreshRate = 1;
  85002. this._multiRenderTarget.renderParticles = false;
  85003. this._multiRenderTarget.renderList = null;
  85004. // set default depth value to 1.0 (far away)
  85005. this._multiRenderTarget.onClearObservable.add(function (engine) {
  85006. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  85007. });
  85008. // Custom render function
  85009. var renderSubMesh = function (subMesh) {
  85010. var mesh = subMesh.getRenderingMesh();
  85011. var scene = _this._scene;
  85012. var engine = scene.getEngine();
  85013. var material = subMesh.getMaterial();
  85014. if (!material) {
  85015. return;
  85016. }
  85017. // Velocity
  85018. if (!_this._previousTransformationMatrices[mesh.uniqueId]) {
  85019. _this._previousTransformationMatrices[mesh.uniqueId] = BABYLON.Matrix.Identity();
  85020. }
  85021. // Culling
  85022. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  85023. // Managing instances
  85024. var batch = mesh._getInstancesRenderList(subMesh._id);
  85025. if (batch.mustReturn) {
  85026. return;
  85027. }
  85028. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85029. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  85030. engine.enableEffect(_this._effect);
  85031. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  85032. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85033. _this._effect.setMatrix("view", scene.getViewMatrix());
  85034. // Alpha test
  85035. if (material && material.needAlphaTesting()) {
  85036. var alphaTexture = material.getAlphaTestTexture();
  85037. if (alphaTexture) {
  85038. _this._effect.setTexture("diffuseSampler", alphaTexture);
  85039. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85040. }
  85041. }
  85042. // Bones
  85043. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85044. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85045. }
  85046. // Velocity
  85047. _this._effect.setMatrix("previousWorldViewProjection", _this._previousTransformationMatrices[mesh.uniqueId]);
  85048. // Draw
  85049. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  85050. }
  85051. // Velocity
  85052. _this._previousTransformationMatrices[mesh.uniqueId] = mesh.getWorldMatrix().multiply(_this._scene.getTransformMatrix());
  85053. };
  85054. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85055. var index;
  85056. if (depthOnlySubMeshes.length) {
  85057. engine.setColorWrite(false);
  85058. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85059. renderSubMesh(depthOnlySubMeshes.data[index]);
  85060. }
  85061. engine.setColorWrite(true);
  85062. }
  85063. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85064. renderSubMesh(opaqueSubMeshes.data[index]);
  85065. }
  85066. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85067. renderSubMesh(alphaTestSubMeshes.data[index]);
  85068. }
  85069. };
  85070. };
  85071. /**
  85072. * Constant used to retrieve the position texture index in the G-Buffer textures array
  85073. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  85074. */
  85075. GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 1;
  85076. /**
  85077. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  85078. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  85079. */
  85080. GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 2;
  85081. return GeometryBufferRenderer;
  85082. }());
  85083. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  85084. })(BABYLON || (BABYLON = {}));
  85085. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  85086. var BABYLON;
  85087. (function (BABYLON) {
  85088. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  85089. get: function () {
  85090. this._geometryBufferRenderer;
  85091. },
  85092. set: function (value) {
  85093. if (value && value.isSupported) {
  85094. this._geometryBufferRenderer = value;
  85095. }
  85096. },
  85097. enumerable: true,
  85098. configurable: true
  85099. });
  85100. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  85101. if (ratio === void 0) { ratio = 1; }
  85102. if (this._geometryBufferRenderer) {
  85103. return this._geometryBufferRenderer;
  85104. }
  85105. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  85106. if (!this._geometryBufferRenderer.isSupported) {
  85107. this._geometryBufferRenderer = null;
  85108. }
  85109. return this._geometryBufferRenderer;
  85110. };
  85111. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  85112. if (!this._geometryBufferRenderer) {
  85113. return;
  85114. }
  85115. this._geometryBufferRenderer.dispose();
  85116. this._geometryBufferRenderer = null;
  85117. };
  85118. /**
  85119. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  85120. * in several rendering techniques.
  85121. */
  85122. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  85123. /**
  85124. * Creates a new instance of the component for the given scene
  85125. * @param scene Defines the scene to register the component in
  85126. */
  85127. function GeometryBufferRendererSceneComponent(scene) {
  85128. /**
  85129. * The component name helpful to identify the component in the list of scene components.
  85130. */
  85131. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  85132. this.scene = scene;
  85133. }
  85134. /**
  85135. * Registers the component in a given scene
  85136. */
  85137. GeometryBufferRendererSceneComponent.prototype.register = function () {
  85138. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  85139. };
  85140. /**
  85141. * Rebuilds the elements related to this component in case of
  85142. * context lost for instance.
  85143. */
  85144. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  85145. // Nothing to do for this component
  85146. };
  85147. /**
  85148. * Disposes the component and the associated ressources
  85149. */
  85150. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  85151. // Nothing to do for this component
  85152. };
  85153. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85154. if (this.scene._geometryBufferRenderer) {
  85155. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  85156. }
  85157. };
  85158. return GeometryBufferRendererSceneComponent;
  85159. }());
  85160. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  85161. })(BABYLON || (BABYLON = {}));
  85162. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  85163. var BABYLON;
  85164. (function (BABYLON) {
  85165. /**
  85166. * Render pipeline to produce ssao effect
  85167. */
  85168. var SSAORenderingPipeline = /** @class */ (function (_super) {
  85169. __extends(SSAORenderingPipeline, _super);
  85170. /**
  85171. * @constructor
  85172. * @param name - The rendering pipeline name
  85173. * @param scene - The scene linked to this pipeline
  85174. * @param 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 }
  85175. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  85176. */
  85177. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  85178. var _this = _super.call(this, scene.getEngine(), name) || this;
  85179. // Members
  85180. /**
  85181. * @ignore
  85182. * The PassPostProcess id in the pipeline that contains the original scene color
  85183. */
  85184. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85185. /**
  85186. * @ignore
  85187. * The SSAO PostProcess id in the pipeline
  85188. */
  85189. _this.SSAORenderEffect = "SSAORenderEffect";
  85190. /**
  85191. * @ignore
  85192. * The horizontal blur PostProcess id in the pipeline
  85193. */
  85194. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85195. /**
  85196. * @ignore
  85197. * The vertical blur PostProcess id in the pipeline
  85198. */
  85199. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85200. /**
  85201. * @ignore
  85202. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85203. */
  85204. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85205. /**
  85206. * The output strength of the SSAO post-process. Default value is 1.0.
  85207. */
  85208. _this.totalStrength = 1.0;
  85209. /**
  85210. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  85211. */
  85212. _this.radius = 0.0001;
  85213. /**
  85214. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  85215. * Must not be equal to fallOff and superior to fallOff.
  85216. * Default value is 0.975
  85217. */
  85218. _this.area = 0.0075;
  85219. /**
  85220. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  85221. * Must not be equal to area and inferior to area.
  85222. * Default value is 0.0
  85223. */
  85224. _this.fallOff = 0.000001;
  85225. /**
  85226. * The base color of the SSAO post-process
  85227. * The final result is "base + ssao" between [0, 1]
  85228. */
  85229. _this.base = 0.5;
  85230. _this._firstUpdate = true;
  85231. _this._scene = scene;
  85232. // Set up assets
  85233. _this._createRandomTexture();
  85234. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85235. var ssaoRatio = ratio.ssaoRatio || ratio;
  85236. var combineRatio = ratio.combineRatio || ratio;
  85237. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85238. _this._createSSAOPostProcess(ssaoRatio);
  85239. _this._createBlurPostProcess(ssaoRatio);
  85240. _this._createSSAOCombinePostProcess(combineRatio);
  85241. // Set up pipeline
  85242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85243. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85244. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85245. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85246. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85247. // Finish
  85248. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85249. if (cameras) {
  85250. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85251. }
  85252. return _this;
  85253. }
  85254. // Public Methods
  85255. /**
  85256. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85257. */
  85258. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85259. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85260. for (var i = 0; i < this._scene.cameras.length; i++) {
  85261. var camera = this._scene.cameras[i];
  85262. this._originalColorPostProcess.dispose(camera);
  85263. this._ssaoPostProcess.dispose(camera);
  85264. this._blurHPostProcess.dispose(camera);
  85265. this._blurVPostProcess.dispose(camera);
  85266. this._ssaoCombinePostProcess.dispose(camera);
  85267. }
  85268. this._randomTexture.dispose();
  85269. if (disableDepthRender) {
  85270. this._scene.disableDepthRenderer();
  85271. }
  85272. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85273. _super.prototype.dispose.call(this);
  85274. };
  85275. // Private Methods
  85276. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  85277. var _this = this;
  85278. var size = 16;
  85279. 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);
  85280. 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);
  85281. this._blurHPostProcess.onActivateObservable.add(function () {
  85282. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  85283. _this._blurHPostProcess.kernel = size * dw;
  85284. });
  85285. this._blurVPostProcess.onActivateObservable.add(function () {
  85286. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  85287. _this._blurVPostProcess.kernel = size * dw;
  85288. });
  85289. };
  85290. /** @hidden */
  85291. SSAORenderingPipeline.prototype._rebuild = function () {
  85292. this._firstUpdate = true;
  85293. _super.prototype._rebuild.call(this);
  85294. };
  85295. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85296. var _this = this;
  85297. var numSamples = 16;
  85298. var sampleSphere = [
  85299. 0.5381, 0.1856, -0.4319,
  85300. 0.1379, 0.2486, 0.4430,
  85301. 0.3371, 0.5679, -0.0057,
  85302. -0.6999, -0.0451, -0.0019,
  85303. 0.0689, -0.1598, -0.8547,
  85304. 0.0560, 0.0069, -0.1843,
  85305. -0.0146, 0.1402, 0.0762,
  85306. 0.0100, -0.1924, -0.0344,
  85307. -0.3577, -0.5301, -0.4358,
  85308. -0.3169, 0.1063, 0.0158,
  85309. 0.0103, -0.5869, 0.0046,
  85310. -0.0897, -0.4940, 0.3287,
  85311. 0.7119, -0.0154, -0.0918,
  85312. -0.0533, 0.0596, -0.5411,
  85313. 0.0352, -0.0631, 0.5460,
  85314. -0.4776, 0.2847, -0.0271
  85315. ];
  85316. var samplesFactor = 1.0 / numSamples;
  85317. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  85318. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85319. "area", "fallOff", "base", "range", "viewport"
  85320. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85321. this._ssaoPostProcess.onApply = function (effect) {
  85322. if (_this._firstUpdate) {
  85323. effect.setArray3("sampleSphere", sampleSphere);
  85324. effect.setFloat("samplesFactor", samplesFactor);
  85325. effect.setFloat("randTextureTiles", 4.0);
  85326. }
  85327. effect.setFloat("totalStrength", _this.totalStrength);
  85328. effect.setFloat("radius", _this.radius);
  85329. effect.setFloat("area", _this.area);
  85330. effect.setFloat("fallOff", _this.fallOff);
  85331. effect.setFloat("base", _this.base);
  85332. effect.setTexture("textureSampler", _this._depthTexture);
  85333. effect.setTexture("randomSampler", _this._randomTexture);
  85334. };
  85335. };
  85336. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85337. var _this = this;
  85338. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85339. this._ssaoCombinePostProcess.onApply = function (effect) {
  85340. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  85341. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85342. };
  85343. };
  85344. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  85345. var size = 512;
  85346. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85347. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85348. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85349. var context = this._randomTexture.getContext();
  85350. var rand = function (min, max) {
  85351. return Math.random() * (max - min) + min;
  85352. };
  85353. var randVector = BABYLON.Vector3.Zero();
  85354. for (var x = 0; x < size; x++) {
  85355. for (var y = 0; y < size; y++) {
  85356. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  85357. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  85358. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  85359. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85360. context.fillRect(x, y, 1, 1);
  85361. }
  85362. }
  85363. this._randomTexture.update(false);
  85364. };
  85365. __decorate([
  85366. BABYLON.serialize()
  85367. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  85368. __decorate([
  85369. BABYLON.serialize()
  85370. ], SSAORenderingPipeline.prototype, "radius", void 0);
  85371. __decorate([
  85372. BABYLON.serialize()
  85373. ], SSAORenderingPipeline.prototype, "area", void 0);
  85374. __decorate([
  85375. BABYLON.serialize()
  85376. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  85377. __decorate([
  85378. BABYLON.serialize()
  85379. ], SSAORenderingPipeline.prototype, "base", void 0);
  85380. return SSAORenderingPipeline;
  85381. }(BABYLON.PostProcessRenderPipeline));
  85382. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  85383. })(BABYLON || (BABYLON = {}));
  85384. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  85385. var BABYLON;
  85386. (function (BABYLON) {
  85387. /**
  85388. * Render pipeline to produce ssao effect
  85389. */
  85390. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  85391. __extends(SSAO2RenderingPipeline, _super);
  85392. /**
  85393. * @constructor
  85394. * @param name The rendering pipeline name
  85395. * @param scene The scene linked to this pipeline
  85396. * @param 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 }
  85397. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85398. */
  85399. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  85400. var _this = _super.call(this, scene.getEngine(), name) || this;
  85401. // Members
  85402. /**
  85403. * @ignore
  85404. * The PassPostProcess id in the pipeline that contains the original scene color
  85405. */
  85406. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85407. /**
  85408. * @ignore
  85409. * The SSAO PostProcess id in the pipeline
  85410. */
  85411. _this.SSAORenderEffect = "SSAORenderEffect";
  85412. /**
  85413. * @ignore
  85414. * The horizontal blur PostProcess id in the pipeline
  85415. */
  85416. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85417. /**
  85418. * @ignore
  85419. * The vertical blur PostProcess id in the pipeline
  85420. */
  85421. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85422. /**
  85423. * @ignore
  85424. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85425. */
  85426. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85427. /**
  85428. * The output strength of the SSAO post-process. Default value is 1.0.
  85429. */
  85430. _this.totalStrength = 1.0;
  85431. /**
  85432. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  85433. */
  85434. _this.maxZ = 100.0;
  85435. /**
  85436. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  85437. */
  85438. _this.minZAspect = 0.2;
  85439. _this._samples = 8;
  85440. _this._textureSamples = 1;
  85441. _this._expensiveBlur = true;
  85442. /**
  85443. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  85444. */
  85445. _this.radius = 2.0;
  85446. /**
  85447. * The base color of the SSAO post-process
  85448. * The final result is "base + ssao" between [0, 1]
  85449. */
  85450. _this.base = 0;
  85451. _this._firstUpdate = true;
  85452. _this._bits = new Uint32Array(1);
  85453. _this._scene = scene;
  85454. _this._ratio = ratio;
  85455. if (!_this.isSupported) {
  85456. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  85457. return _this;
  85458. }
  85459. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  85460. var blurRatio = _this._ratio.blurRatio || ratio;
  85461. // Set up assets
  85462. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  85463. _this._createRandomTexture();
  85464. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  85465. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  85466. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85467. _this._originalColorPostProcess.samples = _this.textureSamples;
  85468. _this._createSSAOPostProcess(1.0);
  85469. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  85470. _this._createSSAOCombinePostProcess(blurRatio);
  85471. // Set up pipeline
  85472. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85473. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85474. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85475. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85476. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85477. // Finish
  85478. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85479. if (cameras) {
  85480. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85481. }
  85482. return _this;
  85483. }
  85484. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  85485. get: function () {
  85486. return this._samples;
  85487. },
  85488. /**
  85489. * Number of samples used for the SSAO calculations. Default value is 8
  85490. */
  85491. set: function (n) {
  85492. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  85493. this._samples = n;
  85494. this._sampleSphere = this._generateHemisphere();
  85495. this._firstUpdate = true;
  85496. },
  85497. enumerable: true,
  85498. configurable: true
  85499. });
  85500. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  85501. get: function () {
  85502. return this._textureSamples;
  85503. },
  85504. /**
  85505. * Number of samples to use for antialiasing
  85506. */
  85507. set: function (n) {
  85508. this._textureSamples = n;
  85509. this._originalColorPostProcess.samples = n;
  85510. this._blurHPostProcess.samples = n;
  85511. this._blurVPostProcess.samples = n;
  85512. this._ssaoPostProcess.samples = n;
  85513. this._ssaoCombinePostProcess.samples = n;
  85514. },
  85515. enumerable: true,
  85516. configurable: true
  85517. });
  85518. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  85519. get: function () {
  85520. return this._expensiveBlur;
  85521. },
  85522. /**
  85523. * If bilateral blur should be used
  85524. */
  85525. set: function (b) {
  85526. 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"]);
  85527. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  85528. this._expensiveBlur = b;
  85529. this._firstUpdate = true;
  85530. },
  85531. enumerable: true,
  85532. configurable: true
  85533. });
  85534. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  85535. /**
  85536. * Support test.
  85537. */
  85538. get: function () {
  85539. var engine = BABYLON.Engine.LastCreatedEngine;
  85540. if (!engine) {
  85541. return false;
  85542. }
  85543. return engine.getCaps().drawBuffersExtension;
  85544. },
  85545. enumerable: true,
  85546. configurable: true
  85547. });
  85548. // Public Methods
  85549. /**
  85550. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85551. */
  85552. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  85553. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  85554. for (var i = 0; i < this._scene.cameras.length; i++) {
  85555. var camera = this._scene.cameras[i];
  85556. this._originalColorPostProcess.dispose(camera);
  85557. this._ssaoPostProcess.dispose(camera);
  85558. this._blurHPostProcess.dispose(camera);
  85559. this._blurVPostProcess.dispose(camera);
  85560. this._ssaoCombinePostProcess.dispose(camera);
  85561. }
  85562. this._randomTexture.dispose();
  85563. if (disableGeometryBufferRenderer) {
  85564. this._scene.disableGeometryBufferRenderer();
  85565. }
  85566. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85567. _super.prototype.dispose.call(this);
  85568. };
  85569. // Private Methods
  85570. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  85571. var _this = this;
  85572. this._samplerOffsets = [];
  85573. var expensive = this.expensiveBlur;
  85574. for (var i = -8; i < 8; i++) {
  85575. this._samplerOffsets.push(i * 2 + 0.5);
  85576. }
  85577. 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");
  85578. this._blurHPostProcess.onApply = function (effect) {
  85579. if (!_this._scene.activeCamera) {
  85580. return;
  85581. }
  85582. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  85583. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85584. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85585. effect.setFloat("radius", _this.radius);
  85586. effect.setTexture("depthSampler", _this._depthTexture);
  85587. if (_this._firstUpdate) {
  85588. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85589. }
  85590. };
  85591. 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");
  85592. this._blurVPostProcess.onApply = function (effect) {
  85593. if (!_this._scene.activeCamera) {
  85594. return;
  85595. }
  85596. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  85597. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85598. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85599. effect.setFloat("radius", _this.radius);
  85600. effect.setTexture("depthSampler", _this._depthTexture);
  85601. if (_this._firstUpdate) {
  85602. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85603. _this._firstUpdate = false;
  85604. }
  85605. };
  85606. this._blurHPostProcess.samples = this.textureSamples;
  85607. this._blurVPostProcess.samples = this.textureSamples;
  85608. };
  85609. /** @hidden */
  85610. SSAO2RenderingPipeline.prototype._rebuild = function () {
  85611. this._firstUpdate = true;
  85612. _super.prototype._rebuild.call(this);
  85613. };
  85614. //Van der Corput radical inverse
  85615. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  85616. this._bits[0] = i;
  85617. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  85618. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  85619. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  85620. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  85621. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  85622. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  85623. };
  85624. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  85625. return [i / n, this._radicalInverse_VdC(i)];
  85626. };
  85627. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  85628. var phi = v * 2.0 * Math.PI;
  85629. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  85630. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  85631. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  85632. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  85633. };
  85634. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  85635. var numSamples = this.samples;
  85636. var result = [];
  85637. var vector;
  85638. var i = 0;
  85639. while (i < numSamples) {
  85640. if (numSamples < 16) {
  85641. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  85642. }
  85643. else {
  85644. var rand = this._hammersley(i, numSamples);
  85645. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  85646. }
  85647. result.push(vector.x, vector.y, vector.z);
  85648. i++;
  85649. }
  85650. return result;
  85651. };
  85652. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85653. var _this = this;
  85654. var numSamples = this.samples;
  85655. this._sampleSphere = this._generateHemisphere();
  85656. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  85657. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85658. "base", "range", "projection", "near", "far", "texelSize",
  85659. "xViewport", "yViewport", "maxZ", "minZAspect"
  85660. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85661. this._ssaoPostProcess.onApply = function (effect) {
  85662. if (_this._firstUpdate) {
  85663. effect.setArray3("sampleSphere", _this._sampleSphere);
  85664. effect.setFloat("randTextureTiles", 32.0);
  85665. }
  85666. if (!_this._scene.activeCamera) {
  85667. return;
  85668. }
  85669. effect.setFloat("samplesFactor", 1 / _this.samples);
  85670. effect.setFloat("totalStrength", _this.totalStrength);
  85671. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  85672. effect.setFloat("radius", _this.radius);
  85673. effect.setFloat("maxZ", _this.maxZ);
  85674. effect.setFloat("minZAspect", _this.minZAspect);
  85675. effect.setFloat("base", _this.base);
  85676. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85677. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85678. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  85679. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  85680. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  85681. effect.setTexture("textureSampler", _this._depthTexture);
  85682. effect.setTexture("normalSampler", _this._normalTexture);
  85683. effect.setTexture("randomSampler", _this._randomTexture);
  85684. };
  85685. this._ssaoPostProcess.samples = this.textureSamples;
  85686. };
  85687. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85688. var _this = this;
  85689. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85690. this._ssaoCombinePostProcess.onApply = function (effect) {
  85691. var viewport = _this._scene.activeCamera.viewport;
  85692. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  85693. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85694. };
  85695. this._ssaoCombinePostProcess.samples = this.textureSamples;
  85696. };
  85697. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  85698. var size = 128;
  85699. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85700. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85701. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85702. var context = this._randomTexture.getContext();
  85703. var rand = function (min, max) {
  85704. return Math.random() * (max - min) + min;
  85705. };
  85706. var randVector = BABYLON.Vector3.Zero();
  85707. for (var x = 0; x < size; x++) {
  85708. for (var y = 0; y < size; y++) {
  85709. randVector.x = rand(0.0, 1.0);
  85710. randVector.y = rand(0.0, 1.0);
  85711. randVector.z = 0.0;
  85712. randVector.normalize();
  85713. randVector.scaleInPlace(255);
  85714. randVector.x = Math.floor(randVector.x);
  85715. randVector.y = Math.floor(randVector.y);
  85716. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85717. context.fillRect(x, y, 1, 1);
  85718. }
  85719. }
  85720. this._randomTexture.update(false);
  85721. };
  85722. /**
  85723. * Serialize the rendering pipeline (Used when exporting)
  85724. * @returns the serialized object
  85725. */
  85726. SSAO2RenderingPipeline.prototype.serialize = function () {
  85727. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85728. serializationObject.customType = "SSAO2RenderingPipeline";
  85729. return serializationObject;
  85730. };
  85731. /**
  85732. * Parse the serialized pipeline
  85733. * @param source Source pipeline.
  85734. * @param scene The scene to load the pipeline to.
  85735. * @param rootUrl The URL of the serialized pipeline.
  85736. * @returns An instantiated pipeline from the serialized object.
  85737. */
  85738. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  85739. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85740. };
  85741. __decorate([
  85742. BABYLON.serialize()
  85743. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  85744. __decorate([
  85745. BABYLON.serialize()
  85746. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  85747. __decorate([
  85748. BABYLON.serialize()
  85749. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  85750. __decorate([
  85751. BABYLON.serialize("samples")
  85752. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  85753. __decorate([
  85754. BABYLON.serialize("textureSamples")
  85755. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  85756. __decorate([
  85757. BABYLON.serialize()
  85758. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  85759. __decorate([
  85760. BABYLON.serialize("expensiveBlur")
  85761. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  85762. __decorate([
  85763. BABYLON.serialize()
  85764. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  85765. __decorate([
  85766. BABYLON.serialize()
  85767. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  85768. return SSAO2RenderingPipeline;
  85769. }(BABYLON.PostProcessRenderPipeline));
  85770. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  85771. })(BABYLON || (BABYLON = {}));
  85772. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  85773. var BABYLON;
  85774. (function (BABYLON) {
  85775. /**
  85776. * BABYLON.JS Chromatic Aberration GLSL Shader
  85777. * Author: Olivier Guyot
  85778. * Separates very slightly R, G and B colors on the edges of the screen
  85779. * Inspired by Francois Tarlier & Martins Upitis
  85780. */
  85781. var LensRenderingPipeline = /** @class */ (function (_super) {
  85782. __extends(LensRenderingPipeline, _super);
  85783. /**
  85784. * @constructor
  85785. *
  85786. * Effect parameters are as follow:
  85787. * {
  85788. * chromatic_aberration: number; // from 0 to x (1 for realism)
  85789. * edge_blur: number; // from 0 to x (1 for realism)
  85790. * distortion: number; // from 0 to x (1 for realism)
  85791. * grain_amount: number; // from 0 to 1
  85792. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  85793. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  85794. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  85795. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  85796. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  85797. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  85798. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  85799. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  85800. * }
  85801. * Note: if an effect parameter is unset, effect is disabled
  85802. *
  85803. * @param name The rendering pipeline name
  85804. * @param parameters - An object containing all parameters (see above)
  85805. * @param scene The scene linked to this pipeline
  85806. * @param 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)
  85807. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85808. */
  85809. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  85810. if (ratio === void 0) { ratio = 1.0; }
  85811. var _this = _super.call(this, scene.getEngine(), name) || this;
  85812. // Lens effects can be of the following:
  85813. // - chromatic aberration (slight shift of RGB colors)
  85814. // - blur on the edge of the lens
  85815. // - lens distortion
  85816. // - depth-of-field blur & highlights enhancing
  85817. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  85818. // - grain effect (noise or custom texture)
  85819. // Two additional texture samplers are needed:
  85820. // - depth map (for depth-of-field)
  85821. // - grain texture
  85822. /**
  85823. * @ignore
  85824. * The chromatic aberration PostProcess id in the pipeline
  85825. */
  85826. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  85827. /**
  85828. * @ignore
  85829. * The highlights enhancing PostProcess id in the pipeline
  85830. */
  85831. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  85832. /**
  85833. * @ignore
  85834. * The depth-of-field PostProcess id in the pipeline
  85835. */
  85836. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  85837. _this._scene = scene;
  85838. // Fetch texture samplers
  85839. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85840. if (parameters.grain_texture) {
  85841. _this._grainTexture = parameters.grain_texture;
  85842. }
  85843. else {
  85844. _this._createGrainTexture();
  85845. }
  85846. // save parameters
  85847. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  85848. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  85849. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  85850. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  85851. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  85852. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  85853. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  85854. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  85855. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  85856. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  85857. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  85858. // Create effects
  85859. _this._createChromaticAberrationPostProcess(ratio);
  85860. _this._createHighlightsPostProcess(ratio);
  85861. _this._createDepthOfFieldPostProcess(ratio / 4);
  85862. // Set up pipeline
  85863. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  85864. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  85865. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  85866. if (_this._highlightsGain === -1) {
  85867. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  85868. }
  85869. // Finish
  85870. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85871. if (cameras) {
  85872. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85873. }
  85874. return _this;
  85875. }
  85876. // public methods (self explanatory)
  85877. /**
  85878. * Sets the amount of blur at the edges
  85879. * @param amount blur amount
  85880. */
  85881. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  85882. /**
  85883. * Sets edge blur to 0
  85884. */
  85885. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  85886. /**
  85887. * Sets the amout of grain
  85888. * @param amount Amount of grain
  85889. */
  85890. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  85891. /**
  85892. * Set grain amount to 0
  85893. */
  85894. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  85895. /**
  85896. * Sets the chromatic aberration amount
  85897. * @param amount amount of chromatic aberration
  85898. */
  85899. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  85900. /**
  85901. * Sets chromatic aberration amount to 0
  85902. */
  85903. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  85904. /**
  85905. * Sets the EdgeDistortion amount
  85906. * @param amount amount of EdgeDistortion
  85907. */
  85908. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  85909. /**
  85910. * Sets edge distortion to 0
  85911. */
  85912. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  85913. /**
  85914. * Sets the FocusDistance amount
  85915. * @param amount amount of FocusDistance
  85916. */
  85917. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  85918. /**
  85919. * Disables depth of field
  85920. */
  85921. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  85922. /**
  85923. * Sets the Aperture amount
  85924. * @param amount amount of Aperture
  85925. */
  85926. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  85927. /**
  85928. * Sets the DarkenOutOfFocus amount
  85929. * @param amount amount of DarkenOutOfFocus
  85930. */
  85931. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  85932. /**
  85933. * Creates a pentagon bokeh effect
  85934. */
  85935. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  85936. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  85937. };
  85938. /**
  85939. * Disables the pentagon bokeh effect
  85940. */
  85941. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  85942. this._highlightsPostProcess.updateEffect();
  85943. };
  85944. /**
  85945. * Enables noise blur
  85946. */
  85947. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  85948. /**
  85949. * Disables noise blur
  85950. */
  85951. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  85952. /**
  85953. * Sets the HighlightsGain amount
  85954. * @param amount amount of HighlightsGain
  85955. */
  85956. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  85957. this._highlightsGain = amount;
  85958. };
  85959. /**
  85960. * Sets the HighlightsThreshold amount
  85961. * @param amount amount of HighlightsThreshold
  85962. */
  85963. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  85964. if (this._highlightsGain === -1) {
  85965. this._highlightsGain = 1.0;
  85966. }
  85967. this._highlightsThreshold = amount;
  85968. };
  85969. /**
  85970. * Disables highlights
  85971. */
  85972. LensRenderingPipeline.prototype.disableHighlights = function () {
  85973. this._highlightsGain = -1;
  85974. };
  85975. /**
  85976. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  85977. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  85978. */
  85979. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85980. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85981. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85982. this._chromaticAberrationPostProcess = null;
  85983. this._highlightsPostProcess = null;
  85984. this._depthOfFieldPostProcess = null;
  85985. this._grainTexture.dispose();
  85986. if (disableDepthRender) {
  85987. this._scene.disableDepthRenderer();
  85988. }
  85989. };
  85990. // colors shifting and distortion
  85991. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  85992. var _this = this;
  85993. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  85994. [], // samplers
  85995. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85996. this._chromaticAberrationPostProcess.onApply = function (effect) {
  85997. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  85998. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  85999. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86000. effect.setFloat('radialIntensity', 1);
  86001. effect.setFloat2('direction', 17, 17);
  86002. effect.setFloat2('centerPosition', 0.5, 0.5);
  86003. };
  86004. };
  86005. // highlights enhancing
  86006. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  86007. var _this = this;
  86008. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  86009. [], // samplers
  86010. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  86011. this._highlightsPostProcess.onApply = function (effect) {
  86012. effect.setFloat('gain', _this._highlightsGain);
  86013. effect.setFloat('threshold', _this._highlightsThreshold);
  86014. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  86015. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86016. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86017. };
  86018. };
  86019. // colors shifting and distortion
  86020. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  86021. var _this = this;
  86022. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  86023. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  86024. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  86025. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86026. this._depthOfFieldPostProcess.onApply = function (effect) {
  86027. effect.setTexture("depthSampler", _this._depthTexture);
  86028. effect.setTexture("grainSampler", _this._grainTexture);
  86029. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  86030. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  86031. effect.setFloat('grain_amount', _this._grainAmount);
  86032. effect.setBool('blur_noise', _this._blurNoise);
  86033. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86034. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86035. effect.setFloat('distortion', _this._distortion);
  86036. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  86037. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  86038. effect.setFloat('aperture', _this._dofAperture);
  86039. effect.setFloat('darken', _this._dofDarken);
  86040. effect.setFloat('edge_blur', _this._edgeBlur);
  86041. effect.setBool('highlights', (_this._highlightsGain !== -1));
  86042. if (_this._scene.activeCamera) {
  86043. effect.setFloat('near', _this._scene.activeCamera.minZ);
  86044. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  86045. }
  86046. };
  86047. };
  86048. // creates a black and white random noise texture, 512x512
  86049. LensRenderingPipeline.prototype._createGrainTexture = function () {
  86050. var size = 512;
  86051. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86052. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  86053. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  86054. var context = this._grainTexture.getContext();
  86055. var rand = function (min, max) {
  86056. return Math.random() * (max - min) + min;
  86057. };
  86058. var value;
  86059. for (var x = 0; x < size; x++) {
  86060. for (var y = 0; y < size; y++) {
  86061. value = Math.floor(rand(0.42, 0.58) * 255);
  86062. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  86063. context.fillRect(x, y, 1, 1);
  86064. }
  86065. }
  86066. this._grainTexture.update(false);
  86067. };
  86068. return LensRenderingPipeline;
  86069. }(BABYLON.PostProcessRenderPipeline));
  86070. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  86071. })(BABYLON || (BABYLON = {}));
  86072. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  86073. var BABYLON;
  86074. (function (BABYLON) {
  86075. /**
  86076. * Standard rendering pipeline
  86077. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86078. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  86079. */
  86080. var StandardRenderingPipeline = /** @class */ (function (_super) {
  86081. __extends(StandardRenderingPipeline, _super);
  86082. /**
  86083. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86084. * @constructor
  86085. * @param name The rendering pipeline name
  86086. * @param scene The scene linked to this pipeline
  86087. * @param 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)
  86088. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  86089. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86090. */
  86091. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  86092. if (originalPostProcess === void 0) { originalPostProcess = null; }
  86093. var _this = _super.call(this, scene.getEngine(), name) || this;
  86094. /**
  86095. * Post-process used to down scale an image x4
  86096. */
  86097. _this.downSampleX4PostProcess = null;
  86098. /**
  86099. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  86100. */
  86101. _this.brightPassPostProcess = null;
  86102. /**
  86103. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  86104. */
  86105. _this.blurHPostProcesses = [];
  86106. /**
  86107. * Post-process array storing all the vertical blur post-processes used by the pipeline
  86108. */
  86109. _this.blurVPostProcesses = [];
  86110. /**
  86111. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  86112. */
  86113. _this.textureAdderPostProcess = null;
  86114. /**
  86115. * Post-process used to create volumetric lighting effect
  86116. */
  86117. _this.volumetricLightPostProcess = null;
  86118. /**
  86119. * Post-process used to smooth the previous volumetric light post-process on the X axis
  86120. */
  86121. _this.volumetricLightSmoothXPostProcess = null;
  86122. /**
  86123. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  86124. */
  86125. _this.volumetricLightSmoothYPostProcess = null;
  86126. /**
  86127. * Post-process used to merge the volumetric light effect and the real scene color
  86128. */
  86129. _this.volumetricLightMergePostProces = null;
  86130. /**
  86131. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  86132. */
  86133. _this.volumetricLightFinalPostProcess = null;
  86134. /**
  86135. * Base post-process used to calculate the average luminance of the final image for HDR
  86136. */
  86137. _this.luminancePostProcess = null;
  86138. /**
  86139. * Post-processes used to create down sample post-processes in order to get
  86140. * the average luminance of the final image for HDR
  86141. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  86142. */
  86143. _this.luminanceDownSamplePostProcesses = [];
  86144. /**
  86145. * Post-process used to create a HDR effect (light adaptation)
  86146. */
  86147. _this.hdrPostProcess = null;
  86148. /**
  86149. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  86150. */
  86151. _this.textureAdderFinalPostProcess = null;
  86152. /**
  86153. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  86154. */
  86155. _this.lensFlareFinalPostProcess = null;
  86156. /**
  86157. * Post-process used to merge the final HDR post-process and the real scene color
  86158. */
  86159. _this.hdrFinalPostProcess = null;
  86160. /**
  86161. * Post-process used to create a lens flare effect
  86162. */
  86163. _this.lensFlarePostProcess = null;
  86164. /**
  86165. * Post-process that merges the result of the lens flare post-process and the real scene color
  86166. */
  86167. _this.lensFlareComposePostProcess = null;
  86168. /**
  86169. * Post-process used to create a motion blur effect
  86170. */
  86171. _this.motionBlurPostProcess = null;
  86172. /**
  86173. * Post-process used to create a depth of field effect
  86174. */
  86175. _this.depthOfFieldPostProcess = null;
  86176. /**
  86177. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  86178. */
  86179. _this.fxaaPostProcess = null;
  86180. // Values
  86181. /**
  86182. * Represents the brightness threshold in order to configure the illuminated surfaces
  86183. */
  86184. _this.brightThreshold = 1.0;
  86185. /**
  86186. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  86187. */
  86188. _this.blurWidth = 512.0;
  86189. /**
  86190. * Sets if the blur for highlighted surfaces must be only horizontal
  86191. */
  86192. _this.horizontalBlur = false;
  86193. /**
  86194. * Sets the overall exposure used by the pipeline
  86195. */
  86196. _this.exposure = 1.0;
  86197. /**
  86198. * Texture used typically to simulate "dirty" on camera lens
  86199. */
  86200. _this.lensTexture = null;
  86201. /**
  86202. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  86203. */
  86204. _this.volumetricLightCoefficient = 0.2;
  86205. /**
  86206. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  86207. */
  86208. _this.volumetricLightPower = 4.0;
  86209. /**
  86210. * Used the set the blur intensity to smooth the volumetric lights
  86211. */
  86212. _this.volumetricLightBlurScale = 64.0;
  86213. /**
  86214. * Light (spot or directional) used to generate the volumetric lights rays
  86215. * The source light must have a shadow generate so the pipeline can get its
  86216. * depth map
  86217. */
  86218. _this.sourceLight = null;
  86219. /**
  86220. * For eye adaptation, represents the minimum luminance the eye can see
  86221. */
  86222. _this.hdrMinimumLuminance = 1.0;
  86223. /**
  86224. * For eye adaptation, represents the decrease luminance speed
  86225. */
  86226. _this.hdrDecreaseRate = 0.5;
  86227. /**
  86228. * For eye adaptation, represents the increase luminance speed
  86229. */
  86230. _this.hdrIncreaseRate = 0.5;
  86231. /**
  86232. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  86233. */
  86234. _this.lensColorTexture = null;
  86235. /**
  86236. * The overall strengh for the lens flare effect
  86237. */
  86238. _this.lensFlareStrength = 20.0;
  86239. /**
  86240. * Dispersion coefficient for lens flare ghosts
  86241. */
  86242. _this.lensFlareGhostDispersal = 1.4;
  86243. /**
  86244. * Main lens flare halo width
  86245. */
  86246. _this.lensFlareHaloWidth = 0.7;
  86247. /**
  86248. * Based on the lens distortion effect, defines how much the lens flare result
  86249. * is distorted
  86250. */
  86251. _this.lensFlareDistortionStrength = 16.0;
  86252. /**
  86253. * Lens star texture must be used to simulate rays on the flares and is available
  86254. * in the documentation
  86255. */
  86256. _this.lensStarTexture = null;
  86257. /**
  86258. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  86259. * flare effect by taking account of the dirt texture
  86260. */
  86261. _this.lensFlareDirtTexture = null;
  86262. /**
  86263. * Represents the focal length for the depth of field effect
  86264. */
  86265. _this.depthOfFieldDistance = 10.0;
  86266. /**
  86267. * Represents the blur intensity for the blurred part of the depth of field effect
  86268. */
  86269. _this.depthOfFieldBlurWidth = 64.0;
  86270. /**
  86271. * For motion blur, defines how much the image is blurred by the movement
  86272. */
  86273. _this.motionStrength = 1.0;
  86274. /**
  86275. * List of animations for the pipeline (IAnimatable implementation)
  86276. */
  86277. _this.animations = [];
  86278. _this._currentDepthOfFieldSource = null;
  86279. _this._hdrCurrentLuminance = 1.0;
  86280. // Getters and setters
  86281. _this._bloomEnabled = false;
  86282. _this._depthOfFieldEnabled = false;
  86283. _this._vlsEnabled = false;
  86284. _this._lensFlareEnabled = false;
  86285. _this._hdrEnabled = false;
  86286. _this._motionBlurEnabled = false;
  86287. _this._fxaaEnabled = false;
  86288. _this._motionBlurSamples = 64.0;
  86289. _this._volumetricLightStepsCount = 50.0;
  86290. _this._samples = 1;
  86291. _this._cameras = cameras || [];
  86292. // Initialize
  86293. _this._scene = scene;
  86294. _this._basePostProcess = originalPostProcess;
  86295. _this._ratio = ratio;
  86296. // Misc
  86297. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86298. // Finish
  86299. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86300. _this._buildPipeline();
  86301. return _this;
  86302. }
  86303. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  86304. /**
  86305. * @ignore
  86306. * Specifies if the bloom pipeline is enabled
  86307. */
  86308. get: function () {
  86309. return this._bloomEnabled;
  86310. },
  86311. set: function (enabled) {
  86312. if (this._bloomEnabled === enabled) {
  86313. return;
  86314. }
  86315. this._bloomEnabled = enabled;
  86316. this._buildPipeline();
  86317. },
  86318. enumerable: true,
  86319. configurable: true
  86320. });
  86321. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  86322. /**
  86323. * @ignore
  86324. * Specifies if the depth of field pipeline is enabed
  86325. */
  86326. get: function () {
  86327. return this._depthOfFieldEnabled;
  86328. },
  86329. set: function (enabled) {
  86330. if (this._depthOfFieldEnabled === enabled) {
  86331. return;
  86332. }
  86333. this._depthOfFieldEnabled = enabled;
  86334. this._buildPipeline();
  86335. },
  86336. enumerable: true,
  86337. configurable: true
  86338. });
  86339. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  86340. /**
  86341. * @ignore
  86342. * Specifies if the lens flare pipeline is enabed
  86343. */
  86344. get: function () {
  86345. return this._lensFlareEnabled;
  86346. },
  86347. set: function (enabled) {
  86348. if (this._lensFlareEnabled === enabled) {
  86349. return;
  86350. }
  86351. this._lensFlareEnabled = enabled;
  86352. this._buildPipeline();
  86353. },
  86354. enumerable: true,
  86355. configurable: true
  86356. });
  86357. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  86358. /**
  86359. * @ignore
  86360. * Specifies if the HDR pipeline is enabled
  86361. */
  86362. get: function () {
  86363. return this._hdrEnabled;
  86364. },
  86365. set: function (enabled) {
  86366. if (this._hdrEnabled === enabled) {
  86367. return;
  86368. }
  86369. this._hdrEnabled = enabled;
  86370. this._buildPipeline();
  86371. },
  86372. enumerable: true,
  86373. configurable: true
  86374. });
  86375. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  86376. /**
  86377. * @ignore
  86378. * Specifies if the volumetric lights scattering effect is enabled
  86379. */
  86380. get: function () {
  86381. return this._vlsEnabled;
  86382. },
  86383. set: function (enabled) {
  86384. if (this._vlsEnabled === enabled) {
  86385. return;
  86386. }
  86387. if (enabled) {
  86388. var geometry = this._scene.enableGeometryBufferRenderer();
  86389. if (!geometry) {
  86390. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  86391. return;
  86392. }
  86393. }
  86394. this._vlsEnabled = enabled;
  86395. this._buildPipeline();
  86396. },
  86397. enumerable: true,
  86398. configurable: true
  86399. });
  86400. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  86401. /**
  86402. * @ignore
  86403. * Specifies if the motion blur effect is enabled
  86404. */
  86405. get: function () {
  86406. return this._motionBlurEnabled;
  86407. },
  86408. set: function (enabled) {
  86409. if (this._motionBlurEnabled === enabled) {
  86410. return;
  86411. }
  86412. this._motionBlurEnabled = enabled;
  86413. this._buildPipeline();
  86414. },
  86415. enumerable: true,
  86416. configurable: true
  86417. });
  86418. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  86419. /**
  86420. * Specifies if anti-aliasing is enabled
  86421. */
  86422. get: function () {
  86423. return this._fxaaEnabled;
  86424. },
  86425. set: function (enabled) {
  86426. if (this._fxaaEnabled === enabled) {
  86427. return;
  86428. }
  86429. this._fxaaEnabled = enabled;
  86430. this._buildPipeline();
  86431. },
  86432. enumerable: true,
  86433. configurable: true
  86434. });
  86435. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  86436. /**
  86437. * Specifies the number of steps used to calculate the volumetric lights
  86438. * Typically in interval [50, 200]
  86439. */
  86440. get: function () {
  86441. return this._volumetricLightStepsCount;
  86442. },
  86443. set: function (count) {
  86444. if (this.volumetricLightPostProcess) {
  86445. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  86446. }
  86447. this._volumetricLightStepsCount = count;
  86448. },
  86449. enumerable: true,
  86450. configurable: true
  86451. });
  86452. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  86453. /**
  86454. * Specifies the number of samples used for the motion blur effect
  86455. * Typically in interval [16, 64]
  86456. */
  86457. get: function () {
  86458. return this._motionBlurSamples;
  86459. },
  86460. set: function (samples) {
  86461. if (this.motionBlurPostProcess) {
  86462. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  86463. }
  86464. this._motionBlurSamples = samples;
  86465. },
  86466. enumerable: true,
  86467. configurable: true
  86468. });
  86469. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  86470. /**
  86471. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86472. */
  86473. get: function () {
  86474. return this._samples;
  86475. },
  86476. set: function (sampleCount) {
  86477. if (this._samples === sampleCount) {
  86478. return;
  86479. }
  86480. this._samples = sampleCount;
  86481. this._buildPipeline();
  86482. },
  86483. enumerable: true,
  86484. configurable: true
  86485. });
  86486. StandardRenderingPipeline.prototype._buildPipeline = function () {
  86487. var _this = this;
  86488. var ratio = this._ratio;
  86489. var scene = this._scene;
  86490. this._disposePostProcesses();
  86491. this._reset();
  86492. // Create pass post-process
  86493. if (!this._basePostProcess) {
  86494. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  86495. this.originalPostProcess.onApply = function (effect) {
  86496. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  86497. };
  86498. }
  86499. else {
  86500. this.originalPostProcess = this._basePostProcess;
  86501. }
  86502. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  86503. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  86504. }
  86505. this._currentDepthOfFieldSource = this.originalPostProcess;
  86506. if (this._bloomEnabled) {
  86507. // Create down sample X4 post-process
  86508. this._createDownSampleX4PostProcess(scene, ratio / 2);
  86509. // Create bright pass post-process
  86510. this._createBrightPassPostProcess(scene, ratio / 2);
  86511. // Create gaussian blur post-processes (down sampling blurs)
  86512. this._createBlurPostProcesses(scene, ratio / 4, 1);
  86513. // Create texture adder post-process
  86514. this._createTextureAdderPostProcess(scene, ratio);
  86515. // Create depth-of-field source post-process
  86516. 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);
  86517. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  86518. }
  86519. if (this._vlsEnabled) {
  86520. // Create volumetric light
  86521. this._createVolumetricLightPostProcess(scene, ratio);
  86522. // Create volumetric light final post-process
  86523. 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);
  86524. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  86525. }
  86526. if (this._lensFlareEnabled) {
  86527. // Create lens flare post-process
  86528. this._createLensFlarePostProcess(scene, ratio);
  86529. // Create depth-of-field source post-process post lens-flare and disable it now
  86530. 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);
  86531. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  86532. }
  86533. if (this._hdrEnabled) {
  86534. // Create luminance
  86535. this._createLuminancePostProcesses(scene, this._floatTextureType);
  86536. // Create HDR
  86537. this._createHdrPostProcess(scene, ratio);
  86538. // Create depth-of-field source post-process post hdr and disable it now
  86539. 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);
  86540. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  86541. }
  86542. if (this._depthOfFieldEnabled) {
  86543. // Create gaussian blur used by depth-of-field
  86544. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  86545. // Create depth-of-field post-process
  86546. this._createDepthOfFieldPostProcess(scene, ratio);
  86547. }
  86548. if (this._motionBlurEnabled) {
  86549. // Create motion blur post-process
  86550. this._createMotionBlurPostProcess(scene, ratio);
  86551. }
  86552. if (this._fxaaEnabled) {
  86553. // Create fxaa post-process
  86554. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86555. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  86556. }
  86557. if (this._cameras !== null) {
  86558. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86559. }
  86560. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  86561. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86562. }
  86563. };
  86564. // Down Sample X4 Post-Processs
  86565. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  86566. var _this = this;
  86567. var downSampleX4Offsets = new Array(32);
  86568. 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);
  86569. this.downSampleX4PostProcess.onApply = function (effect) {
  86570. var id = 0;
  86571. var width = _this.downSampleX4PostProcess.width;
  86572. var height = _this.downSampleX4PostProcess.height;
  86573. for (var i = -2; i < 2; i++) {
  86574. for (var j = -2; j < 2; j++) {
  86575. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  86576. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  86577. id += 2;
  86578. }
  86579. }
  86580. effect.setArray2("dsOffsets", downSampleX4Offsets);
  86581. };
  86582. // Add to pipeline
  86583. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  86584. };
  86585. // Brightpass Post-Process
  86586. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  86587. var _this = this;
  86588. var brightOffsets = new Array(8);
  86589. 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);
  86590. this.brightPassPostProcess.onApply = function (effect) {
  86591. var sU = (1.0 / _this.brightPassPostProcess.width);
  86592. var sV = (1.0 / _this.brightPassPostProcess.height);
  86593. brightOffsets[0] = -0.5 * sU;
  86594. brightOffsets[1] = 0.5 * sV;
  86595. brightOffsets[2] = 0.5 * sU;
  86596. brightOffsets[3] = 0.5 * sV;
  86597. brightOffsets[4] = -0.5 * sU;
  86598. brightOffsets[5] = -0.5 * sV;
  86599. brightOffsets[6] = 0.5 * sU;
  86600. brightOffsets[7] = -0.5 * sV;
  86601. effect.setArray2("dsOffsets", brightOffsets);
  86602. effect.setFloat("brightThreshold", _this.brightThreshold);
  86603. };
  86604. // Add to pipeline
  86605. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  86606. };
  86607. // Create blur H&V post-processes
  86608. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  86609. var _this = this;
  86610. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  86611. var engine = scene.getEngine();
  86612. 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);
  86613. 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);
  86614. blurX.onActivateObservable.add(function () {
  86615. var dw = blurX.width / engine.getRenderWidth();
  86616. blurX.kernel = _this[blurWidthKey] * dw;
  86617. });
  86618. blurY.onActivateObservable.add(function () {
  86619. var dw = blurY.height / engine.getRenderHeight();
  86620. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  86621. });
  86622. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  86623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  86624. this.blurHPostProcesses.push(blurX);
  86625. this.blurVPostProcesses.push(blurY);
  86626. };
  86627. // Create texture adder post-process
  86628. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  86629. var _this = this;
  86630. 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);
  86631. this.textureAdderPostProcess.onApply = function (effect) {
  86632. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  86633. effect.setTexture("lensSampler", _this.lensTexture);
  86634. effect.setFloat("exposure", _this.exposure);
  86635. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  86636. };
  86637. // Add to pipeline
  86638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  86639. };
  86640. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  86641. var _this = this;
  86642. var geometryRenderer = scene.enableGeometryBufferRenderer();
  86643. geometryRenderer.enablePosition = true;
  86644. var geometry = geometryRenderer.getGBuffer();
  86645. // Base post-process
  86646. 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));
  86647. var depthValues = BABYLON.Vector2.Zero();
  86648. this.volumetricLightPostProcess.onApply = function (effect) {
  86649. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  86650. var generator = _this.sourceLight.getShadowGenerator();
  86651. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  86652. effect.setTexture("positionSampler", geometry.textures[2]);
  86653. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  86654. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  86655. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  86656. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  86657. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  86658. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  86659. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  86660. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  86661. effect.setVector2("depthValues", depthValues);
  86662. }
  86663. };
  86664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  86665. // Smooth
  86666. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  86667. // Merge
  86668. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  86669. this.volumetricLightMergePostProces.onApply = function (effect) {
  86670. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  86671. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  86672. };
  86673. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  86674. };
  86675. // Create luminance
  86676. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  86677. var _this = this;
  86678. // Create luminance
  86679. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  86680. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  86681. var offsets = [];
  86682. this.luminancePostProcess.onApply = function (effect) {
  86683. var sU = (1.0 / _this.luminancePostProcess.width);
  86684. var sV = (1.0 / _this.luminancePostProcess.height);
  86685. offsets[0] = -0.5 * sU;
  86686. offsets[1] = 0.5 * sV;
  86687. offsets[2] = 0.5 * sU;
  86688. offsets[3] = 0.5 * sV;
  86689. offsets[4] = -0.5 * sU;
  86690. offsets[5] = -0.5 * sV;
  86691. offsets[6] = 0.5 * sU;
  86692. offsets[7] = -0.5 * sV;
  86693. effect.setArray2("lumOffsets", offsets);
  86694. };
  86695. // Add to pipeline
  86696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  86697. // Create down sample luminance
  86698. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  86699. var size = Math.pow(3, i);
  86700. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  86701. if (i === 0) {
  86702. defines += "#define FINAL_DOWN_SAMPLER";
  86703. }
  86704. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  86705. this.luminanceDownSamplePostProcesses.push(postProcess);
  86706. }
  86707. // Create callbacks and add effects
  86708. var lastLuminance = this.luminancePostProcess;
  86709. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  86710. var downSampleOffsets = new Array(18);
  86711. pp.onApply = function (effect) {
  86712. if (!lastLuminance) {
  86713. return;
  86714. }
  86715. var id = 0;
  86716. for (var x = -1; x < 2; x++) {
  86717. for (var y = -1; y < 2; y++) {
  86718. downSampleOffsets[id] = x / lastLuminance.width;
  86719. downSampleOffsets[id + 1] = y / lastLuminance.height;
  86720. id += 2;
  86721. }
  86722. }
  86723. effect.setArray2("dsOffsets", downSampleOffsets);
  86724. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  86725. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86726. lastLuminance = _this.luminancePostProcess;
  86727. }
  86728. else {
  86729. lastLuminance = pp;
  86730. }
  86731. };
  86732. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86733. pp.onAfterRender = function (effect) {
  86734. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  86735. 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);
  86736. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  86737. };
  86738. }
  86739. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  86740. });
  86741. };
  86742. // Create HDR post-process
  86743. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  86744. var _this = this;
  86745. 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);
  86746. var outputLiminance = 1;
  86747. var time = 0;
  86748. var lastTime = 0;
  86749. this.hdrPostProcess.onApply = function (effect) {
  86750. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  86751. time += scene.getEngine().getDeltaTime();
  86752. if (outputLiminance < 0) {
  86753. outputLiminance = _this._hdrCurrentLuminance;
  86754. }
  86755. else {
  86756. var dt = (lastTime - time) / 1000.0;
  86757. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  86758. outputLiminance += _this.hdrDecreaseRate * dt;
  86759. }
  86760. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  86761. outputLiminance -= _this.hdrIncreaseRate * dt;
  86762. }
  86763. else {
  86764. outputLiminance = _this._hdrCurrentLuminance;
  86765. }
  86766. }
  86767. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  86768. effect.setFloat("averageLuminance", outputLiminance);
  86769. lastTime = time;
  86770. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  86771. };
  86772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  86773. };
  86774. // Create lens flare post-process
  86775. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  86776. var _this = this;
  86777. 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);
  86778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  86779. this._createBlurPostProcesses(scene, ratio / 4, 2);
  86780. 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);
  86781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  86782. var resolution = new BABYLON.Vector2(0, 0);
  86783. // Lens flare
  86784. this.lensFlarePostProcess.onApply = function (effect) {
  86785. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  86786. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  86787. effect.setFloat("strength", _this.lensFlareStrength);
  86788. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  86789. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  86790. // Shift
  86791. resolution.x = _this.lensFlarePostProcess.width;
  86792. resolution.y = _this.lensFlarePostProcess.height;
  86793. effect.setVector2("resolution", resolution);
  86794. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  86795. };
  86796. // Compose
  86797. 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);
  86798. 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);
  86799. this.lensFlareComposePostProcess.onApply = function (effect) {
  86800. if (!_this._scene.activeCamera) {
  86801. return;
  86802. }
  86803. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86804. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  86805. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  86806. // Lens start rotation matrix
  86807. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  86808. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  86809. 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));
  86810. camRot *= 4.0;
  86811. 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);
  86812. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  86813. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  86814. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  86815. };
  86816. };
  86817. // Create depth-of-field post-process
  86818. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  86819. var _this = this;
  86820. 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);
  86821. this.depthOfFieldPostProcess.onApply = function (effect) {
  86822. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86823. effect.setTexture("depthSampler", _this._getDepthTexture());
  86824. effect.setFloat("distance", _this.depthOfFieldDistance);
  86825. };
  86826. // Add to pipeline
  86827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  86828. };
  86829. // Create motion blur post-process
  86830. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  86831. var _this = this;
  86832. 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);
  86833. var motionScale = 0;
  86834. var prevViewProjection = BABYLON.Matrix.Identity();
  86835. var invViewProjection = BABYLON.Matrix.Identity();
  86836. var viewProjection = BABYLON.Matrix.Identity();
  86837. var screenSize = BABYLON.Vector2.Zero();
  86838. this.motionBlurPostProcess.onApply = function (effect) {
  86839. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  86840. viewProjection.invertToRef(invViewProjection);
  86841. effect.setMatrix("inverseViewProjection", invViewProjection);
  86842. effect.setMatrix("prevViewProjection", prevViewProjection);
  86843. prevViewProjection = viewProjection;
  86844. screenSize.x = _this.motionBlurPostProcess.width;
  86845. screenSize.y = _this.motionBlurPostProcess.height;
  86846. effect.setVector2("screenSize", screenSize);
  86847. motionScale = scene.getEngine().getFps() / 60.0;
  86848. effect.setFloat("motionScale", motionScale);
  86849. effect.setFloat("motionStrength", _this.motionStrength);
  86850. effect.setTexture("depthSampler", _this._getDepthTexture());
  86851. };
  86852. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  86853. };
  86854. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  86855. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  86856. var renderer = this._scene.enableGeometryBufferRenderer();
  86857. return renderer.getGBuffer().textures[0];
  86858. }
  86859. return this._scene.enableDepthRenderer().getDepthMap();
  86860. };
  86861. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  86862. for (var i = 0; i < this._cameras.length; i++) {
  86863. var camera = this._cameras[i];
  86864. if (this.originalPostProcess) {
  86865. this.originalPostProcess.dispose(camera);
  86866. }
  86867. if (this.downSampleX4PostProcess) {
  86868. this.downSampleX4PostProcess.dispose(camera);
  86869. }
  86870. if (this.brightPassPostProcess) {
  86871. this.brightPassPostProcess.dispose(camera);
  86872. }
  86873. if (this.textureAdderPostProcess) {
  86874. this.textureAdderPostProcess.dispose(camera);
  86875. }
  86876. if (this.textureAdderFinalPostProcess) {
  86877. this.textureAdderFinalPostProcess.dispose(camera);
  86878. }
  86879. if (this.volumetricLightPostProcess) {
  86880. this.volumetricLightPostProcess.dispose(camera);
  86881. }
  86882. if (this.volumetricLightSmoothXPostProcess) {
  86883. this.volumetricLightSmoothXPostProcess.dispose(camera);
  86884. }
  86885. if (this.volumetricLightSmoothYPostProcess) {
  86886. this.volumetricLightSmoothYPostProcess.dispose(camera);
  86887. }
  86888. if (this.volumetricLightMergePostProces) {
  86889. this.volumetricLightMergePostProces.dispose(camera);
  86890. }
  86891. if (this.volumetricLightFinalPostProcess) {
  86892. this.volumetricLightFinalPostProcess.dispose(camera);
  86893. }
  86894. if (this.lensFlarePostProcess) {
  86895. this.lensFlarePostProcess.dispose(camera);
  86896. }
  86897. if (this.lensFlareComposePostProcess) {
  86898. this.lensFlareComposePostProcess.dispose(camera);
  86899. }
  86900. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  86901. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  86902. }
  86903. if (this.luminancePostProcess) {
  86904. this.luminancePostProcess.dispose(camera);
  86905. }
  86906. if (this.hdrPostProcess) {
  86907. this.hdrPostProcess.dispose(camera);
  86908. }
  86909. if (this.hdrFinalPostProcess) {
  86910. this.hdrFinalPostProcess.dispose(camera);
  86911. }
  86912. if (this.depthOfFieldPostProcess) {
  86913. this.depthOfFieldPostProcess.dispose(camera);
  86914. }
  86915. if (this.motionBlurPostProcess) {
  86916. this.motionBlurPostProcess.dispose(camera);
  86917. }
  86918. if (this.fxaaPostProcess) {
  86919. this.fxaaPostProcess.dispose(camera);
  86920. }
  86921. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  86922. this.blurHPostProcesses[j].dispose(camera);
  86923. }
  86924. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  86925. this.blurVPostProcesses[j].dispose(camera);
  86926. }
  86927. }
  86928. this.originalPostProcess = null;
  86929. this.downSampleX4PostProcess = null;
  86930. this.brightPassPostProcess = null;
  86931. this.textureAdderPostProcess = null;
  86932. this.textureAdderFinalPostProcess = null;
  86933. this.volumetricLightPostProcess = null;
  86934. this.volumetricLightSmoothXPostProcess = null;
  86935. this.volumetricLightSmoothYPostProcess = null;
  86936. this.volumetricLightMergePostProces = null;
  86937. this.volumetricLightFinalPostProcess = null;
  86938. this.lensFlarePostProcess = null;
  86939. this.lensFlareComposePostProcess = null;
  86940. this.luminancePostProcess = null;
  86941. this.hdrPostProcess = null;
  86942. this.hdrFinalPostProcess = null;
  86943. this.depthOfFieldPostProcess = null;
  86944. this.motionBlurPostProcess = null;
  86945. this.fxaaPostProcess = null;
  86946. this.luminanceDownSamplePostProcesses = [];
  86947. this.blurHPostProcesses = [];
  86948. this.blurVPostProcesses = [];
  86949. };
  86950. /**
  86951. * Dispose of the pipeline and stop all post processes
  86952. */
  86953. StandardRenderingPipeline.prototype.dispose = function () {
  86954. this._disposePostProcesses();
  86955. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86956. _super.prototype.dispose.call(this);
  86957. };
  86958. /**
  86959. * Serialize the rendering pipeline (Used when exporting)
  86960. * @returns the serialized object
  86961. */
  86962. StandardRenderingPipeline.prototype.serialize = function () {
  86963. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86964. if (this.sourceLight) {
  86965. serializationObject.sourceLightId = this.sourceLight.id;
  86966. }
  86967. serializationObject.customType = "StandardRenderingPipeline";
  86968. return serializationObject;
  86969. };
  86970. /**
  86971. * Parse the serialized pipeline
  86972. * @param source Source pipeline.
  86973. * @param scene The scene to load the pipeline to.
  86974. * @param rootUrl The URL of the serialized pipeline.
  86975. * @returns An instantiated pipeline from the serialized object.
  86976. */
  86977. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86978. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  86979. if (source.sourceLightId) {
  86980. p.sourceLight = scene.getLightByID(source.sourceLightId);
  86981. }
  86982. return p;
  86983. };
  86984. /**
  86985. * Luminance steps
  86986. */
  86987. StandardRenderingPipeline.LuminanceSteps = 6;
  86988. __decorate([
  86989. BABYLON.serialize()
  86990. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  86991. __decorate([
  86992. BABYLON.serialize()
  86993. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  86994. __decorate([
  86995. BABYLON.serialize()
  86996. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  86997. __decorate([
  86998. BABYLON.serialize()
  86999. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  87000. __decorate([
  87001. BABYLON.serializeAsTexture("lensTexture")
  87002. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  87003. __decorate([
  87004. BABYLON.serialize()
  87005. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  87006. __decorate([
  87007. BABYLON.serialize()
  87008. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  87009. __decorate([
  87010. BABYLON.serialize()
  87011. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  87012. __decorate([
  87013. BABYLON.serialize()
  87014. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  87015. __decorate([
  87016. BABYLON.serialize()
  87017. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  87018. __decorate([
  87019. BABYLON.serialize()
  87020. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  87021. __decorate([
  87022. BABYLON.serializeAsTexture("lensColorTexture")
  87023. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  87024. __decorate([
  87025. BABYLON.serialize()
  87026. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  87027. __decorate([
  87028. BABYLON.serialize()
  87029. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  87030. __decorate([
  87031. BABYLON.serialize()
  87032. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  87033. __decorate([
  87034. BABYLON.serialize()
  87035. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  87036. __decorate([
  87037. BABYLON.serializeAsTexture("lensStarTexture")
  87038. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  87039. __decorate([
  87040. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  87041. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  87042. __decorate([
  87043. BABYLON.serialize()
  87044. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  87045. __decorate([
  87046. BABYLON.serialize()
  87047. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  87048. __decorate([
  87049. BABYLON.serialize()
  87050. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  87051. __decorate([
  87052. BABYLON.serialize()
  87053. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  87054. __decorate([
  87055. BABYLON.serialize()
  87056. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  87057. __decorate([
  87058. BABYLON.serialize()
  87059. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  87060. __decorate([
  87061. BABYLON.serialize()
  87062. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  87063. __decorate([
  87064. BABYLON.serialize()
  87065. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  87066. __decorate([
  87067. BABYLON.serialize()
  87068. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  87069. __decorate([
  87070. BABYLON.serialize()
  87071. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  87072. __decorate([
  87073. BABYLON.serialize()
  87074. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  87075. __decorate([
  87076. BABYLON.serialize()
  87077. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  87078. __decorate([
  87079. BABYLON.serialize()
  87080. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  87081. __decorate([
  87082. BABYLON.serialize()
  87083. ], StandardRenderingPipeline.prototype, "samples", null);
  87084. return StandardRenderingPipeline;
  87085. }(BABYLON.PostProcessRenderPipeline));
  87086. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  87087. })(BABYLON || (BABYLON = {}));
  87088. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  87089. var BABYLON;
  87090. (function (BABYLON) {
  87091. /**
  87092. * Fxaa post process
  87093. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  87094. */
  87095. var FxaaPostProcess = /** @class */ (function (_super) {
  87096. __extends(FxaaPostProcess, _super);
  87097. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  87098. if (camera === void 0) { camera = null; }
  87099. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87100. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  87101. var defines = _this._getDefines();
  87102. _this.updateEffect(defines);
  87103. _this.onApplyObservable.add(function (effect) {
  87104. var texelSize = _this.texelSize;
  87105. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  87106. });
  87107. return _this;
  87108. }
  87109. FxaaPostProcess.prototype._getDefines = function () {
  87110. var engine = this.getEngine();
  87111. if (!engine) {
  87112. return null;
  87113. }
  87114. var glInfo = engine.getGlInfo();
  87115. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  87116. return "#define MALI 1\n";
  87117. }
  87118. return null;
  87119. };
  87120. return FxaaPostProcess;
  87121. }(BABYLON.PostProcess));
  87122. BABYLON.FxaaPostProcess = FxaaPostProcess;
  87123. })(BABYLON || (BABYLON = {}));
  87124. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  87125. var BABYLON;
  87126. (function (BABYLON) {
  87127. /**
  87128. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  87129. */
  87130. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  87131. __extends(ChromaticAberrationPostProcess, _super);
  87132. /**
  87133. * Creates a new instance ChromaticAberrationPostProcess
  87134. * @param name The name of the effect.
  87135. * @param screenWidth The width of the screen to apply the effect on.
  87136. * @param screenHeight The height of the screen to apply the effect on.
  87137. * @param options The required width/height ratio to downsize to before computing the render pass.
  87138. * @param camera The camera to apply the render pass to.
  87139. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87140. * @param engine The engine which the post process will be applied. (default: current engine)
  87141. * @param reusable If the post process can be reused on the same frame. (default: false)
  87142. * @param textureType Type of textures used when performing the post process. (default: 0)
  87143. * @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)
  87144. */
  87145. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87146. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87147. if (blockCompilation === void 0) { blockCompilation = false; }
  87148. 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;
  87149. /**
  87150. * The amount of seperation of rgb channels (default: 30)
  87151. */
  87152. _this.aberrationAmount = 30;
  87153. /**
  87154. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  87155. */
  87156. _this.radialIntensity = 0;
  87157. /**
  87158. * 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))
  87159. */
  87160. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  87161. /**
  87162. * 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))
  87163. */
  87164. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  87165. _this.onApplyObservable.add(function (effect) {
  87166. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  87167. effect.setFloat('screen_width', screenWidth);
  87168. effect.setFloat('screen_height', screenHeight);
  87169. effect.setFloat('radialIntensity', _this.radialIntensity);
  87170. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  87171. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  87172. });
  87173. return _this;
  87174. }
  87175. return ChromaticAberrationPostProcess;
  87176. }(BABYLON.PostProcess));
  87177. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  87178. })(BABYLON || (BABYLON = {}));
  87179. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  87180. var BABYLON;
  87181. (function (BABYLON) {
  87182. /**
  87183. * The GrainPostProcess adds noise to the image at mid luminance levels
  87184. */
  87185. var GrainPostProcess = /** @class */ (function (_super) {
  87186. __extends(GrainPostProcess, _super);
  87187. /**
  87188. * Creates a new instance of @see GrainPostProcess
  87189. * @param name The name of the effect.
  87190. * @param options The required width/height ratio to downsize to before computing the render pass.
  87191. * @param camera The camera to apply the render pass to.
  87192. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87193. * @param engine The engine which the post process will be applied. (default: current engine)
  87194. * @param reusable If the post process can be reused on the same frame. (default: false)
  87195. * @param textureType Type of textures used when performing the post process. (default: 0)
  87196. * @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)
  87197. */
  87198. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87199. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87200. if (blockCompilation === void 0) { blockCompilation = false; }
  87201. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87202. /**
  87203. * The intensity of the grain added (default: 30)
  87204. */
  87205. _this.intensity = 30;
  87206. /**
  87207. * If the grain should be randomized on every frame
  87208. */
  87209. _this.animated = false;
  87210. _this.onApplyObservable.add(function (effect) {
  87211. effect.setFloat('intensity', _this.intensity);
  87212. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  87213. });
  87214. return _this;
  87215. }
  87216. return GrainPostProcess;
  87217. }(BABYLON.PostProcess));
  87218. BABYLON.GrainPostProcess = GrainPostProcess;
  87219. })(BABYLON || (BABYLON = {}));
  87220. //# sourceMappingURL=babylon.grainPostProcess.js.map
  87221. var BABYLON;
  87222. (function (BABYLON) {
  87223. /**
  87224. * The SharpenPostProcess applies a sharpen kernel to every pixel
  87225. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87226. */
  87227. var SharpenPostProcess = /** @class */ (function (_super) {
  87228. __extends(SharpenPostProcess, _super);
  87229. /**
  87230. * Creates a new instance ConvolutionPostProcess
  87231. * @param name The name of the effect.
  87232. * @param options The required width/height ratio to downsize to before computing the render pass.
  87233. * @param camera The camera to apply the render pass to.
  87234. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87235. * @param engine The engine which the post process will be applied. (default: current engine)
  87236. * @param reusable If the post process can be reused on the same frame. (default: false)
  87237. * @param textureType Type of textures used when performing the post process. (default: 0)
  87238. * @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)
  87239. */
  87240. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87241. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87242. if (blockCompilation === void 0) { blockCompilation = false; }
  87243. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87244. /**
  87245. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  87246. */
  87247. _this.colorAmount = 1.0;
  87248. /**
  87249. * How much sharpness should be applied (default: 0.3)
  87250. */
  87251. _this.edgeAmount = 0.3;
  87252. _this.onApply = function (effect) {
  87253. effect.setFloat2("screenSize", _this.width, _this.height);
  87254. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  87255. };
  87256. return _this;
  87257. }
  87258. return SharpenPostProcess;
  87259. }(BABYLON.PostProcess));
  87260. BABYLON.SharpenPostProcess = SharpenPostProcess;
  87261. })(BABYLON || (BABYLON = {}));
  87262. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  87263. var BABYLON;
  87264. (function (BABYLON) {
  87265. /**
  87266. * The Blur Post Process which blurs an image based on a kernel and direction.
  87267. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  87268. */
  87269. var BlurPostProcess = /** @class */ (function (_super) {
  87270. __extends(BlurPostProcess, _super);
  87271. /**
  87272. * Creates a new instance BlurPostProcess
  87273. * @param name The name of the effect.
  87274. * @param direction The direction in which to blur the image.
  87275. * @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.
  87276. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  87277. * @param camera The camera to apply the render pass to.
  87278. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87279. * @param engine The engine which the post process will be applied. (default: current engine)
  87280. * @param reusable If the post process can be reused on the same frame. (default: false)
  87281. * @param textureType Type of textures used when performing the post process. (default: 0)
  87282. * @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)
  87283. */
  87284. function BlurPostProcess(name,
  87285. /** The direction in which to blur the image. */
  87286. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  87287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87288. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87289. if (defines === void 0) { defines = ""; }
  87290. if (blockCompilation === void 0) { blockCompilation = false; }
  87291. 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;
  87292. _this.direction = direction;
  87293. _this.blockCompilation = blockCompilation;
  87294. _this._packedFloat = false;
  87295. _this._staticDefines = "";
  87296. _this._staticDefines = defines;
  87297. _this.onApplyObservable.add(function (effect) {
  87298. if (_this._outputTexture) {
  87299. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  87300. }
  87301. else {
  87302. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  87303. }
  87304. });
  87305. _this.kernel = kernel;
  87306. return _this;
  87307. }
  87308. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  87309. /**
  87310. * Gets the length in pixels of the blur sample region
  87311. */
  87312. get: function () {
  87313. return this._idealKernel;
  87314. },
  87315. /**
  87316. * Sets the length in pixels of the blur sample region
  87317. */
  87318. set: function (v) {
  87319. if (this._idealKernel === v) {
  87320. return;
  87321. }
  87322. v = Math.max(v, 1);
  87323. this._idealKernel = v;
  87324. this._kernel = this._nearestBestKernel(v);
  87325. if (!this.blockCompilation) {
  87326. this._updateParameters();
  87327. }
  87328. },
  87329. enumerable: true,
  87330. configurable: true
  87331. });
  87332. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  87333. /**
  87334. * Gets wether or not the blur is unpacking/repacking floats
  87335. */
  87336. get: function () {
  87337. return this._packedFloat;
  87338. },
  87339. /**
  87340. * Sets wether or not the blur needs to unpack/repack floats
  87341. */
  87342. set: function (v) {
  87343. if (this._packedFloat === v) {
  87344. return;
  87345. }
  87346. this._packedFloat = v;
  87347. if (!this.blockCompilation) {
  87348. this._updateParameters();
  87349. }
  87350. },
  87351. enumerable: true,
  87352. configurable: true
  87353. });
  87354. /**
  87355. * Updates the effect with the current post process compile time values and recompiles the shader.
  87356. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87357. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87358. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87359. * @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
  87360. * @param onCompiled Called when the shader has been compiled.
  87361. * @param onError Called if there is an error when compiling a shader.
  87362. */
  87363. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87364. if (defines === void 0) { defines = null; }
  87365. if (uniforms === void 0) { uniforms = null; }
  87366. if (samplers === void 0) { samplers = null; }
  87367. this._updateParameters(onCompiled, onError);
  87368. };
  87369. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  87370. // Generate sampling offsets and weights
  87371. var N = this._kernel;
  87372. var centerIndex = (N - 1) / 2;
  87373. // Generate Gaussian sampling weights over kernel
  87374. var offsets = [];
  87375. var weights = [];
  87376. var totalWeight = 0;
  87377. for (var i = 0; i < N; i++) {
  87378. var u = i / (N - 1);
  87379. var w = this._gaussianWeight(u * 2.0 - 1);
  87380. offsets[i] = (i - centerIndex);
  87381. weights[i] = w;
  87382. totalWeight += w;
  87383. }
  87384. // Normalize weights
  87385. for (var i = 0; i < weights.length; i++) {
  87386. weights[i] /= totalWeight;
  87387. }
  87388. // Optimize: combine samples to take advantage of hardware linear sampling
  87389. // Walk from left to center, combining pairs (symmetrically)
  87390. var linearSamplingWeights = [];
  87391. var linearSamplingOffsets = [];
  87392. var linearSamplingMap = [];
  87393. for (var i = 0; i <= centerIndex; i += 2) {
  87394. var j = Math.min(i + 1, Math.floor(centerIndex));
  87395. var singleCenterSample = i === j;
  87396. if (singleCenterSample) {
  87397. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87398. }
  87399. else {
  87400. var sharedCell = j === centerIndex;
  87401. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  87402. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  87403. if (offsetLinear === 0) {
  87404. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87405. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  87406. }
  87407. else {
  87408. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  87409. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  87410. }
  87411. }
  87412. }
  87413. for (var i = 0; i < linearSamplingMap.length; i++) {
  87414. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  87415. linearSamplingWeights[i] = linearSamplingMap[i].w;
  87416. }
  87417. // Replace with optimized
  87418. offsets = linearSamplingOffsets;
  87419. weights = linearSamplingWeights;
  87420. // Generate shaders
  87421. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  87422. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  87423. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  87424. var defines = "";
  87425. defines += this._staticDefines;
  87426. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  87427. if (this._staticDefines.indexOf("DOF") != -1) {
  87428. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  87429. varyingCount--;
  87430. }
  87431. for (var i = 0; i < varyingCount; i++) {
  87432. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  87433. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  87434. }
  87435. var depCount = 0;
  87436. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  87437. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  87438. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  87439. depCount++;
  87440. }
  87441. if (this.packedFloat) {
  87442. defines += "#define PACKEDFLOAT 1";
  87443. }
  87444. this.blockCompilation = false;
  87445. _super.prototype.updateEffect.call(this, defines, null, null, {
  87446. varyingCount: varyingCount,
  87447. depCount: depCount
  87448. }, onCompiled, onError);
  87449. };
  87450. /**
  87451. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  87452. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  87453. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  87454. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  87455. * The gaps between physical kernels are compensated for in the weighting of the samples
  87456. * @param idealKernel Ideal blur kernel.
  87457. * @return Nearest best kernel.
  87458. */
  87459. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  87460. var v = Math.round(idealKernel);
  87461. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  87462. var k = _a[_i];
  87463. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  87464. return Math.max(k, 3);
  87465. }
  87466. }
  87467. return Math.max(v, 3);
  87468. };
  87469. /**
  87470. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  87471. * @param x The point on the Gaussian distribution to sample.
  87472. * @return the value of the Gaussian function at x.
  87473. */
  87474. BlurPostProcess.prototype._gaussianWeight = function (x) {
  87475. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  87476. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  87477. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  87478. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  87479. // truncated at around 1.3% of peak strength.
  87480. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  87481. var sigma = (1 / 3);
  87482. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  87483. var exponent = -((x * x) / (2.0 * sigma * sigma));
  87484. var weight = (1.0 / denominator) * Math.exp(exponent);
  87485. return weight;
  87486. };
  87487. /**
  87488. * Generates a string that can be used as a floating point number in GLSL.
  87489. * @param x Value to print.
  87490. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  87491. * @return GLSL float string.
  87492. */
  87493. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  87494. if (decimalFigures === void 0) { decimalFigures = 8; }
  87495. return x.toFixed(decimalFigures).replace(/0+$/, '');
  87496. };
  87497. return BlurPostProcess;
  87498. }(BABYLON.PostProcess));
  87499. BABYLON.BlurPostProcess = BlurPostProcess;
  87500. })(BABYLON || (BABYLON = {}));
  87501. //# sourceMappingURL=babylon.blurPostProcess.js.map
  87502. var BABYLON;
  87503. (function (BABYLON) {
  87504. /**
  87505. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  87506. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  87507. * based on samples that have a large difference in distance than the center pixel.
  87508. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87509. */
  87510. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  87511. __extends(DepthOfFieldBlurPostProcess, _super);
  87512. /**
  87513. * Creates a new instance CircleOfConfusionPostProcess
  87514. * @param name The name of the effect.
  87515. * @param scene The scene the effect belongs to.
  87516. * @param direction The direction the blur should be applied.
  87517. * @param kernel The size of the kernel used to blur.
  87518. * @param options The required width/height ratio to downsize to before computing the render pass.
  87519. * @param camera The camera to apply the render pass to.
  87520. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  87521. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  87522. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87523. * @param engine The engine which the post process will be applied. (default: current engine)
  87524. * @param reusable If the post process can be reused on the same frame. (default: false)
  87525. * @param textureType Type of textures used when performing the post process. (default: 0)
  87526. * @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)
  87527. */
  87528. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  87529. if (imageToBlur === void 0) { imageToBlur = null; }
  87530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87531. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87532. if (blockCompilation === void 0) { blockCompilation = false; }
  87533. 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;
  87534. _this.direction = direction;
  87535. _this.onApplyObservable.add(function (effect) {
  87536. if (imageToBlur != null) {
  87537. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  87538. }
  87539. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87540. if (scene.activeCamera) {
  87541. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87542. }
  87543. });
  87544. return _this;
  87545. }
  87546. return DepthOfFieldBlurPostProcess;
  87547. }(BABYLON.BlurPostProcess));
  87548. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  87549. })(BABYLON || (BABYLON = {}));
  87550. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  87551. var BABYLON;
  87552. (function (BABYLON) {
  87553. /**
  87554. * Options to be set when merging outputs from the default pipeline.
  87555. */
  87556. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  87557. function DepthOfFieldMergePostProcessOptions() {
  87558. }
  87559. return DepthOfFieldMergePostProcessOptions;
  87560. }());
  87561. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  87562. /**
  87563. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87564. */
  87565. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  87566. __extends(DepthOfFieldMergePostProcess, _super);
  87567. /**
  87568. * Creates a new instance of DepthOfFieldMergePostProcess
  87569. * @param name The name of the effect.
  87570. * @param originalFromInput Post process which's input will be used for the merge.
  87571. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  87572. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  87573. * @param options The required width/height ratio to downsize to before computing the render pass.
  87574. * @param camera The camera to apply the render pass to.
  87575. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87576. * @param engine The engine which the post process will be applied. (default: current engine)
  87577. * @param reusable If the post process can be reused on the same frame. (default: false)
  87578. * @param textureType Type of textures used when performing the post process. (default: 0)
  87579. * @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)
  87580. */
  87581. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87582. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87583. if (blockCompilation === void 0) { blockCompilation = false; }
  87584. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87585. _this.blurSteps = blurSteps;
  87586. _this.onApplyObservable.add(function (effect) {
  87587. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87588. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87589. blurSteps.forEach(function (step, index) {
  87590. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  87591. });
  87592. });
  87593. if (!blockCompilation) {
  87594. _this.updateEffect();
  87595. }
  87596. return _this;
  87597. }
  87598. /**
  87599. * Updates the effect with the current post process compile time values and recompiles the shader.
  87600. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87601. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87602. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87603. * @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
  87604. * @param onCompiled Called when the shader has been compiled.
  87605. * @param onError Called if there is an error when compiling a shader.
  87606. */
  87607. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87608. if (defines === void 0) { defines = null; }
  87609. if (uniforms === void 0) { uniforms = null; }
  87610. if (samplers === void 0) { samplers = null; }
  87611. if (!defines) {
  87612. defines = "";
  87613. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  87614. }
  87615. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  87616. };
  87617. return DepthOfFieldMergePostProcess;
  87618. }(BABYLON.PostProcess));
  87619. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  87620. })(BABYLON || (BABYLON = {}));
  87621. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  87622. var BABYLON;
  87623. (function (BABYLON) {
  87624. /**
  87625. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  87626. */
  87627. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  87628. __extends(CircleOfConfusionPostProcess, _super);
  87629. /**
  87630. * Creates a new instance CircleOfConfusionPostProcess
  87631. * @param name The name of the effect.
  87632. * @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.
  87633. * @param options The required width/height ratio to downsize to before computing the render pass.
  87634. * @param camera The camera to apply the render pass to.
  87635. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87636. * @param engine The engine which the post process will be applied. (default: current engine)
  87637. * @param reusable If the post process can be reused on the same frame. (default: false)
  87638. * @param textureType Type of textures used when performing the post process. (default: 0)
  87639. * @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)
  87640. */
  87641. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87642. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87643. if (blockCompilation === void 0) { blockCompilation = false; }
  87644. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87645. /**
  87646. * 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.
  87647. */
  87648. _this.lensSize = 50;
  87649. /**
  87650. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87651. */
  87652. _this.fStop = 1.4;
  87653. /**
  87654. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87655. */
  87656. _this.focusDistance = 2000;
  87657. /**
  87658. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  87659. */
  87660. _this.focalLength = 50;
  87661. _this._depthTexture = null;
  87662. _this._depthTexture = depthTexture;
  87663. _this.onApplyObservable.add(function (effect) {
  87664. if (!_this._depthTexture) {
  87665. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  87666. return;
  87667. }
  87668. effect.setTexture("depthSampler", _this._depthTexture);
  87669. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  87670. var aperture = _this.lensSize / _this.fStop;
  87671. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  87672. effect.setFloat('focusDistance', _this.focusDistance);
  87673. effect.setFloat('cocPrecalculation', cocPrecalculation);
  87674. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  87675. });
  87676. return _this;
  87677. }
  87678. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  87679. /**
  87680. * 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.
  87681. */
  87682. set: function (value) {
  87683. this._depthTexture = value;
  87684. },
  87685. enumerable: true,
  87686. configurable: true
  87687. });
  87688. return CircleOfConfusionPostProcess;
  87689. }(BABYLON.PostProcess));
  87690. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  87691. })(BABYLON || (BABYLON = {}));
  87692. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  87693. var BABYLON;
  87694. (function (BABYLON) {
  87695. /**
  87696. * Specifies the level of max blur that should be applied when using the depth of field effect
  87697. */
  87698. var DepthOfFieldEffectBlurLevel;
  87699. (function (DepthOfFieldEffectBlurLevel) {
  87700. /**
  87701. * Subtle blur
  87702. */
  87703. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  87704. /**
  87705. * Medium blur
  87706. */
  87707. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  87708. /**
  87709. * Large blur
  87710. */
  87711. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  87712. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  87713. /**
  87714. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  87715. */
  87716. var DepthOfFieldEffect = /** @class */ (function (_super) {
  87717. __extends(DepthOfFieldEffect, _super);
  87718. /**
  87719. * Creates a new instance DepthOfFieldEffect
  87720. * @param scene The scene the effect belongs to.
  87721. * @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.
  87722. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87723. * @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)
  87724. */
  87725. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  87726. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  87727. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87728. if (blockCompilation === void 0) { blockCompilation = false; }
  87729. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  87730. return _this._effects;
  87731. }, true) || this;
  87732. /**
  87733. * @hidden Internal post processes in depth of field effect
  87734. */
  87735. _this._effects = [];
  87736. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  87737. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87738. // 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)
  87739. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  87740. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87741. _this._depthOfFieldBlurY = [];
  87742. _this._depthOfFieldBlurX = [];
  87743. var blurCount = 1;
  87744. var kernelSize = 15;
  87745. switch (blurLevel) {
  87746. case DepthOfFieldEffectBlurLevel.High: {
  87747. blurCount = 3;
  87748. kernelSize = 51;
  87749. break;
  87750. }
  87751. case DepthOfFieldEffectBlurLevel.Medium: {
  87752. blurCount = 2;
  87753. kernelSize = 31;
  87754. break;
  87755. }
  87756. default: {
  87757. kernelSize = 15;
  87758. blurCount = 1;
  87759. break;
  87760. }
  87761. }
  87762. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  87763. var ratio = 1.0;
  87764. for (var i = 0; i < blurCount; i++) {
  87765. 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);
  87766. blurY.autoClear = false;
  87767. ratio = 0.75 / Math.pow(2, i);
  87768. 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);
  87769. blurX.autoClear = false;
  87770. _this._depthOfFieldBlurY.push(blurY);
  87771. _this._depthOfFieldBlurX.push(blurX);
  87772. }
  87773. // Set all post processes on the effect.
  87774. _this._effects = [_this._circleOfConfusion];
  87775. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  87776. _this._effects.push(_this._depthOfFieldBlurY[i]);
  87777. _this._effects.push(_this._depthOfFieldBlurX[i]);
  87778. }
  87779. // Merge blurred images with original image based on circleOfConfusion
  87780. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87781. _this._dofMerge.autoClear = false;
  87782. _this._effects.push(_this._dofMerge);
  87783. return _this;
  87784. }
  87785. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  87786. get: function () {
  87787. return this._circleOfConfusion.focalLength;
  87788. },
  87789. /**
  87790. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  87791. */
  87792. set: function (value) {
  87793. this._circleOfConfusion.focalLength = value;
  87794. },
  87795. enumerable: true,
  87796. configurable: true
  87797. });
  87798. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  87799. get: function () {
  87800. return this._circleOfConfusion.fStop;
  87801. },
  87802. /**
  87803. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87804. */
  87805. set: function (value) {
  87806. this._circleOfConfusion.fStop = value;
  87807. },
  87808. enumerable: true,
  87809. configurable: true
  87810. });
  87811. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  87812. get: function () {
  87813. return this._circleOfConfusion.focusDistance;
  87814. },
  87815. /**
  87816. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87817. */
  87818. set: function (value) {
  87819. this._circleOfConfusion.focusDistance = value;
  87820. },
  87821. enumerable: true,
  87822. configurable: true
  87823. });
  87824. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  87825. get: function () {
  87826. return this._circleOfConfusion.lensSize;
  87827. },
  87828. /**
  87829. * 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.
  87830. */
  87831. set: function (value) {
  87832. this._circleOfConfusion.lensSize = value;
  87833. },
  87834. enumerable: true,
  87835. configurable: true
  87836. });
  87837. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  87838. /**
  87839. * 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.
  87840. */
  87841. set: function (value) {
  87842. this._circleOfConfusion.depthTexture = value;
  87843. },
  87844. enumerable: true,
  87845. configurable: true
  87846. });
  87847. /**
  87848. * Disposes each of the internal effects for a given camera.
  87849. * @param camera The camera to dispose the effect on.
  87850. */
  87851. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  87852. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87853. this._effects[effectIndex].dispose(camera);
  87854. }
  87855. };
  87856. /**
  87857. * @hidden Internal
  87858. */
  87859. DepthOfFieldEffect.prototype._updateEffects = function () {
  87860. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87861. this._effects[effectIndex].updateEffect();
  87862. }
  87863. };
  87864. /**
  87865. * Internal
  87866. * @returns if all the contained post processes are ready.
  87867. * @hidden
  87868. */
  87869. DepthOfFieldEffect.prototype._isReady = function () {
  87870. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87871. if (!this._effects[effectIndex].isReady()) {
  87872. return false;
  87873. }
  87874. }
  87875. return true;
  87876. };
  87877. return DepthOfFieldEffect;
  87878. }(BABYLON.PostProcessRenderEffect));
  87879. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  87880. })(BABYLON || (BABYLON = {}));
  87881. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  87882. var BABYLON;
  87883. (function (BABYLON) {
  87884. /**
  87885. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87886. */
  87887. var BloomMergePostProcess = /** @class */ (function (_super) {
  87888. __extends(BloomMergePostProcess, _super);
  87889. /**
  87890. * Creates a new instance of @see BloomMergePostProcess
  87891. * @param name The name of the effect.
  87892. * @param originalFromInput Post process which's input will be used for the merge.
  87893. * @param blurred Blurred highlights post process which's output will be used.
  87894. * @param weight Weight of the bloom to be added to the original input.
  87895. * @param options The required width/height ratio to downsize to before computing the render pass.
  87896. * @param camera The camera to apply the render pass to.
  87897. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87898. * @param engine The engine which the post process will be applied. (default: current engine)
  87899. * @param reusable If the post process can be reused on the same frame. (default: false)
  87900. * @param textureType Type of textures used when performing the post process. (default: 0)
  87901. * @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)
  87902. */
  87903. function BloomMergePostProcess(name, originalFromInput, blurred,
  87904. /** Weight of the bloom to be added to the original input. */
  87905. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87906. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87907. if (blockCompilation === void 0) { blockCompilation = false; }
  87908. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87909. _this.weight = weight;
  87910. _this.onApplyObservable.add(function (effect) {
  87911. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87912. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  87913. effect.setFloat("bloomWeight", _this.weight);
  87914. });
  87915. if (!blockCompilation) {
  87916. _this.updateEffect();
  87917. }
  87918. return _this;
  87919. }
  87920. return BloomMergePostProcess;
  87921. }(BABYLON.PostProcess));
  87922. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  87923. })(BABYLON || (BABYLON = {}));
  87924. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  87925. var BABYLON;
  87926. (function (BABYLON) {
  87927. /**
  87928. * 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.
  87929. */
  87930. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  87931. __extends(ExtractHighlightsPostProcess, _super);
  87932. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87933. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87934. if (blockCompilation === void 0) { blockCompilation = false; }
  87935. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87936. /**
  87937. * The luminance threshold, pixels below this value will be set to black.
  87938. */
  87939. _this.threshold = 0.9;
  87940. /** @hidden */
  87941. _this._exposure = 1;
  87942. /**
  87943. * Post process which has the input texture to be used when performing highlight extraction
  87944. * @hidden
  87945. */
  87946. _this._inputPostProcess = null;
  87947. _this.onApplyObservable.add(function (effect) {
  87948. if (_this._inputPostProcess) {
  87949. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  87950. }
  87951. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  87952. effect.setFloat('exposure', _this._exposure);
  87953. });
  87954. return _this;
  87955. }
  87956. return ExtractHighlightsPostProcess;
  87957. }(BABYLON.PostProcess));
  87958. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  87959. })(BABYLON || (BABYLON = {}));
  87960. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  87961. var BABYLON;
  87962. (function (BABYLON) {
  87963. /**
  87964. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  87965. */
  87966. var BloomEffect = /** @class */ (function (_super) {
  87967. __extends(BloomEffect, _super);
  87968. /**
  87969. * Creates a new instance of @see BloomEffect
  87970. * @param scene The scene the effect belongs to.
  87971. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  87972. * @param bloomKernel The size of the kernel to be used when applying the blur.
  87973. * @param bloomWeight The the strength of bloom.
  87974. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87975. * @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)
  87976. */
  87977. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  87978. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87979. if (blockCompilation === void 0) { blockCompilation = false; }
  87980. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  87981. return _this._effects;
  87982. }, true) || this;
  87983. _this.bloomScale = bloomScale;
  87984. /**
  87985. * @hidden Internal
  87986. */
  87987. _this._effects = [];
  87988. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87989. _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);
  87990. _this._blurX.alwaysForcePOT = true;
  87991. _this._blurX.autoClear = false;
  87992. _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);
  87993. _this._blurY.alwaysForcePOT = true;
  87994. _this._blurY.autoClear = false;
  87995. _this.kernel = bloomKernel;
  87996. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  87997. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87998. _this._merge.autoClear = false;
  87999. _this._effects.push(_this._merge);
  88000. return _this;
  88001. }
  88002. Object.defineProperty(BloomEffect.prototype, "threshold", {
  88003. /**
  88004. * The luminance threshold to find bright areas of the image to bloom.
  88005. */
  88006. get: function () {
  88007. return this._downscale.threshold;
  88008. },
  88009. set: function (value) {
  88010. this._downscale.threshold = value;
  88011. },
  88012. enumerable: true,
  88013. configurable: true
  88014. });
  88015. Object.defineProperty(BloomEffect.prototype, "weight", {
  88016. /**
  88017. * The strength of the bloom.
  88018. */
  88019. get: function () {
  88020. return this._merge.weight;
  88021. },
  88022. set: function (value) {
  88023. this._merge.weight = value;
  88024. },
  88025. enumerable: true,
  88026. configurable: true
  88027. });
  88028. Object.defineProperty(BloomEffect.prototype, "kernel", {
  88029. /**
  88030. * Specifies the size of the bloom blur kernel, relative to the final output size
  88031. */
  88032. get: function () {
  88033. return this._blurX.kernel / this.bloomScale;
  88034. },
  88035. set: function (value) {
  88036. this._blurX.kernel = value * this.bloomScale;
  88037. this._blurY.kernel = value * this.bloomScale;
  88038. },
  88039. enumerable: true,
  88040. configurable: true
  88041. });
  88042. /**
  88043. * Disposes each of the internal effects for a given camera.
  88044. * @param camera The camera to dispose the effect on.
  88045. */
  88046. BloomEffect.prototype.disposeEffects = function (camera) {
  88047. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88048. this._effects[effectIndex].dispose(camera);
  88049. }
  88050. };
  88051. /**
  88052. * @hidden Internal
  88053. */
  88054. BloomEffect.prototype._updateEffects = function () {
  88055. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88056. this._effects[effectIndex].updateEffect();
  88057. }
  88058. };
  88059. /**
  88060. * Internal
  88061. * @returns if all the contained post processes are ready.
  88062. * @hidden
  88063. */
  88064. BloomEffect.prototype._isReady = function () {
  88065. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88066. if (!this._effects[effectIndex].isReady()) {
  88067. return false;
  88068. }
  88069. }
  88070. return true;
  88071. };
  88072. return BloomEffect;
  88073. }(BABYLON.PostProcessRenderEffect));
  88074. BABYLON.BloomEffect = BloomEffect;
  88075. })(BABYLON || (BABYLON = {}));
  88076. //# sourceMappingURL=babylon.bloomEffect.js.map
  88077. var BABYLON;
  88078. (function (BABYLON) {
  88079. /**
  88080. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  88081. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  88082. */
  88083. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  88084. __extends(DefaultRenderingPipeline, _super);
  88085. /**
  88086. * @constructor
  88087. * @param name - The rendering pipeline name (default: "")
  88088. * @param hdr - If high dynamic range textures should be used (default: true)
  88089. * @param scene - The scene linked to this pipeline (default: the last created scene)
  88090. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  88091. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  88092. */
  88093. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  88094. if (name === void 0) { name = ""; }
  88095. if (hdr === void 0) { hdr = true; }
  88096. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  88097. if (automaticBuild === void 0) { automaticBuild = true; }
  88098. var _this = _super.call(this, scene.getEngine(), name) || this;
  88099. _this._camerasToBeAttached = [];
  88100. /**
  88101. * ID of the sharpen post process,
  88102. */
  88103. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  88104. /**
  88105. * @ignore
  88106. * ID of the image processing post process;
  88107. */
  88108. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  88109. /**
  88110. * @ignore
  88111. * ID of the Fast Approximate Anti-Aliasing post process;
  88112. */
  88113. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  88114. /**
  88115. * ID of the chromatic aberration post process,
  88116. */
  88117. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  88118. /**
  88119. * ID of the grain post process
  88120. */
  88121. _this.GrainPostProcessId = "GrainPostProcessEffect";
  88122. /**
  88123. * Glow post process which adds a glow to emmisive areas of the image
  88124. */
  88125. _this._glowLayer = null;
  88126. /**
  88127. * Animations which can be used to tweak settings over a period of time
  88128. */
  88129. _this.animations = [];
  88130. _this._imageProcessingConfigurationObserver = null;
  88131. // Values
  88132. _this._sharpenEnabled = false;
  88133. _this._bloomEnabled = false;
  88134. _this._depthOfFieldEnabled = false;
  88135. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  88136. _this._fxaaEnabled = false;
  88137. _this._imageProcessingEnabled = true;
  88138. _this._bloomScale = 0.5;
  88139. _this._chromaticAberrationEnabled = false;
  88140. _this._grainEnabled = false;
  88141. _this._buildAllowed = true;
  88142. _this._resizeObserver = null;
  88143. _this._hardwareScaleLevel = 1.0;
  88144. _this._bloomKernel = 64;
  88145. /**
  88146. * Specifies the weight of the bloom in the final rendering
  88147. */
  88148. _this._bloomWeight = 0.15;
  88149. /**
  88150. * Specifies the luma threshold for the area that will be blurred by the bloom
  88151. */
  88152. _this._bloomThreshold = 0.9;
  88153. _this._samples = 1;
  88154. _this._hasCleared = false;
  88155. _this._prevPostProcess = null;
  88156. _this._prevPrevPostProcess = null;
  88157. _this._depthOfFieldSceneObserver = null;
  88158. _this._cameras = cameras || scene.cameras;
  88159. _this._cameras = _this._cameras.slice();
  88160. _this._camerasToBeAttached = _this._cameras.slice();
  88161. _this._buildAllowed = automaticBuild;
  88162. // Initialize
  88163. _this._scene = scene;
  88164. var caps = _this._scene.getEngine().getCaps();
  88165. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  88166. // Misc
  88167. if (_this._hdr) {
  88168. if (caps.textureHalfFloatRender) {
  88169. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88170. }
  88171. else if (caps.textureFloatRender) {
  88172. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88173. }
  88174. }
  88175. else {
  88176. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88177. }
  88178. // Attach
  88179. scene.postProcessRenderPipelineManager.addPipeline(_this);
  88180. var engine = _this._scene.getEngine();
  88181. // Create post processes before hand so they can be modified before enabled.
  88182. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  88183. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88184. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  88185. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  88186. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  88187. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88188. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  88189. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88190. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  88191. _this._resizeObserver = engine.onResizeObservable.add(function () {
  88192. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  88193. _this.bloomKernel = _this.bloomKernel;
  88194. });
  88195. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  88196. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  88197. });
  88198. _this._buildPipeline();
  88199. return _this;
  88200. }
  88201. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  88202. get: function () {
  88203. return this._sharpenEnabled;
  88204. },
  88205. /**
  88206. * Enable or disable the sharpen process from the pipeline
  88207. */
  88208. set: function (enabled) {
  88209. if (this._sharpenEnabled === enabled) {
  88210. return;
  88211. }
  88212. this._sharpenEnabled = enabled;
  88213. this._buildPipeline();
  88214. },
  88215. enumerable: true,
  88216. configurable: true
  88217. });
  88218. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  88219. /**
  88220. * Specifies the size of the bloom blur kernel, relative to the final output size
  88221. */
  88222. get: function () {
  88223. return this._bloomKernel;
  88224. },
  88225. set: function (value) {
  88226. this._bloomKernel = value;
  88227. this.bloom.kernel = value / this._hardwareScaleLevel;
  88228. },
  88229. enumerable: true,
  88230. configurable: true
  88231. });
  88232. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  88233. get: function () {
  88234. return this._bloomWeight;
  88235. },
  88236. /**
  88237. * The strength of the bloom.
  88238. */
  88239. set: function (value) {
  88240. if (this._bloomWeight === value) {
  88241. return;
  88242. }
  88243. this.bloom.weight = value;
  88244. this._bloomWeight = value;
  88245. },
  88246. enumerable: true,
  88247. configurable: true
  88248. });
  88249. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  88250. get: function () {
  88251. return this._bloomThreshold;
  88252. },
  88253. /**
  88254. * The strength of the bloom.
  88255. */
  88256. set: function (value) {
  88257. if (this._bloomThreshold === value) {
  88258. return;
  88259. }
  88260. this.bloom.threshold = value;
  88261. this._bloomThreshold = value;
  88262. },
  88263. enumerable: true,
  88264. configurable: true
  88265. });
  88266. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  88267. get: function () {
  88268. return this._bloomScale;
  88269. },
  88270. /**
  88271. * The scale of the bloom, lower value will provide better performance.
  88272. */
  88273. set: function (value) {
  88274. if (this._bloomScale === value) {
  88275. return;
  88276. }
  88277. this._bloomScale = value;
  88278. // recreate bloom and dispose old as this setting is not dynamic
  88279. this._rebuildBloom();
  88280. this._buildPipeline();
  88281. },
  88282. enumerable: true,
  88283. configurable: true
  88284. });
  88285. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  88286. get: function () {
  88287. return this._bloomEnabled;
  88288. },
  88289. /**
  88290. * Enable or disable the bloom from the pipeline
  88291. */
  88292. set: function (enabled) {
  88293. if (this._bloomEnabled === enabled) {
  88294. return;
  88295. }
  88296. this._bloomEnabled = enabled;
  88297. this._buildPipeline();
  88298. },
  88299. enumerable: true,
  88300. configurable: true
  88301. });
  88302. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  88303. // recreate bloom and dispose old as this setting is not dynamic
  88304. var oldBloom = this.bloom;
  88305. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  88306. this.bloom.threshold = oldBloom.threshold;
  88307. for (var i = 0; i < this._cameras.length; i++) {
  88308. oldBloom.disposeEffects(this._cameras[i]);
  88309. }
  88310. };
  88311. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  88312. /**
  88313. * If the depth of field is enabled.
  88314. */
  88315. get: function () {
  88316. return this._depthOfFieldEnabled;
  88317. },
  88318. set: function (enabled) {
  88319. if (this._depthOfFieldEnabled === enabled) {
  88320. return;
  88321. }
  88322. this._depthOfFieldEnabled = enabled;
  88323. this._buildPipeline();
  88324. },
  88325. enumerable: true,
  88326. configurable: true
  88327. });
  88328. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  88329. /**
  88330. * Blur level of the depth of field effect. (Higher blur will effect performance)
  88331. */
  88332. get: function () {
  88333. return this._depthOfFieldBlurLevel;
  88334. },
  88335. set: function (value) {
  88336. if (this._depthOfFieldBlurLevel === value) {
  88337. return;
  88338. }
  88339. this._depthOfFieldBlurLevel = value;
  88340. // recreate dof and dispose old as this setting is not dynamic
  88341. var oldDof = this.depthOfField;
  88342. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  88343. this.depthOfField.focalLength = oldDof.focalLength;
  88344. this.depthOfField.focusDistance = oldDof.focusDistance;
  88345. this.depthOfField.fStop = oldDof.fStop;
  88346. this.depthOfField.lensSize = oldDof.lensSize;
  88347. for (var i = 0; i < this._cameras.length; i++) {
  88348. oldDof.disposeEffects(this._cameras[i]);
  88349. }
  88350. this._buildPipeline();
  88351. },
  88352. enumerable: true,
  88353. configurable: true
  88354. });
  88355. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  88356. get: function () {
  88357. return this._fxaaEnabled;
  88358. },
  88359. /**
  88360. * If the anti aliasing is enabled.
  88361. */
  88362. set: function (enabled) {
  88363. if (this._fxaaEnabled === enabled) {
  88364. return;
  88365. }
  88366. this._fxaaEnabled = enabled;
  88367. this._buildPipeline();
  88368. },
  88369. enumerable: true,
  88370. configurable: true
  88371. });
  88372. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  88373. get: function () {
  88374. return this._samples;
  88375. },
  88376. /**
  88377. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  88378. */
  88379. set: function (sampleCount) {
  88380. if (this._samples === sampleCount) {
  88381. return;
  88382. }
  88383. this._samples = sampleCount;
  88384. this._buildPipeline();
  88385. },
  88386. enumerable: true,
  88387. configurable: true
  88388. });
  88389. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  88390. get: function () {
  88391. return this._imageProcessingEnabled;
  88392. },
  88393. /**
  88394. * If image processing is enabled.
  88395. */
  88396. set: function (enabled) {
  88397. if (this._imageProcessingEnabled === enabled) {
  88398. return;
  88399. }
  88400. this._imageProcessingEnabled = enabled;
  88401. this._buildPipeline();
  88402. },
  88403. enumerable: true,
  88404. configurable: true
  88405. });
  88406. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  88407. get: function () {
  88408. return this._glowLayer == null;
  88409. },
  88410. /**
  88411. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  88412. */
  88413. set: function (enabled) {
  88414. if (enabled && !this._glowLayer) {
  88415. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  88416. }
  88417. else if (!enabled && this._glowLayer) {
  88418. this._glowLayer.dispose();
  88419. this._glowLayer = null;
  88420. }
  88421. },
  88422. enumerable: true,
  88423. configurable: true
  88424. });
  88425. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  88426. get: function () {
  88427. return this._chromaticAberrationEnabled;
  88428. },
  88429. /**
  88430. * Enable or disable the chromaticAberration process from the pipeline
  88431. */
  88432. set: function (enabled) {
  88433. if (this._chromaticAberrationEnabled === enabled) {
  88434. return;
  88435. }
  88436. this._chromaticAberrationEnabled = enabled;
  88437. this._buildPipeline();
  88438. },
  88439. enumerable: true,
  88440. configurable: true
  88441. });
  88442. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  88443. get: function () {
  88444. return this._grainEnabled;
  88445. },
  88446. /**
  88447. * Enable or disable the grain process from the pipeline
  88448. */
  88449. set: function (enabled) {
  88450. if (this._grainEnabled === enabled) {
  88451. return;
  88452. }
  88453. this._grainEnabled = enabled;
  88454. this._buildPipeline();
  88455. },
  88456. enumerable: true,
  88457. configurable: true
  88458. });
  88459. /**
  88460. * Force the compilation of the entire pipeline.
  88461. */
  88462. DefaultRenderingPipeline.prototype.prepare = function () {
  88463. var previousState = this._buildAllowed;
  88464. this._buildAllowed = true;
  88465. this._buildPipeline();
  88466. this._buildAllowed = previousState;
  88467. };
  88468. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  88469. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  88470. if (this._hasCleared) {
  88471. postProcess.autoClear = false;
  88472. }
  88473. else {
  88474. postProcess.autoClear = true;
  88475. this._scene.autoClear = false;
  88476. this._hasCleared = true;
  88477. }
  88478. if (!skipTextureSharing) {
  88479. if (this._prevPrevPostProcess) {
  88480. postProcess.shareOutputWith(this._prevPrevPostProcess);
  88481. }
  88482. else {
  88483. postProcess.useOwnOutput();
  88484. }
  88485. if (this._prevPostProcess) {
  88486. this._prevPrevPostProcess = this._prevPostProcess;
  88487. }
  88488. this._prevPostProcess = postProcess;
  88489. }
  88490. };
  88491. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  88492. var _this = this;
  88493. if (!this._buildAllowed) {
  88494. return;
  88495. }
  88496. this._scene.autoClear = true;
  88497. var engine = this._scene.getEngine();
  88498. this._disposePostProcesses();
  88499. if (this._cameras !== null) {
  88500. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88501. // get back cameras to be used to reattach pipeline
  88502. this._cameras = this._camerasToBeAttached.slice();
  88503. }
  88504. this._reset();
  88505. this._prevPostProcess = null;
  88506. this._prevPrevPostProcess = null;
  88507. this._hasCleared = false;
  88508. if (this.depthOfFieldEnabled) {
  88509. // Multi camera suport
  88510. if (this._cameras.length > 1) {
  88511. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  88512. var camera = _a[_i];
  88513. var depthRenderer = this._scene.enableDepthRenderer(camera);
  88514. depthRenderer.useOnlyInActiveCamera = true;
  88515. }
  88516. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  88517. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  88518. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  88519. }
  88520. });
  88521. }
  88522. else {
  88523. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88524. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  88525. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  88526. }
  88527. if (!this.depthOfField._isReady()) {
  88528. this.depthOfField._updateEffects();
  88529. }
  88530. this.addEffect(this.depthOfField);
  88531. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  88532. }
  88533. else {
  88534. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88535. }
  88536. if (this.bloomEnabled) {
  88537. if (!this.bloom._isReady()) {
  88538. this.bloom._updateEffects();
  88539. }
  88540. this.addEffect(this.bloom);
  88541. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  88542. }
  88543. if (this._imageProcessingEnabled) {
  88544. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88545. if (this._hdr) {
  88546. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  88547. this._setAutoClearAndTextureSharing(this.imageProcessing);
  88548. }
  88549. else {
  88550. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  88551. }
  88552. }
  88553. if (this.sharpenEnabled) {
  88554. if (!this.sharpen.isReady()) {
  88555. this.sharpen.updateEffect();
  88556. }
  88557. this.addEffect(this._sharpenEffect);
  88558. this._setAutoClearAndTextureSharing(this.sharpen);
  88559. }
  88560. if (this.grainEnabled) {
  88561. if (!this.grain.isReady()) {
  88562. this.grain.updateEffect();
  88563. }
  88564. this.addEffect(this._grainEffect);
  88565. this._setAutoClearAndTextureSharing(this.grain);
  88566. }
  88567. if (this.chromaticAberrationEnabled) {
  88568. if (!this.chromaticAberration.isReady()) {
  88569. this.chromaticAberration.updateEffect();
  88570. }
  88571. this.addEffect(this._chromaticAberrationEffect);
  88572. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  88573. }
  88574. if (this.fxaaEnabled) {
  88575. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88576. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  88577. this._setAutoClearAndTextureSharing(this.fxaa, true);
  88578. }
  88579. if (this._cameras !== null) {
  88580. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  88581. }
  88582. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  88583. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  88584. }
  88585. };
  88586. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  88587. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  88588. for (var i = 0; i < this._cameras.length; i++) {
  88589. var camera = this._cameras[i];
  88590. if (this.imageProcessing) {
  88591. this.imageProcessing.dispose(camera);
  88592. }
  88593. if (this.fxaa) {
  88594. this.fxaa.dispose(camera);
  88595. }
  88596. // These are created in the constructor and should not be disposed on every pipeline change
  88597. if (disposeNonRecreated) {
  88598. if (this.sharpen) {
  88599. this.sharpen.dispose(camera);
  88600. }
  88601. if (this.depthOfField) {
  88602. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88603. this.depthOfField.disposeEffects(camera);
  88604. }
  88605. if (this.bloom) {
  88606. this.bloom.disposeEffects(camera);
  88607. }
  88608. if (this.chromaticAberration) {
  88609. this.chromaticAberration.dispose(camera);
  88610. }
  88611. if (this.grain) {
  88612. this.grain.dispose(camera);
  88613. }
  88614. if (this._glowLayer) {
  88615. this._glowLayer.dispose();
  88616. }
  88617. }
  88618. }
  88619. this.imageProcessing = null;
  88620. this.fxaa = null;
  88621. if (disposeNonRecreated) {
  88622. this.sharpen = null;
  88623. this._sharpenEffect = null;
  88624. this.depthOfField = null;
  88625. this.bloom = null;
  88626. this.chromaticAberration = null;
  88627. this._chromaticAberrationEffect = null;
  88628. this.grain = null;
  88629. this._grainEffect = null;
  88630. this._glowLayer = null;
  88631. }
  88632. };
  88633. /**
  88634. * Adds a camera to the pipeline
  88635. * @param camera the camera to be added
  88636. */
  88637. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  88638. this._camerasToBeAttached.push(camera);
  88639. this._buildPipeline();
  88640. };
  88641. /**
  88642. * Removes a camera from the pipeline
  88643. * @param camera the camera to remove
  88644. */
  88645. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  88646. var index = this._camerasToBeAttached.indexOf(camera);
  88647. this._camerasToBeAttached.splice(index, 1);
  88648. this._buildPipeline();
  88649. };
  88650. /**
  88651. * Dispose of the pipeline and stop all post processes
  88652. */
  88653. DefaultRenderingPipeline.prototype.dispose = function () {
  88654. this._disposePostProcesses(true);
  88655. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88656. this._scene.autoClear = true;
  88657. if (this._resizeObserver) {
  88658. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  88659. this._resizeObserver = null;
  88660. }
  88661. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  88662. _super.prototype.dispose.call(this);
  88663. };
  88664. /**
  88665. * Serialize the rendering pipeline (Used when exporting)
  88666. * @returns the serialized object
  88667. */
  88668. DefaultRenderingPipeline.prototype.serialize = function () {
  88669. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88670. serializationObject.customType = "DefaultRenderingPipeline";
  88671. return serializationObject;
  88672. };
  88673. /**
  88674. * Parse the serialized pipeline
  88675. * @param source Source pipeline.
  88676. * @param scene The scene to load the pipeline to.
  88677. * @param rootUrl The URL of the serialized pipeline.
  88678. * @returns An instantiated pipeline from the serialized object.
  88679. */
  88680. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  88681. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  88682. };
  88683. __decorate([
  88684. BABYLON.serialize()
  88685. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  88686. __decorate([
  88687. BABYLON.serialize()
  88688. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  88689. __decorate([
  88690. BABYLON.serialize()
  88691. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  88692. __decorate([
  88693. BABYLON.serialize()
  88694. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  88695. __decorate([
  88696. BABYLON.serialize()
  88697. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  88698. __decorate([
  88699. BABYLON.serialize()
  88700. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  88701. __decorate([
  88702. BABYLON.serialize()
  88703. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  88704. __decorate([
  88705. BABYLON.serialize()
  88706. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  88707. __decorate([
  88708. BABYLON.serialize()
  88709. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  88710. __decorate([
  88711. BABYLON.serialize()
  88712. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  88713. __decorate([
  88714. BABYLON.serialize()
  88715. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  88716. __decorate([
  88717. BABYLON.serialize()
  88718. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  88719. __decorate([
  88720. BABYLON.serialize()
  88721. ], DefaultRenderingPipeline.prototype, "samples", null);
  88722. __decorate([
  88723. BABYLON.serialize()
  88724. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  88725. __decorate([
  88726. BABYLON.serialize()
  88727. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  88728. __decorate([
  88729. BABYLON.serialize()
  88730. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  88731. __decorate([
  88732. BABYLON.serialize()
  88733. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  88734. return DefaultRenderingPipeline;
  88735. }(BABYLON.PostProcessRenderPipeline));
  88736. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  88737. })(BABYLON || (BABYLON = {}));
  88738. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  88739. var BABYLON;
  88740. (function (BABYLON) {
  88741. /**
  88742. * @hidden
  88743. */
  88744. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  88745. __extends(ImageProcessingConfigurationDefines, _super);
  88746. function ImageProcessingConfigurationDefines() {
  88747. var _this = _super.call(this) || this;
  88748. _this.IMAGEPROCESSING = false;
  88749. _this.VIGNETTE = false;
  88750. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88751. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88752. _this.TONEMAPPING = false;
  88753. _this.TONEMAPPING_ACES = false;
  88754. _this.CONTRAST = false;
  88755. _this.COLORCURVES = false;
  88756. _this.COLORGRADING = false;
  88757. _this.COLORGRADING3D = false;
  88758. _this.SAMPLER3DGREENDEPTH = false;
  88759. _this.SAMPLER3DBGRMAP = false;
  88760. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88761. _this.EXPOSURE = false;
  88762. _this.rebuild();
  88763. return _this;
  88764. }
  88765. return ImageProcessingConfigurationDefines;
  88766. }(BABYLON.MaterialDefines));
  88767. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  88768. /**
  88769. * This groups together the common properties used for image processing either in direct forward pass
  88770. * or through post processing effect depending on the use of the image processing pipeline in your scene
  88771. * or not.
  88772. */
  88773. var ImageProcessingConfiguration = /** @class */ (function () {
  88774. function ImageProcessingConfiguration() {
  88775. /**
  88776. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  88777. */
  88778. this.colorCurves = new BABYLON.ColorCurves();
  88779. this._colorCurvesEnabled = false;
  88780. this._colorGradingEnabled = false;
  88781. this._colorGradingWithGreenDepth = true;
  88782. this._colorGradingBGR = true;
  88783. /** @hidden */
  88784. this._exposure = 1.0;
  88785. this._toneMappingEnabled = false;
  88786. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  88787. this._contrast = 1.0;
  88788. /**
  88789. * Vignette stretch size.
  88790. */
  88791. this.vignetteStretch = 0;
  88792. /**
  88793. * Vignette centre X Offset.
  88794. */
  88795. this.vignetteCentreX = 0;
  88796. /**
  88797. * Vignette centre Y Offset.
  88798. */
  88799. this.vignetteCentreY = 0;
  88800. /**
  88801. * Vignette weight or intensity of the vignette effect.
  88802. */
  88803. this.vignetteWeight = 1.5;
  88804. /**
  88805. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88806. * if vignetteEnabled is set to true.
  88807. */
  88808. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88809. /**
  88810. * Camera field of view used by the Vignette effect.
  88811. */
  88812. this.vignetteCameraFov = 0.5;
  88813. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  88814. this._vignetteEnabled = false;
  88815. this._applyByPostProcess = false;
  88816. this._isEnabled = true;
  88817. /**
  88818. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  88819. */
  88820. this.onUpdateParameters = new BABYLON.Observable();
  88821. }
  88822. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  88823. /**
  88824. * Gets wether the color curves effect is enabled.
  88825. */
  88826. get: function () {
  88827. return this._colorCurvesEnabled;
  88828. },
  88829. /**
  88830. * Sets wether the color curves effect is enabled.
  88831. */
  88832. set: function (value) {
  88833. if (this._colorCurvesEnabled === value) {
  88834. return;
  88835. }
  88836. this._colorCurvesEnabled = value;
  88837. this._updateParameters();
  88838. },
  88839. enumerable: true,
  88840. configurable: true
  88841. });
  88842. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  88843. /**
  88844. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88845. */
  88846. get: function () {
  88847. return this._colorGradingTexture;
  88848. },
  88849. /**
  88850. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88851. */
  88852. set: function (value) {
  88853. if (this._colorGradingTexture === value) {
  88854. return;
  88855. }
  88856. this._colorGradingTexture = value;
  88857. this._updateParameters();
  88858. },
  88859. enumerable: true,
  88860. configurable: true
  88861. });
  88862. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  88863. /**
  88864. * Gets wether the color grading effect is enabled.
  88865. */
  88866. get: function () {
  88867. return this._colorGradingEnabled;
  88868. },
  88869. /**
  88870. * Sets wether the color grading effect is enabled.
  88871. */
  88872. set: function (value) {
  88873. if (this._colorGradingEnabled === value) {
  88874. return;
  88875. }
  88876. this._colorGradingEnabled = value;
  88877. this._updateParameters();
  88878. },
  88879. enumerable: true,
  88880. configurable: true
  88881. });
  88882. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  88883. /**
  88884. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  88885. */
  88886. get: function () {
  88887. return this._colorGradingWithGreenDepth;
  88888. },
  88889. /**
  88890. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  88891. */
  88892. set: function (value) {
  88893. if (this._colorGradingWithGreenDepth === value) {
  88894. return;
  88895. }
  88896. this._colorGradingWithGreenDepth = value;
  88897. this._updateParameters();
  88898. },
  88899. enumerable: true,
  88900. configurable: true
  88901. });
  88902. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  88903. /**
  88904. * Gets wether the color grading texture contains BGR values.
  88905. */
  88906. get: function () {
  88907. return this._colorGradingBGR;
  88908. },
  88909. /**
  88910. * Sets wether the color grading texture contains BGR values.
  88911. */
  88912. set: function (value) {
  88913. if (this._colorGradingBGR === value) {
  88914. return;
  88915. }
  88916. this._colorGradingBGR = value;
  88917. this._updateParameters();
  88918. },
  88919. enumerable: true,
  88920. configurable: true
  88921. });
  88922. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  88923. /**
  88924. * Gets the Exposure used in the effect.
  88925. */
  88926. get: function () {
  88927. return this._exposure;
  88928. },
  88929. /**
  88930. * Sets the Exposure used in the effect.
  88931. */
  88932. set: function (value) {
  88933. if (this._exposure === value) {
  88934. return;
  88935. }
  88936. this._exposure = value;
  88937. this._updateParameters();
  88938. },
  88939. enumerable: true,
  88940. configurable: true
  88941. });
  88942. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  88943. /**
  88944. * Gets wether the tone mapping effect is enabled.
  88945. */
  88946. get: function () {
  88947. return this._toneMappingEnabled;
  88948. },
  88949. /**
  88950. * Sets wether the tone mapping effect is enabled.
  88951. */
  88952. set: function (value) {
  88953. if (this._toneMappingEnabled === value) {
  88954. return;
  88955. }
  88956. this._toneMappingEnabled = value;
  88957. this._updateParameters();
  88958. },
  88959. enumerable: true,
  88960. configurable: true
  88961. });
  88962. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  88963. /**
  88964. * Gets the type of tone mapping effect.
  88965. */
  88966. get: function () {
  88967. return this._toneMappingType;
  88968. },
  88969. /**
  88970. * Sets the type of tone mapping effect used in BabylonJS.
  88971. */
  88972. set: function (value) {
  88973. if (this._toneMappingType === value) {
  88974. return;
  88975. }
  88976. this._toneMappingType = value;
  88977. this._updateParameters();
  88978. },
  88979. enumerable: true,
  88980. configurable: true
  88981. });
  88982. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  88983. /**
  88984. * Gets the contrast used in the effect.
  88985. */
  88986. get: function () {
  88987. return this._contrast;
  88988. },
  88989. /**
  88990. * Sets the contrast used in the effect.
  88991. */
  88992. set: function (value) {
  88993. if (this._contrast === value) {
  88994. return;
  88995. }
  88996. this._contrast = value;
  88997. this._updateParameters();
  88998. },
  88999. enumerable: true,
  89000. configurable: true
  89001. });
  89002. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  89003. /**
  89004. * Gets the vignette blend mode allowing different kind of effect.
  89005. */
  89006. get: function () {
  89007. return this._vignetteBlendMode;
  89008. },
  89009. /**
  89010. * Sets the vignette blend mode allowing different kind of effect.
  89011. */
  89012. set: function (value) {
  89013. if (this._vignetteBlendMode === value) {
  89014. return;
  89015. }
  89016. this._vignetteBlendMode = value;
  89017. this._updateParameters();
  89018. },
  89019. enumerable: true,
  89020. configurable: true
  89021. });
  89022. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  89023. /**
  89024. * Gets wether the vignette effect is enabled.
  89025. */
  89026. get: function () {
  89027. return this._vignetteEnabled;
  89028. },
  89029. /**
  89030. * Sets wether the vignette effect is enabled.
  89031. */
  89032. set: function (value) {
  89033. if (this._vignetteEnabled === value) {
  89034. return;
  89035. }
  89036. this._vignetteEnabled = value;
  89037. this._updateParameters();
  89038. },
  89039. enumerable: true,
  89040. configurable: true
  89041. });
  89042. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  89043. /**
  89044. * Gets wether the image processing is applied through a post process or not.
  89045. */
  89046. get: function () {
  89047. return this._applyByPostProcess;
  89048. },
  89049. /**
  89050. * Sets wether the image processing is applied through a post process or not.
  89051. */
  89052. set: function (value) {
  89053. if (this._applyByPostProcess === value) {
  89054. return;
  89055. }
  89056. this._applyByPostProcess = value;
  89057. this._updateParameters();
  89058. },
  89059. enumerable: true,
  89060. configurable: true
  89061. });
  89062. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  89063. /**
  89064. * Gets wether the image processing is enabled or not.
  89065. */
  89066. get: function () {
  89067. return this._isEnabled;
  89068. },
  89069. /**
  89070. * Sets wether the image processing is enabled or not.
  89071. */
  89072. set: function (value) {
  89073. if (this._isEnabled === value) {
  89074. return;
  89075. }
  89076. this._isEnabled = value;
  89077. this._updateParameters();
  89078. },
  89079. enumerable: true,
  89080. configurable: true
  89081. });
  89082. /**
  89083. * Method called each time the image processing information changes requires to recompile the effect.
  89084. */
  89085. ImageProcessingConfiguration.prototype._updateParameters = function () {
  89086. this.onUpdateParameters.notifyObservers(this);
  89087. };
  89088. /**
  89089. * Gets the current class name.
  89090. * @return "ImageProcessingConfiguration"
  89091. */
  89092. ImageProcessingConfiguration.prototype.getClassName = function () {
  89093. return "ImageProcessingConfiguration";
  89094. };
  89095. /**
  89096. * Prepare the list of uniforms associated with the Image Processing effects.
  89097. * @param uniforms The list of uniforms used in the effect
  89098. * @param defines the list of defines currently in use
  89099. */
  89100. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  89101. if (defines.EXPOSURE) {
  89102. uniforms.push("exposureLinear");
  89103. }
  89104. if (defines.CONTRAST) {
  89105. uniforms.push("contrast");
  89106. }
  89107. if (defines.COLORGRADING) {
  89108. uniforms.push("colorTransformSettings");
  89109. }
  89110. if (defines.VIGNETTE) {
  89111. uniforms.push("vInverseScreenSize");
  89112. uniforms.push("vignetteSettings1");
  89113. uniforms.push("vignetteSettings2");
  89114. }
  89115. if (defines.COLORCURVES) {
  89116. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  89117. }
  89118. };
  89119. /**
  89120. * Prepare the list of samplers associated with the Image Processing effects.
  89121. * @param samplersList The list of uniforms used in the effect
  89122. * @param defines the list of defines currently in use
  89123. */
  89124. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  89125. if (defines.COLORGRADING) {
  89126. samplersList.push("txColorTransform");
  89127. }
  89128. };
  89129. /**
  89130. * Prepare the list of defines associated to the shader.
  89131. * @param defines the list of defines to complete
  89132. * @param forPostProcess Define if we are currently in post process mode or not
  89133. */
  89134. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  89135. if (forPostProcess === void 0) { forPostProcess = false; }
  89136. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  89137. defines.VIGNETTE = false;
  89138. defines.TONEMAPPING = false;
  89139. defines.TONEMAPPING_ACES = false;
  89140. defines.CONTRAST = false;
  89141. defines.EXPOSURE = false;
  89142. defines.COLORCURVES = false;
  89143. defines.COLORGRADING = false;
  89144. defines.COLORGRADING3D = false;
  89145. defines.IMAGEPROCESSING = false;
  89146. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  89147. return;
  89148. }
  89149. defines.VIGNETTE = this.vignetteEnabled;
  89150. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  89151. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  89152. defines.TONEMAPPING = this.toneMappingEnabled;
  89153. switch (this._toneMappingType) {
  89154. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  89155. defines.TONEMAPPING_ACES = true;
  89156. break;
  89157. }
  89158. defines.CONTRAST = (this.contrast !== 1.0);
  89159. defines.EXPOSURE = (this.exposure !== 1.0);
  89160. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  89161. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  89162. if (defines.COLORGRADING) {
  89163. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  89164. }
  89165. else {
  89166. defines.COLORGRADING3D = false;
  89167. }
  89168. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  89169. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  89170. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  89171. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  89172. };
  89173. /**
  89174. * Returns true if all the image processing information are ready.
  89175. * @returns True if ready, otherwise, false
  89176. */
  89177. ImageProcessingConfiguration.prototype.isReady = function () {
  89178. // Color Grading texure can not be none blocking.
  89179. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  89180. };
  89181. /**
  89182. * Binds the image processing to the shader.
  89183. * @param effect The effect to bind to
  89184. * @param aspectRatio Define the current aspect ratio of the effect
  89185. */
  89186. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  89187. if (aspectRatio === void 0) { aspectRatio = 1; }
  89188. // Color Curves
  89189. if (this._colorCurvesEnabled && this.colorCurves) {
  89190. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  89191. }
  89192. // Vignette
  89193. if (this._vignetteEnabled) {
  89194. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  89195. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  89196. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  89197. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  89198. var vignetteScaleX = vignetteScaleY * aspectRatio;
  89199. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  89200. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  89201. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  89202. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  89203. var vignettePower = -2.0 * this.vignetteWeight;
  89204. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  89205. }
  89206. // Exposure
  89207. effect.setFloat("exposureLinear", this.exposure);
  89208. // Contrast
  89209. effect.setFloat("contrast", this.contrast);
  89210. // Color transform settings
  89211. if (this.colorGradingTexture) {
  89212. effect.setTexture("txColorTransform", this.colorGradingTexture);
  89213. var textureSize = this.colorGradingTexture.getSize().height;
  89214. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  89215. 0.5 / textureSize, // textureOffset
  89216. textureSize, // textureSize
  89217. this.colorGradingTexture.level // weight
  89218. );
  89219. }
  89220. };
  89221. /**
  89222. * Clones the current image processing instance.
  89223. * @return The cloned image processing
  89224. */
  89225. ImageProcessingConfiguration.prototype.clone = function () {
  89226. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  89227. };
  89228. /**
  89229. * Serializes the current image processing instance to a json representation.
  89230. * @return a JSON representation
  89231. */
  89232. ImageProcessingConfiguration.prototype.serialize = function () {
  89233. return BABYLON.SerializationHelper.Serialize(this);
  89234. };
  89235. /**
  89236. * Parses the image processing from a json representation.
  89237. * @param source the JSON source to parse
  89238. * @return The parsed image processing
  89239. */
  89240. ImageProcessingConfiguration.Parse = function (source) {
  89241. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  89242. };
  89243. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  89244. /**
  89245. * Used to apply the vignette as a mix with the pixel color.
  89246. */
  89247. get: function () {
  89248. return this._VIGNETTEMODE_MULTIPLY;
  89249. },
  89250. enumerable: true,
  89251. configurable: true
  89252. });
  89253. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  89254. /**
  89255. * Used to apply the vignette as a replacement of the pixel color.
  89256. */
  89257. get: function () {
  89258. return this._VIGNETTEMODE_OPAQUE;
  89259. },
  89260. enumerable: true,
  89261. configurable: true
  89262. });
  89263. /**
  89264. * Default tone mapping applied in BabylonJS.
  89265. */
  89266. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  89267. /**
  89268. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  89269. * to other engines rendering to increase portability.
  89270. */
  89271. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  89272. // Static constants associated to the image processing.
  89273. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  89274. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  89275. __decorate([
  89276. BABYLON.serializeAsColorCurves()
  89277. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  89278. __decorate([
  89279. BABYLON.serialize()
  89280. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  89281. __decorate([
  89282. BABYLON.serializeAsTexture("colorGradingTexture")
  89283. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  89284. __decorate([
  89285. BABYLON.serialize()
  89286. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  89287. __decorate([
  89288. BABYLON.serialize()
  89289. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  89290. __decorate([
  89291. BABYLON.serialize()
  89292. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  89293. __decorate([
  89294. BABYLON.serialize()
  89295. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  89296. __decorate([
  89297. BABYLON.serialize()
  89298. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  89299. __decorate([
  89300. BABYLON.serialize()
  89301. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  89302. __decorate([
  89303. BABYLON.serialize()
  89304. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  89305. __decorate([
  89306. BABYLON.serialize()
  89307. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  89308. __decorate([
  89309. BABYLON.serialize()
  89310. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  89311. __decorate([
  89312. BABYLON.serialize()
  89313. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  89314. __decorate([
  89315. BABYLON.serialize()
  89316. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  89317. __decorate([
  89318. BABYLON.serializeAsColor4()
  89319. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  89320. __decorate([
  89321. BABYLON.serialize()
  89322. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  89323. __decorate([
  89324. BABYLON.serialize()
  89325. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  89326. __decorate([
  89327. BABYLON.serialize()
  89328. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  89329. __decorate([
  89330. BABYLON.serialize()
  89331. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  89332. __decorate([
  89333. BABYLON.serialize()
  89334. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  89335. return ImageProcessingConfiguration;
  89336. }());
  89337. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  89338. })(BABYLON || (BABYLON = {}));
  89339. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  89340. var BABYLON;
  89341. (function (BABYLON) {
  89342. /**
  89343. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  89344. * It can help converting any input color in a desired output one. This can then be used to create effects
  89345. * from sepia, black and white to sixties or futuristic rendering...
  89346. *
  89347. * The only supported format is currently 3dl.
  89348. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  89349. */
  89350. var ColorGradingTexture = /** @class */ (function (_super) {
  89351. __extends(ColorGradingTexture, _super);
  89352. /**
  89353. * Instantiates a ColorGradingTexture from the following parameters.
  89354. *
  89355. * @param url The location of the color gradind data (currently only supporting 3dl)
  89356. * @param scene The scene the texture will be used in
  89357. */
  89358. function ColorGradingTexture(url, scene) {
  89359. var _this = _super.call(this, scene) || this;
  89360. if (!url) {
  89361. return _this;
  89362. }
  89363. _this._engine = scene.getEngine();
  89364. _this._textureMatrix = BABYLON.Matrix.Identity();
  89365. _this.name = url;
  89366. _this.url = url;
  89367. _this.hasAlpha = false;
  89368. _this.isCube = false;
  89369. _this.is3D = _this._engine.webGLVersion > 1;
  89370. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89371. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89372. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89373. _this.anisotropicFilteringLevel = 1;
  89374. _this._texture = _this._getFromCache(url, true);
  89375. if (!_this._texture) {
  89376. if (!scene.useDelayedTextureLoading) {
  89377. _this.loadTexture();
  89378. }
  89379. else {
  89380. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89381. }
  89382. }
  89383. return _this;
  89384. }
  89385. /**
  89386. * Returns the texture matrix used in most of the material.
  89387. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  89388. */
  89389. ColorGradingTexture.prototype.getTextureMatrix = function () {
  89390. return this._textureMatrix;
  89391. };
  89392. /**
  89393. * Occurs when the file being loaded is a .3dl LUT file.
  89394. */
  89395. ColorGradingTexture.prototype.load3dlTexture = function () {
  89396. var engine = this._engine;
  89397. var texture;
  89398. if (engine.webGLVersion === 1) {
  89399. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89400. }
  89401. else {
  89402. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89403. }
  89404. this._texture = texture;
  89405. var callback = function (text) {
  89406. if (typeof text !== "string") {
  89407. return;
  89408. }
  89409. var data = null;
  89410. var tempData = null;
  89411. var line;
  89412. var lines = text.split('\n');
  89413. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  89414. var maxColor = 0;
  89415. for (var i = 0; i < lines.length; i++) {
  89416. line = lines[i];
  89417. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  89418. continue;
  89419. }
  89420. if (line.indexOf('#') === 0) {
  89421. continue;
  89422. }
  89423. var words = line.split(" ");
  89424. if (size === 0) {
  89425. // Number of space + one
  89426. size = words.length;
  89427. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  89428. tempData = new Float32Array(size * size * size * 4);
  89429. continue;
  89430. }
  89431. if (size != 0) {
  89432. var r = Math.max(parseInt(words[0]), 0);
  89433. var g = Math.max(parseInt(words[1]), 0);
  89434. var b = Math.max(parseInt(words[2]), 0);
  89435. maxColor = Math.max(r, maxColor);
  89436. maxColor = Math.max(g, maxColor);
  89437. maxColor = Math.max(b, maxColor);
  89438. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  89439. if (tempData) {
  89440. tempData[pixelStorageIndex + 0] = r;
  89441. tempData[pixelStorageIndex + 1] = g;
  89442. tempData[pixelStorageIndex + 2] = b;
  89443. }
  89444. // Keep for reference in case of back compat problems.
  89445. // pixelIndexSlice++;
  89446. // if (pixelIndexSlice % size == 0) {
  89447. // pixelIndexH++;
  89448. // pixelIndexSlice = 0;
  89449. // if (pixelIndexH % size == 0) {
  89450. // pixelIndexW++;
  89451. // pixelIndexH = 0;
  89452. // }
  89453. // }
  89454. pixelIndexH++;
  89455. if (pixelIndexH % size == 0) {
  89456. pixelIndexSlice++;
  89457. pixelIndexH = 0;
  89458. if (pixelIndexSlice % size == 0) {
  89459. pixelIndexW++;
  89460. pixelIndexSlice = 0;
  89461. }
  89462. }
  89463. }
  89464. }
  89465. if (tempData && data) {
  89466. for (var i = 0; i < tempData.length; i++) {
  89467. if (i > 0 && (i + 1) % 4 === 0) {
  89468. data[i] = 255;
  89469. }
  89470. else {
  89471. var value = tempData[i];
  89472. data[i] = (value / maxColor * 255);
  89473. }
  89474. }
  89475. }
  89476. if (texture.is3D) {
  89477. texture.updateSize(size, size, size);
  89478. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89479. }
  89480. else {
  89481. texture.updateSize(size * size, size);
  89482. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89483. }
  89484. };
  89485. var scene = this.getScene();
  89486. if (scene) {
  89487. scene._loadFile(this.url, callback);
  89488. }
  89489. else {
  89490. this._engine._loadFile(this.url, callback);
  89491. }
  89492. return this._texture;
  89493. };
  89494. /**
  89495. * Starts the loading process of the texture.
  89496. */
  89497. ColorGradingTexture.prototype.loadTexture = function () {
  89498. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  89499. this.load3dlTexture();
  89500. }
  89501. };
  89502. /**
  89503. * Clones the color gradind texture.
  89504. */
  89505. ColorGradingTexture.prototype.clone = function () {
  89506. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  89507. // Base texture
  89508. newTexture.level = this.level;
  89509. return newTexture;
  89510. };
  89511. /**
  89512. * Called during delayed load for textures.
  89513. */
  89514. ColorGradingTexture.prototype.delayLoad = function () {
  89515. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89516. return;
  89517. }
  89518. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89519. this._texture = this._getFromCache(this.url, true);
  89520. if (!this._texture) {
  89521. this.loadTexture();
  89522. }
  89523. };
  89524. /**
  89525. * Parses a color grading texture serialized by Babylon.
  89526. * @param parsedTexture The texture information being parsedTexture
  89527. * @param scene The scene to load the texture in
  89528. * @param rootUrl The root url of the data assets to load
  89529. * @return A color gradind texture
  89530. */
  89531. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89532. var texture = null;
  89533. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89534. texture = new ColorGradingTexture(parsedTexture.name, scene);
  89535. texture.name = parsedTexture.name;
  89536. texture.level = parsedTexture.level;
  89537. }
  89538. return texture;
  89539. };
  89540. /**
  89541. * Serializes the LUT texture to json format.
  89542. */
  89543. ColorGradingTexture.prototype.serialize = function () {
  89544. if (!this.name) {
  89545. return null;
  89546. }
  89547. var serializationObject = {};
  89548. serializationObject.name = this.name;
  89549. serializationObject.level = this.level;
  89550. serializationObject.customType = "BABYLON.ColorGradingTexture";
  89551. return serializationObject;
  89552. };
  89553. /**
  89554. * Empty line regex stored for GC.
  89555. */
  89556. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  89557. return ColorGradingTexture;
  89558. }(BABYLON.BaseTexture));
  89559. BABYLON.ColorGradingTexture = ColorGradingTexture;
  89560. })(BABYLON || (BABYLON = {}));
  89561. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  89562. var BABYLON;
  89563. (function (BABYLON) {
  89564. /**
  89565. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89566. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89567. * 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;
  89568. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89569. */
  89570. var ColorCurves = /** @class */ (function () {
  89571. function ColorCurves() {
  89572. this._dirty = true;
  89573. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  89574. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  89575. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89576. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  89577. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89578. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  89579. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  89580. this._globalHue = 30;
  89581. this._globalDensity = 0;
  89582. this._globalSaturation = 0;
  89583. this._globalExposure = 0;
  89584. this._highlightsHue = 30;
  89585. this._highlightsDensity = 0;
  89586. this._highlightsSaturation = 0;
  89587. this._highlightsExposure = 0;
  89588. this._midtonesHue = 30;
  89589. this._midtonesDensity = 0;
  89590. this._midtonesSaturation = 0;
  89591. this._midtonesExposure = 0;
  89592. this._shadowsHue = 30;
  89593. this._shadowsDensity = 0;
  89594. this._shadowsSaturation = 0;
  89595. this._shadowsExposure = 0;
  89596. }
  89597. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  89598. /**
  89599. * Gets the global Hue value.
  89600. * 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).
  89601. */
  89602. get: function () {
  89603. return this._globalHue;
  89604. },
  89605. /**
  89606. * Sets the global Hue value.
  89607. * 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).
  89608. */
  89609. set: function (value) {
  89610. this._globalHue = value;
  89611. this._dirty = true;
  89612. },
  89613. enumerable: true,
  89614. configurable: true
  89615. });
  89616. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  89617. /**
  89618. * Gets the global Density value.
  89619. * 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.
  89620. * Values less than zero provide a filter of opposite hue.
  89621. */
  89622. get: function () {
  89623. return this._globalDensity;
  89624. },
  89625. /**
  89626. * Sets the global Density value.
  89627. * 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.
  89628. * Values less than zero provide a filter of opposite hue.
  89629. */
  89630. set: function (value) {
  89631. this._globalDensity = value;
  89632. this._dirty = true;
  89633. },
  89634. enumerable: true,
  89635. configurable: true
  89636. });
  89637. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  89638. /**
  89639. * Gets the global Saturation value.
  89640. * 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.
  89641. */
  89642. get: function () {
  89643. return this._globalSaturation;
  89644. },
  89645. /**
  89646. * Sets the global Saturation value.
  89647. * 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.
  89648. */
  89649. set: function (value) {
  89650. this._globalSaturation = value;
  89651. this._dirty = true;
  89652. },
  89653. enumerable: true,
  89654. configurable: true
  89655. });
  89656. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  89657. /**
  89658. * Gets the global Exposure value.
  89659. * 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.
  89660. */
  89661. get: function () {
  89662. return this._globalExposure;
  89663. },
  89664. /**
  89665. * Sets the global Exposure value.
  89666. * 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.
  89667. */
  89668. set: function (value) {
  89669. this._globalExposure = value;
  89670. this._dirty = true;
  89671. },
  89672. enumerable: true,
  89673. configurable: true
  89674. });
  89675. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  89676. /**
  89677. * Gets the highlights Hue value.
  89678. * 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).
  89679. */
  89680. get: function () {
  89681. return this._highlightsHue;
  89682. },
  89683. /**
  89684. * Sets the highlights Hue value.
  89685. * 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).
  89686. */
  89687. set: function (value) {
  89688. this._highlightsHue = value;
  89689. this._dirty = true;
  89690. },
  89691. enumerable: true,
  89692. configurable: true
  89693. });
  89694. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  89695. /**
  89696. * Gets the highlights Density value.
  89697. * 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.
  89698. * Values less than zero provide a filter of opposite hue.
  89699. */
  89700. get: function () {
  89701. return this._highlightsDensity;
  89702. },
  89703. /**
  89704. * Sets the highlights Density value.
  89705. * 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.
  89706. * Values less than zero provide a filter of opposite hue.
  89707. */
  89708. set: function (value) {
  89709. this._highlightsDensity = value;
  89710. this._dirty = true;
  89711. },
  89712. enumerable: true,
  89713. configurable: true
  89714. });
  89715. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  89716. /**
  89717. * Gets the highlights Saturation value.
  89718. * 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.
  89719. */
  89720. get: function () {
  89721. return this._highlightsSaturation;
  89722. },
  89723. /**
  89724. * Sets the highlights Saturation value.
  89725. * 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.
  89726. */
  89727. set: function (value) {
  89728. this._highlightsSaturation = value;
  89729. this._dirty = true;
  89730. },
  89731. enumerable: true,
  89732. configurable: true
  89733. });
  89734. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  89735. /**
  89736. * Gets the highlights Exposure value.
  89737. * 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.
  89738. */
  89739. get: function () {
  89740. return this._highlightsExposure;
  89741. },
  89742. /**
  89743. * Sets the highlights Exposure value.
  89744. * 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.
  89745. */
  89746. set: function (value) {
  89747. this._highlightsExposure = value;
  89748. this._dirty = true;
  89749. },
  89750. enumerable: true,
  89751. configurable: true
  89752. });
  89753. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  89754. /**
  89755. * Gets the midtones Hue value.
  89756. * 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).
  89757. */
  89758. get: function () {
  89759. return this._midtonesHue;
  89760. },
  89761. /**
  89762. * Sets the midtones Hue value.
  89763. * 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).
  89764. */
  89765. set: function (value) {
  89766. this._midtonesHue = value;
  89767. this._dirty = true;
  89768. },
  89769. enumerable: true,
  89770. configurable: true
  89771. });
  89772. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  89773. /**
  89774. * Gets the midtones Density value.
  89775. * 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.
  89776. * Values less than zero provide a filter of opposite hue.
  89777. */
  89778. get: function () {
  89779. return this._midtonesDensity;
  89780. },
  89781. /**
  89782. * Sets the midtones Density value.
  89783. * 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.
  89784. * Values less than zero provide a filter of opposite hue.
  89785. */
  89786. set: function (value) {
  89787. this._midtonesDensity = value;
  89788. this._dirty = true;
  89789. },
  89790. enumerable: true,
  89791. configurable: true
  89792. });
  89793. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  89794. /**
  89795. * Gets the midtones Saturation value.
  89796. * 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.
  89797. */
  89798. get: function () {
  89799. return this._midtonesSaturation;
  89800. },
  89801. /**
  89802. * Sets the midtones Saturation value.
  89803. * 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.
  89804. */
  89805. set: function (value) {
  89806. this._midtonesSaturation = value;
  89807. this._dirty = true;
  89808. },
  89809. enumerable: true,
  89810. configurable: true
  89811. });
  89812. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  89813. /**
  89814. * Gets the midtones Exposure value.
  89815. * 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.
  89816. */
  89817. get: function () {
  89818. return this._midtonesExposure;
  89819. },
  89820. /**
  89821. * Sets the midtones Exposure value.
  89822. * 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.
  89823. */
  89824. set: function (value) {
  89825. this._midtonesExposure = value;
  89826. this._dirty = true;
  89827. },
  89828. enumerable: true,
  89829. configurable: true
  89830. });
  89831. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  89832. /**
  89833. * Gets the shadows Hue value.
  89834. * 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).
  89835. */
  89836. get: function () {
  89837. return this._shadowsHue;
  89838. },
  89839. /**
  89840. * Sets the shadows Hue value.
  89841. * 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).
  89842. */
  89843. set: function (value) {
  89844. this._shadowsHue = value;
  89845. this._dirty = true;
  89846. },
  89847. enumerable: true,
  89848. configurable: true
  89849. });
  89850. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  89851. /**
  89852. * Gets the shadows Density value.
  89853. * 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.
  89854. * Values less than zero provide a filter of opposite hue.
  89855. */
  89856. get: function () {
  89857. return this._shadowsDensity;
  89858. },
  89859. /**
  89860. * Sets the shadows Density value.
  89861. * 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.
  89862. * Values less than zero provide a filter of opposite hue.
  89863. */
  89864. set: function (value) {
  89865. this._shadowsDensity = value;
  89866. this._dirty = true;
  89867. },
  89868. enumerable: true,
  89869. configurable: true
  89870. });
  89871. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  89872. /**
  89873. * Gets the shadows Saturation value.
  89874. * 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.
  89875. */
  89876. get: function () {
  89877. return this._shadowsSaturation;
  89878. },
  89879. /**
  89880. * Sets the shadows Saturation value.
  89881. * 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.
  89882. */
  89883. set: function (value) {
  89884. this._shadowsSaturation = value;
  89885. this._dirty = true;
  89886. },
  89887. enumerable: true,
  89888. configurable: true
  89889. });
  89890. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  89891. /**
  89892. * Gets the shadows Exposure value.
  89893. * 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.
  89894. */
  89895. get: function () {
  89896. return this._shadowsExposure;
  89897. },
  89898. /**
  89899. * Sets the shadows Exposure value.
  89900. * 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.
  89901. */
  89902. set: function (value) {
  89903. this._shadowsExposure = value;
  89904. this._dirty = true;
  89905. },
  89906. enumerable: true,
  89907. configurable: true
  89908. });
  89909. /**
  89910. * Returns the class name
  89911. * @returns The class name
  89912. */
  89913. ColorCurves.prototype.getClassName = function () {
  89914. return "ColorCurves";
  89915. };
  89916. /**
  89917. * Binds the color curves to the shader.
  89918. * @param colorCurves The color curve to bind
  89919. * @param effect The effect to bind to
  89920. * @param positiveUniform The positive uniform shader parameter
  89921. * @param neutralUniform The neutral uniform shader parameter
  89922. * @param negativeUniform The negative uniform shader parameter
  89923. */
  89924. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  89925. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  89926. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  89927. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  89928. if (colorCurves._dirty) {
  89929. colorCurves._dirty = false;
  89930. // Fill in global info.
  89931. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  89932. // Compute highlights info.
  89933. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  89934. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  89935. // Compute midtones info.
  89936. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  89937. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  89938. // Compute shadows info.
  89939. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  89940. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  89941. // Compute deltas (neutral is midtones).
  89942. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  89943. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  89944. }
  89945. if (effect) {
  89946. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  89947. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  89948. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  89949. }
  89950. };
  89951. /**
  89952. * Prepare the list of uniforms associated with the ColorCurves effects.
  89953. * @param uniformsList The list of uniforms used in the effect
  89954. */
  89955. ColorCurves.PrepareUniforms = function (uniformsList) {
  89956. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  89957. };
  89958. /**
  89959. * Returns color grading data based on a hue, density, saturation and exposure value.
  89960. * @param filterHue The hue of the color filter.
  89961. * @param filterDensity The density of the color filter.
  89962. * @param saturation The saturation.
  89963. * @param exposure The exposure.
  89964. * @param result The result data container.
  89965. */
  89966. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  89967. if (hue == null) {
  89968. return;
  89969. }
  89970. hue = ColorCurves.clamp(hue, 0, 360);
  89971. density = ColorCurves.clamp(density, -100, 100);
  89972. saturation = ColorCurves.clamp(saturation, -100, 100);
  89973. exposure = ColorCurves.clamp(exposure, -100, 100);
  89974. // Remap the slider/config filter density with non-linear mapping and also scale by half
  89975. // so that the maximum filter density is only 50% control. This provides fine control
  89976. // for small values and reasonable range.
  89977. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  89978. density *= 0.5;
  89979. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  89980. if (density < 0) {
  89981. density *= -1;
  89982. hue = (hue + 180) % 360;
  89983. }
  89984. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  89985. result.scaleToRef(2, result);
  89986. result.a = 1 + 0.01 * saturation;
  89987. };
  89988. /**
  89989. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  89990. * @param value The input slider value in range [-100,100].
  89991. * @returns Adjusted value.
  89992. */
  89993. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  89994. value /= 100;
  89995. var x = Math.abs(value);
  89996. x = Math.pow(x, 2);
  89997. if (value < 0) {
  89998. x *= -1;
  89999. }
  90000. x *= 100;
  90001. return x;
  90002. };
  90003. /**
  90004. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  90005. * @param hue The hue (H) input.
  90006. * @param saturation The saturation (S) input.
  90007. * @param brightness The brightness (B) input.
  90008. * @result An RGBA color represented as Vector4.
  90009. */
  90010. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  90011. var h = ColorCurves.clamp(hue, 0, 360);
  90012. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  90013. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  90014. if (s === 0) {
  90015. result.r = v;
  90016. result.g = v;
  90017. result.b = v;
  90018. }
  90019. else {
  90020. // sector 0 to 5
  90021. h /= 60;
  90022. var i = Math.floor(h);
  90023. // fractional part of h
  90024. var f = h - i;
  90025. var p = v * (1 - s);
  90026. var q = v * (1 - s * f);
  90027. var t = v * (1 - s * (1 - f));
  90028. switch (i) {
  90029. case 0:
  90030. result.r = v;
  90031. result.g = t;
  90032. result.b = p;
  90033. break;
  90034. case 1:
  90035. result.r = q;
  90036. result.g = v;
  90037. result.b = p;
  90038. break;
  90039. case 2:
  90040. result.r = p;
  90041. result.g = v;
  90042. result.b = t;
  90043. break;
  90044. case 3:
  90045. result.r = p;
  90046. result.g = q;
  90047. result.b = v;
  90048. break;
  90049. case 4:
  90050. result.r = t;
  90051. result.g = p;
  90052. result.b = v;
  90053. break;
  90054. default: // case 5:
  90055. result.r = v;
  90056. result.g = p;
  90057. result.b = q;
  90058. break;
  90059. }
  90060. }
  90061. result.a = 1;
  90062. };
  90063. /**
  90064. * Returns a value clamped between min and max
  90065. * @param value The value to clamp
  90066. * @param min The minimum of value
  90067. * @param max The maximum of value
  90068. * @returns The clamped value.
  90069. */
  90070. ColorCurves.clamp = function (value, min, max) {
  90071. return Math.min(Math.max(value, min), max);
  90072. };
  90073. /**
  90074. * Clones the current color curve instance.
  90075. * @return The cloned curves
  90076. */
  90077. ColorCurves.prototype.clone = function () {
  90078. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  90079. };
  90080. /**
  90081. * Serializes the current color curve instance to a json representation.
  90082. * @return a JSON representation
  90083. */
  90084. ColorCurves.prototype.serialize = function () {
  90085. return BABYLON.SerializationHelper.Serialize(this);
  90086. };
  90087. /**
  90088. * Parses the color curve from a json representation.
  90089. * @param source the JSON source to parse
  90090. * @return The parsed curves
  90091. */
  90092. ColorCurves.Parse = function (source) {
  90093. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  90094. };
  90095. __decorate([
  90096. BABYLON.serialize()
  90097. ], ColorCurves.prototype, "_globalHue", void 0);
  90098. __decorate([
  90099. BABYLON.serialize()
  90100. ], ColorCurves.prototype, "_globalDensity", void 0);
  90101. __decorate([
  90102. BABYLON.serialize()
  90103. ], ColorCurves.prototype, "_globalSaturation", void 0);
  90104. __decorate([
  90105. BABYLON.serialize()
  90106. ], ColorCurves.prototype, "_globalExposure", void 0);
  90107. __decorate([
  90108. BABYLON.serialize()
  90109. ], ColorCurves.prototype, "_highlightsHue", void 0);
  90110. __decorate([
  90111. BABYLON.serialize()
  90112. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  90113. __decorate([
  90114. BABYLON.serialize()
  90115. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  90116. __decorate([
  90117. BABYLON.serialize()
  90118. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  90119. __decorate([
  90120. BABYLON.serialize()
  90121. ], ColorCurves.prototype, "_midtonesHue", void 0);
  90122. __decorate([
  90123. BABYLON.serialize()
  90124. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  90125. __decorate([
  90126. BABYLON.serialize()
  90127. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  90128. __decorate([
  90129. BABYLON.serialize()
  90130. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  90131. return ColorCurves;
  90132. }());
  90133. BABYLON.ColorCurves = ColorCurves;
  90134. })(BABYLON || (BABYLON = {}));
  90135. //# sourceMappingURL=babylon.colorCurves.js.map
  90136. var BABYLON;
  90137. (function (BABYLON) {
  90138. /**
  90139. * Post process which applies a refractin texture
  90140. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90141. */
  90142. var RefractionPostProcess = /** @class */ (function (_super) {
  90143. __extends(RefractionPostProcess, _super);
  90144. /**
  90145. * Initializes the RefractionPostProcess
  90146. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90147. * @param name The name of the effect.
  90148. * @param refractionTextureUrl Url of the refraction texture to use
  90149. * @param color the base color of the refraction (used to taint the rendering)
  90150. * @param depth simulated refraction depth
  90151. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  90152. * @param camera The camera to apply the render pass to.
  90153. * @param options The required width/height ratio to downsize to before computing the render pass.
  90154. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90155. * @param engine The engine which the post process will be applied. (default: current engine)
  90156. * @param reusable If the post process can be reused on the same frame. (default: false)
  90157. */
  90158. function RefractionPostProcess(name, refractionTextureUrl,
  90159. /** the base color of the refraction (used to taint the rendering) */
  90160. color,
  90161. /** simulated refraction depth */
  90162. depth,
  90163. /** the coefficient of the base color (0 to remove base color tainting) */
  90164. colorLevel, options, camera, samplingMode, engine, reusable) {
  90165. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  90166. _this.color = color;
  90167. _this.depth = depth;
  90168. _this.colorLevel = colorLevel;
  90169. _this._ownRefractionTexture = true;
  90170. _this.onActivateObservable.add(function (cam) {
  90171. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  90172. });
  90173. _this.onApplyObservable.add(function (effect) {
  90174. effect.setColor3("baseColor", _this.color);
  90175. effect.setFloat("depth", _this.depth);
  90176. effect.setFloat("colorLevel", _this.colorLevel);
  90177. effect.setTexture("refractionSampler", _this._refTexture);
  90178. });
  90179. return _this;
  90180. }
  90181. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  90182. /**
  90183. * Gets or sets the refraction texture
  90184. * Please note that you are responsible for disposing the texture if you set it manually
  90185. */
  90186. get: function () {
  90187. return this._refTexture;
  90188. },
  90189. set: function (value) {
  90190. if (this._refTexture && this._ownRefractionTexture) {
  90191. this._refTexture.dispose();
  90192. }
  90193. this._refTexture = value;
  90194. this._ownRefractionTexture = false;
  90195. },
  90196. enumerable: true,
  90197. configurable: true
  90198. });
  90199. // Methods
  90200. /**
  90201. * Disposes of the post process
  90202. * @param camera Camera to dispose post process on
  90203. */
  90204. RefractionPostProcess.prototype.dispose = function (camera) {
  90205. if (this._refTexture && this._ownRefractionTexture) {
  90206. this._refTexture.dispose();
  90207. this._refTexture = null;
  90208. }
  90209. _super.prototype.dispose.call(this, camera);
  90210. };
  90211. return RefractionPostProcess;
  90212. }(BABYLON.PostProcess));
  90213. BABYLON.RefractionPostProcess = RefractionPostProcess;
  90214. })(BABYLON || (BABYLON = {}));
  90215. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  90216. var BABYLON;
  90217. (function (BABYLON) {
  90218. /**
  90219. * Post process used to render in black and white
  90220. */
  90221. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  90222. __extends(BlackAndWhitePostProcess, _super);
  90223. /**
  90224. * Creates a black and white post process
  90225. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  90226. * @param name The name of the effect.
  90227. * @param options The required width/height ratio to downsize to before computing the render pass.
  90228. * @param camera The camera to apply the render pass to.
  90229. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90230. * @param engine The engine which the post process will be applied. (default: current engine)
  90231. * @param reusable If the post process can be reused on the same frame. (default: false)
  90232. */
  90233. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  90234. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  90235. /**
  90236. * Linear about to convert he result to black and white (default: 1)
  90237. */
  90238. _this.degree = 1;
  90239. _this.onApplyObservable.add(function (effect) {
  90240. effect.setFloat("degree", _this.degree);
  90241. });
  90242. return _this;
  90243. }
  90244. return BlackAndWhitePostProcess;
  90245. }(BABYLON.PostProcess));
  90246. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  90247. })(BABYLON || (BABYLON = {}));
  90248. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  90249. var BABYLON;
  90250. (function (BABYLON) {
  90251. /**
  90252. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  90253. * input texture to perform effects such as edge detection or sharpening
  90254. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  90255. */
  90256. var ConvolutionPostProcess = /** @class */ (function (_super) {
  90257. __extends(ConvolutionPostProcess, _super);
  90258. /**
  90259. * Creates a new instance ConvolutionPostProcess
  90260. * @param name The name of the effect.
  90261. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  90262. * @param options The required width/height ratio to downsize to before computing the render pass.
  90263. * @param camera The camera to apply the render pass to.
  90264. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90265. * @param engine The engine which the post process will be applied. (default: current engine)
  90266. * @param reusable If the post process can be reused on the same frame. (default: false)
  90267. * @param textureType Type of textures used when performing the post process. (default: 0)
  90268. */
  90269. function ConvolutionPostProcess(name,
  90270. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  90271. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  90272. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90273. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90274. _this.kernel = kernel;
  90275. _this.onApply = function (effect) {
  90276. effect.setFloat2("screenSize", _this.width, _this.height);
  90277. effect.setArray("kernel", _this.kernel);
  90278. };
  90279. return _this;
  90280. }
  90281. // Statics
  90282. /**
  90283. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90284. */
  90285. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  90286. /**
  90287. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90288. */
  90289. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  90290. /**
  90291. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90292. */
  90293. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  90294. /**
  90295. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90296. */
  90297. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  90298. /**
  90299. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90300. */
  90301. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  90302. /**
  90303. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90304. */
  90305. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  90306. return ConvolutionPostProcess;
  90307. }(BABYLON.PostProcess));
  90308. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  90309. })(BABYLON || (BABYLON = {}));
  90310. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  90311. var BABYLON;
  90312. (function (BABYLON) {
  90313. /**
  90314. * Applies a kernel filter to the image
  90315. */
  90316. var FilterPostProcess = /** @class */ (function (_super) {
  90317. __extends(FilterPostProcess, _super);
  90318. /**
  90319. *
  90320. * @param name The name of the effect.
  90321. * @param kernelMatrix The matrix to be applied to the image
  90322. * @param options The required width/height ratio to downsize to before computing the render pass.
  90323. * @param camera The camera to apply the render pass to.
  90324. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90325. * @param engine The engine which the post process will be applied. (default: current engine)
  90326. * @param reusable If the post process can be reused on the same frame. (default: false)
  90327. */
  90328. function FilterPostProcess(name,
  90329. /** The matrix to be applied to the image */
  90330. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  90331. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  90332. _this.kernelMatrix = kernelMatrix;
  90333. _this.onApply = function (effect) {
  90334. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  90335. };
  90336. return _this;
  90337. }
  90338. return FilterPostProcess;
  90339. }(BABYLON.PostProcess));
  90340. BABYLON.FilterPostProcess = FilterPostProcess;
  90341. })(BABYLON || (BABYLON = {}));
  90342. //# sourceMappingURL=babylon.filterPostProcess.js.map
  90343. var BABYLON;
  90344. (function (BABYLON) {
  90345. /**
  90346. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  90347. */
  90348. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  90349. __extends(VolumetricLightScatteringPostProcess, _super);
  90350. /**
  90351. * @constructor
  90352. * @param name The post-process name
  90353. * @param 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)
  90354. * @param camera The camera that the post-process will be attached to
  90355. * @param mesh The mesh used to create the light scattering
  90356. * @param samples The post-process quality, default 100
  90357. * @param samplingModeThe post-process filtering mode
  90358. * @param engine The babylon engine
  90359. * @param reusable If the post-process is reusable
  90360. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  90361. */
  90362. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  90363. if (samples === void 0) { samples = 100; }
  90364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90365. 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;
  90366. _this._screenCoordinates = BABYLON.Vector2.Zero();
  90367. /**
  90368. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  90369. */
  90370. _this.customMeshPosition = BABYLON.Vector3.Zero();
  90371. /**
  90372. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  90373. */
  90374. _this.useCustomMeshPosition = false;
  90375. /**
  90376. * If the post-process should inverse the light scattering direction
  90377. */
  90378. _this.invert = true;
  90379. /**
  90380. * Array containing the excluded meshes not rendered in the internal pass
  90381. */
  90382. _this.excludedMeshes = new Array();
  90383. /**
  90384. * Controls the overall intensity of the post-process
  90385. */
  90386. _this.exposure = 0.3;
  90387. /**
  90388. * Dissipates each sample's contribution in range [0, 1]
  90389. */
  90390. _this.decay = 0.96815;
  90391. /**
  90392. * Controls the overall intensity of each sample
  90393. */
  90394. _this.weight = 0.58767;
  90395. /**
  90396. * Controls the density of each sample
  90397. */
  90398. _this.density = 0.926;
  90399. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  90400. engine = scene.getEngine();
  90401. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  90402. // Configure mesh
  90403. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  90404. // Configure
  90405. _this._createPass(scene, ratio.passRatio || ratio);
  90406. _this.onActivate = function (camera) {
  90407. if (!_this.isSupported) {
  90408. _this.dispose(camera);
  90409. }
  90410. _this.onActivate = null;
  90411. };
  90412. _this.onApplyObservable.add(function (effect) {
  90413. _this._updateMeshScreenCoordinates(scene);
  90414. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  90415. effect.setFloat("exposure", _this.exposure);
  90416. effect.setFloat("decay", _this.decay);
  90417. effect.setFloat("weight", _this.weight);
  90418. effect.setFloat("density", _this.density);
  90419. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  90420. });
  90421. return _this;
  90422. }
  90423. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  90424. /**
  90425. * @hidden
  90426. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  90427. */
  90428. get: function () {
  90429. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90430. return false;
  90431. },
  90432. set: function (useDiffuseColor) {
  90433. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90434. },
  90435. enumerable: true,
  90436. configurable: true
  90437. });
  90438. /**
  90439. * Returns the string "VolumetricLightScatteringPostProcess"
  90440. * @returns "VolumetricLightScatteringPostProcess"
  90441. */
  90442. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  90443. return "VolumetricLightScatteringPostProcess";
  90444. };
  90445. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  90446. var mesh = subMesh.getMesh();
  90447. // Render this.mesh as default
  90448. if (mesh === this.mesh && mesh.material) {
  90449. return mesh.material.isReady(mesh);
  90450. }
  90451. var defines = [];
  90452. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90453. var material = subMesh.getMaterial();
  90454. // Alpha test
  90455. if (material) {
  90456. if (material.needAlphaTesting()) {
  90457. defines.push("#define ALPHATEST");
  90458. }
  90459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90460. attribs.push(BABYLON.VertexBuffer.UVKind);
  90461. defines.push("#define UV1");
  90462. }
  90463. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90464. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90465. defines.push("#define UV2");
  90466. }
  90467. }
  90468. // Bones
  90469. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90472. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90473. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90474. }
  90475. else {
  90476. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90477. }
  90478. // Instances
  90479. if (useInstances) {
  90480. defines.push("#define INSTANCES");
  90481. attribs.push("world0");
  90482. attribs.push("world1");
  90483. attribs.push("world2");
  90484. attribs.push("world3");
  90485. }
  90486. // Get correct effect
  90487. var join = defines.join("\n");
  90488. if (this._cachedDefines !== join) {
  90489. this._cachedDefines = join;
  90490. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  90491. }
  90492. return this._volumetricLightScatteringPass.isReady();
  90493. };
  90494. /**
  90495. * Sets the new light position for light scattering effect
  90496. * @param position The new custom light position
  90497. */
  90498. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  90499. this.customMeshPosition = position;
  90500. };
  90501. /**
  90502. * Returns the light position for light scattering effect
  90503. * @return Vector3 The custom light position
  90504. */
  90505. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  90506. return this.customMeshPosition;
  90507. };
  90508. /**
  90509. * Disposes the internal assets and detaches the post-process from the camera
  90510. */
  90511. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  90512. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  90513. if (rttIndex !== -1) {
  90514. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  90515. }
  90516. this._volumetricLightScatteringRTT.dispose();
  90517. _super.prototype.dispose.call(this, camera);
  90518. };
  90519. /**
  90520. * Returns the render target texture used by the post-process
  90521. * @return the render target texture used by the post-process
  90522. */
  90523. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  90524. return this._volumetricLightScatteringRTT;
  90525. };
  90526. // Private methods
  90527. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  90528. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  90529. return true;
  90530. }
  90531. return false;
  90532. };
  90533. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  90534. var _this = this;
  90535. var engine = scene.getEngine();
  90536. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90537. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90538. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90539. this._volumetricLightScatteringRTT.renderList = null;
  90540. this._volumetricLightScatteringRTT.renderParticles = false;
  90541. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  90542. var camera = this.getCamera();
  90543. if (camera) {
  90544. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90545. }
  90546. else {
  90547. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90548. }
  90549. // Custom render function for submeshes
  90550. var renderSubMesh = function (subMesh) {
  90551. var mesh = subMesh.getRenderingMesh();
  90552. if (_this._meshExcluded(mesh)) {
  90553. return;
  90554. }
  90555. var material = subMesh.getMaterial();
  90556. if (!material) {
  90557. return;
  90558. }
  90559. var scene = mesh.getScene();
  90560. var engine = scene.getEngine();
  90561. // Culling
  90562. engine.setState(material.backFaceCulling);
  90563. // Managing instances
  90564. var batch = mesh._getInstancesRenderList(subMesh._id);
  90565. if (batch.mustReturn) {
  90566. return;
  90567. }
  90568. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  90569. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  90570. var effect = _this._volumetricLightScatteringPass;
  90571. if (mesh === _this.mesh) {
  90572. if (subMesh.effect) {
  90573. effect = subMesh.effect;
  90574. }
  90575. else {
  90576. effect = material.getEffect();
  90577. }
  90578. }
  90579. engine.enableEffect(effect);
  90580. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  90581. if (mesh === _this.mesh) {
  90582. material.bind(mesh.getWorldMatrix(), mesh);
  90583. }
  90584. else {
  90585. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  90586. // Alpha test
  90587. if (material && material.needAlphaTesting()) {
  90588. var alphaTexture = material.getAlphaTestTexture();
  90589. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  90590. if (alphaTexture) {
  90591. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90592. }
  90593. }
  90594. // Bones
  90595. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90596. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90597. }
  90598. }
  90599. // Draw
  90600. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  90601. }
  90602. };
  90603. // Render target texture callbacks
  90604. var savedSceneClearColor;
  90605. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  90606. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  90607. savedSceneClearColor = scene.clearColor;
  90608. scene.clearColor = sceneClearColor;
  90609. });
  90610. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  90611. scene.clearColor = savedSceneClearColor;
  90612. });
  90613. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90614. var engine = scene.getEngine();
  90615. var index;
  90616. if (depthOnlySubMeshes.length) {
  90617. engine.setColorWrite(false);
  90618. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90619. renderSubMesh(depthOnlySubMeshes.data[index]);
  90620. }
  90621. engine.setColorWrite(true);
  90622. }
  90623. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90624. renderSubMesh(opaqueSubMeshes.data[index]);
  90625. }
  90626. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90627. renderSubMesh(alphaTestSubMeshes.data[index]);
  90628. }
  90629. if (transparentSubMeshes.length) {
  90630. // Sort sub meshes
  90631. for (index = 0; index < transparentSubMeshes.length; index++) {
  90632. var submesh = transparentSubMeshes.data[index];
  90633. var boundingInfo = submesh.getBoundingInfo();
  90634. if (boundingInfo && scene.activeCamera) {
  90635. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  90636. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  90637. }
  90638. }
  90639. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  90640. sortedArray.sort(function (a, b) {
  90641. // Alpha index first
  90642. if (a._alphaIndex > b._alphaIndex) {
  90643. return 1;
  90644. }
  90645. if (a._alphaIndex < b._alphaIndex) {
  90646. return -1;
  90647. }
  90648. // Then distance to camera
  90649. if (a._distanceToCamera < b._distanceToCamera) {
  90650. return 1;
  90651. }
  90652. if (a._distanceToCamera > b._distanceToCamera) {
  90653. return -1;
  90654. }
  90655. return 0;
  90656. });
  90657. // Render sub meshes
  90658. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  90659. for (index = 0; index < sortedArray.length; index++) {
  90660. renderSubMesh(sortedArray[index]);
  90661. }
  90662. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90663. }
  90664. };
  90665. };
  90666. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  90667. var transform = scene.getTransformMatrix();
  90668. var meshPosition;
  90669. if (this.useCustomMeshPosition) {
  90670. meshPosition = this.customMeshPosition;
  90671. }
  90672. else if (this.attachedNode) {
  90673. meshPosition = this.attachedNode.position;
  90674. }
  90675. else {
  90676. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  90677. }
  90678. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  90679. this._screenCoordinates.x = pos.x / this._viewPort.width;
  90680. this._screenCoordinates.y = pos.y / this._viewPort.height;
  90681. if (this.invert) {
  90682. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  90683. }
  90684. };
  90685. // Static methods
  90686. /**
  90687. * Creates a default mesh for the Volumeric Light Scattering post-process
  90688. * @param name The mesh name
  90689. * @param scene The scene where to create the mesh
  90690. * @return the default mesh
  90691. */
  90692. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  90693. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  90694. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  90695. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  90696. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  90697. mesh.material = material;
  90698. return mesh;
  90699. };
  90700. __decorate([
  90701. BABYLON.serializeAsVector3()
  90702. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  90703. __decorate([
  90704. BABYLON.serialize()
  90705. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  90706. __decorate([
  90707. BABYLON.serialize()
  90708. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  90709. __decorate([
  90710. BABYLON.serializeAsMeshReference()
  90711. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  90712. __decorate([
  90713. BABYLON.serialize()
  90714. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  90715. __decorate([
  90716. BABYLON.serialize()
  90717. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  90718. __decorate([
  90719. BABYLON.serialize()
  90720. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  90721. __decorate([
  90722. BABYLON.serialize()
  90723. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  90724. __decorate([
  90725. BABYLON.serialize()
  90726. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  90727. return VolumetricLightScatteringPostProcess;
  90728. }(BABYLON.PostProcess));
  90729. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  90730. })(BABYLON || (BABYLON = {}));
  90731. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  90732. var BABYLON;
  90733. (function (BABYLON) {
  90734. /**
  90735. *
  90736. * This post-process allows the modification of rendered colors by using
  90737. * a 'look-up table' (LUT). This effect is also called Color Grading.
  90738. *
  90739. * The object needs to be provided an url to a texture containing the color
  90740. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  90741. * Use an image editing software to tweak the LUT to match your needs.
  90742. *
  90743. * For an example of a color LUT, see here:
  90744. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  90745. * For explanations on color grading, see here:
  90746. * @see http://udn.epicgames.com/Three/ColorGrading.html
  90747. *
  90748. */
  90749. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  90750. __extends(ColorCorrectionPostProcess, _super);
  90751. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  90752. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  90753. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90754. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  90755. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90756. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90757. _this.onApply = function (effect) {
  90758. effect.setTexture("colorTable", _this._colorTableTexture);
  90759. };
  90760. return _this;
  90761. }
  90762. return ColorCorrectionPostProcess;
  90763. }(BABYLON.PostProcess));
  90764. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  90765. })(BABYLON || (BABYLON = {}));
  90766. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  90767. var BABYLON;
  90768. (function (BABYLON) {
  90769. /** Defines operator used for tonemapping */
  90770. var TonemappingOperator;
  90771. (function (TonemappingOperator) {
  90772. /** Hable */
  90773. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  90774. /** Reinhard */
  90775. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  90776. /** HejiDawson */
  90777. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  90778. /** Photographic */
  90779. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  90780. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  90781. /**
  90782. * Defines a post process to apply tone mapping
  90783. */
  90784. var TonemapPostProcess = /** @class */ (function (_super) {
  90785. __extends(TonemapPostProcess, _super);
  90786. /**
  90787. * Creates a new TonemapPostProcess
  90788. * @param name defines the name of the postprocess
  90789. * @param _operator defines the operator to use
  90790. * @param exposureAdjustment defines the required exposure adjustement
  90791. * @param camera defines the camera to use (can be null)
  90792. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  90793. * @param engine defines the hosting engine (can be ignore if camera is set)
  90794. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  90795. */
  90796. function TonemapPostProcess(name, _operator,
  90797. /** Defines the required exposure adjustement */
  90798. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  90799. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90800. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90801. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  90802. _this._operator = _operator;
  90803. _this.exposureAdjustment = exposureAdjustment;
  90804. var defines = "#define ";
  90805. if (_this._operator === TonemappingOperator.Hable) {
  90806. defines += "HABLE_TONEMAPPING";
  90807. }
  90808. else if (_this._operator === TonemappingOperator.Reinhard) {
  90809. defines += "REINHARD_TONEMAPPING";
  90810. }
  90811. else if (_this._operator === TonemappingOperator.HejiDawson) {
  90812. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  90813. }
  90814. else if (_this._operator === TonemappingOperator.Photographic) {
  90815. defines += "PHOTOGRAPHIC_TONEMAPPING";
  90816. }
  90817. //sadly a second call to create the effect.
  90818. _this.updateEffect(defines);
  90819. _this.onApply = function (effect) {
  90820. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  90821. };
  90822. return _this;
  90823. }
  90824. return TonemapPostProcess;
  90825. }(BABYLON.PostProcess));
  90826. BABYLON.TonemapPostProcess = TonemapPostProcess;
  90827. })(BABYLON || (BABYLON = {}));
  90828. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  90829. var BABYLON;
  90830. (function (BABYLON) {
  90831. /**
  90832. * DisplayPassPostProcess which produces an output the same as it's input
  90833. */
  90834. var DisplayPassPostProcess = /** @class */ (function (_super) {
  90835. __extends(DisplayPassPostProcess, _super);
  90836. /**
  90837. * Creates the DisplayPassPostProcess
  90838. * @param name The name of the effect.
  90839. * @param options The required width/height ratio to downsize to before computing the render pass.
  90840. * @param camera The camera to apply the render pass to.
  90841. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90842. * @param engine The engine which the post process will be applied. (default: current engine)
  90843. * @param reusable If the post process can be reused on the same frame. (default: false)
  90844. */
  90845. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  90846. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  90847. }
  90848. return DisplayPassPostProcess;
  90849. }(BABYLON.PostProcess));
  90850. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  90851. })(BABYLON || (BABYLON = {}));
  90852. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  90853. var BABYLON;
  90854. (function (BABYLON) {
  90855. /**
  90856. * Extracts highlights from the image
  90857. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90858. */
  90859. var HighlightsPostProcess = /** @class */ (function (_super) {
  90860. __extends(HighlightsPostProcess, _super);
  90861. /**
  90862. * Extracts highlights from the image
  90863. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90864. * @param name The name of the effect.
  90865. * @param options The required width/height ratio to downsize to before computing the render pass.
  90866. * @param camera The camera to apply the render pass to.
  90867. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90868. * @param engine The engine which the post process will be applied. (default: current engine)
  90869. * @param reusable If the post process can be reused on the same frame. (default: false)
  90870. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  90871. */
  90872. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  90873. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90874. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90875. }
  90876. return HighlightsPostProcess;
  90877. }(BABYLON.PostProcess));
  90878. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  90879. })(BABYLON || (BABYLON = {}));
  90880. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  90881. var BABYLON;
  90882. (function (BABYLON) {
  90883. /**
  90884. * ImageProcessingPostProcess
  90885. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  90886. */
  90887. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  90888. __extends(ImageProcessingPostProcess, _super);
  90889. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  90890. if (camera === void 0) { camera = null; }
  90891. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90892. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  90893. _this._fromLinearSpace = true;
  90894. /**
  90895. * Defines cache preventing GC.
  90896. */
  90897. _this._defines = {
  90898. IMAGEPROCESSING: false,
  90899. VIGNETTE: false,
  90900. VIGNETTEBLENDMODEMULTIPLY: false,
  90901. VIGNETTEBLENDMODEOPAQUE: false,
  90902. TONEMAPPING: false,
  90903. TONEMAPPING_ACES: false,
  90904. CONTRAST: false,
  90905. COLORCURVES: false,
  90906. COLORGRADING: false,
  90907. COLORGRADING3D: false,
  90908. FROMLINEARSPACE: false,
  90909. SAMPLER3DGREENDEPTH: false,
  90910. SAMPLER3DBGRMAP: false,
  90911. IMAGEPROCESSINGPOSTPROCESS: false,
  90912. EXPOSURE: false,
  90913. };
  90914. // Setup the configuration as forced by the constructor. This would then not force the
  90915. // scene materials output in linear space and let untouched the default forward pass.
  90916. if (imageProcessingConfiguration) {
  90917. imageProcessingConfiguration.applyByPostProcess = true;
  90918. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  90919. // This will cause the shader to be compiled
  90920. _this.fromLinearSpace = false;
  90921. }
  90922. // Setup the default processing configuration to the scene.
  90923. else {
  90924. _this._attachImageProcessingConfiguration(null, true);
  90925. _this.imageProcessingConfiguration.applyByPostProcess = true;
  90926. }
  90927. _this.onApply = function (effect) {
  90928. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  90929. };
  90930. return _this;
  90931. }
  90932. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  90933. /**
  90934. * Gets the image processing configuration used either in this material.
  90935. */
  90936. get: function () {
  90937. return this._imageProcessingConfiguration;
  90938. },
  90939. /**
  90940. * Sets the Default image processing configuration used either in the this material.
  90941. *
  90942. * If sets to null, the scene one is in use.
  90943. */
  90944. set: function (value) {
  90945. this._attachImageProcessingConfiguration(value);
  90946. },
  90947. enumerable: true,
  90948. configurable: true
  90949. });
  90950. /**
  90951. * Attaches a new image processing configuration to the PBR Material.
  90952. * @param configuration
  90953. */
  90954. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  90955. var _this = this;
  90956. if (doNotBuild === void 0) { doNotBuild = false; }
  90957. if (configuration === this._imageProcessingConfiguration) {
  90958. return;
  90959. }
  90960. // Detaches observer.
  90961. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90962. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90963. }
  90964. // Pick the scene configuration if needed.
  90965. if (!configuration) {
  90966. var scene = null;
  90967. var engine = this.getEngine();
  90968. var camera = this.getCamera();
  90969. if (camera) {
  90970. scene = camera.getScene();
  90971. }
  90972. else if (engine && engine.scenes) {
  90973. var scenes = engine.scenes;
  90974. scene = scenes[scenes.length - 1];
  90975. }
  90976. else {
  90977. scene = BABYLON.Engine.LastCreatedScene;
  90978. }
  90979. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  90980. }
  90981. else {
  90982. this._imageProcessingConfiguration = configuration;
  90983. }
  90984. // Attaches observer.
  90985. if (this._imageProcessingConfiguration) {
  90986. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90987. _this._updateParameters();
  90988. });
  90989. }
  90990. // Ensure the effect will be rebuilt.
  90991. if (!doNotBuild) {
  90992. this._updateParameters();
  90993. }
  90994. };
  90995. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  90996. /**
  90997. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  90998. */
  90999. get: function () {
  91000. return this.imageProcessingConfiguration.colorCurves;
  91001. },
  91002. /**
  91003. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  91004. */
  91005. set: function (value) {
  91006. this.imageProcessingConfiguration.colorCurves = value;
  91007. },
  91008. enumerable: true,
  91009. configurable: true
  91010. });
  91011. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  91012. /**
  91013. * Gets wether the color curves effect is enabled.
  91014. */
  91015. get: function () {
  91016. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91017. },
  91018. /**
  91019. * Sets wether the color curves effect is enabled.
  91020. */
  91021. set: function (value) {
  91022. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91023. },
  91024. enumerable: true,
  91025. configurable: true
  91026. });
  91027. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  91028. /**
  91029. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  91030. */
  91031. get: function () {
  91032. return this.imageProcessingConfiguration.colorGradingTexture;
  91033. },
  91034. /**
  91035. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  91036. */
  91037. set: function (value) {
  91038. this.imageProcessingConfiguration.colorGradingTexture = value;
  91039. },
  91040. enumerable: true,
  91041. configurable: true
  91042. });
  91043. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  91044. /**
  91045. * Gets wether the color grading effect is enabled.
  91046. */
  91047. get: function () {
  91048. return this.imageProcessingConfiguration.colorGradingEnabled;
  91049. },
  91050. /**
  91051. * Gets wether the color grading effect is enabled.
  91052. */
  91053. set: function (value) {
  91054. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91055. },
  91056. enumerable: true,
  91057. configurable: true
  91058. });
  91059. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  91060. /**
  91061. * Gets exposure used in the effect.
  91062. */
  91063. get: function () {
  91064. return this.imageProcessingConfiguration.exposure;
  91065. },
  91066. /**
  91067. * Sets exposure used in the effect.
  91068. */
  91069. set: function (value) {
  91070. this.imageProcessingConfiguration.exposure = value;
  91071. },
  91072. enumerable: true,
  91073. configurable: true
  91074. });
  91075. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  91076. /**
  91077. * Gets wether tonemapping is enabled or not.
  91078. */
  91079. get: function () {
  91080. return this._imageProcessingConfiguration.toneMappingEnabled;
  91081. },
  91082. /**
  91083. * Sets wether tonemapping is enabled or not
  91084. */
  91085. set: function (value) {
  91086. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91087. },
  91088. enumerable: true,
  91089. configurable: true
  91090. });
  91091. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  91092. /**
  91093. * Gets contrast used in the effect.
  91094. */
  91095. get: function () {
  91096. return this.imageProcessingConfiguration.contrast;
  91097. },
  91098. /**
  91099. * Sets contrast used in the effect.
  91100. */
  91101. set: function (value) {
  91102. this.imageProcessingConfiguration.contrast = value;
  91103. },
  91104. enumerable: true,
  91105. configurable: true
  91106. });
  91107. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  91108. /**
  91109. * Gets Vignette stretch size.
  91110. */
  91111. get: function () {
  91112. return this.imageProcessingConfiguration.vignetteStretch;
  91113. },
  91114. /**
  91115. * Sets Vignette stretch size.
  91116. */
  91117. set: function (value) {
  91118. this.imageProcessingConfiguration.vignetteStretch = value;
  91119. },
  91120. enumerable: true,
  91121. configurable: true
  91122. });
  91123. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  91124. /**
  91125. * Gets Vignette centre X Offset.
  91126. */
  91127. get: function () {
  91128. return this.imageProcessingConfiguration.vignetteCentreX;
  91129. },
  91130. /**
  91131. * Sets Vignette centre X Offset.
  91132. */
  91133. set: function (value) {
  91134. this.imageProcessingConfiguration.vignetteCentreX = value;
  91135. },
  91136. enumerable: true,
  91137. configurable: true
  91138. });
  91139. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  91140. /**
  91141. * Gets Vignette centre Y Offset.
  91142. */
  91143. get: function () {
  91144. return this.imageProcessingConfiguration.vignetteCentreY;
  91145. },
  91146. /**
  91147. * Sets Vignette centre Y Offset.
  91148. */
  91149. set: function (value) {
  91150. this.imageProcessingConfiguration.vignetteCentreY = value;
  91151. },
  91152. enumerable: true,
  91153. configurable: true
  91154. });
  91155. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  91156. /**
  91157. * Gets Vignette weight or intensity of the vignette effect.
  91158. */
  91159. get: function () {
  91160. return this.imageProcessingConfiguration.vignetteWeight;
  91161. },
  91162. /**
  91163. * Sets Vignette weight or intensity of the vignette effect.
  91164. */
  91165. set: function (value) {
  91166. this.imageProcessingConfiguration.vignetteWeight = value;
  91167. },
  91168. enumerable: true,
  91169. configurable: true
  91170. });
  91171. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  91172. /**
  91173. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91174. * if vignetteEnabled is set to true.
  91175. */
  91176. get: function () {
  91177. return this.imageProcessingConfiguration.vignetteColor;
  91178. },
  91179. /**
  91180. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91181. * if vignetteEnabled is set to true.
  91182. */
  91183. set: function (value) {
  91184. this.imageProcessingConfiguration.vignetteColor = value;
  91185. },
  91186. enumerable: true,
  91187. configurable: true
  91188. });
  91189. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  91190. /**
  91191. * Gets Camera field of view used by the Vignette effect.
  91192. */
  91193. get: function () {
  91194. return this.imageProcessingConfiguration.vignetteCameraFov;
  91195. },
  91196. /**
  91197. * Sets Camera field of view used by the Vignette effect.
  91198. */
  91199. set: function (value) {
  91200. this.imageProcessingConfiguration.vignetteCameraFov = value;
  91201. },
  91202. enumerable: true,
  91203. configurable: true
  91204. });
  91205. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  91206. /**
  91207. * Gets the vignette blend mode allowing different kind of effect.
  91208. */
  91209. get: function () {
  91210. return this.imageProcessingConfiguration.vignetteBlendMode;
  91211. },
  91212. /**
  91213. * Sets the vignette blend mode allowing different kind of effect.
  91214. */
  91215. set: function (value) {
  91216. this.imageProcessingConfiguration.vignetteBlendMode = value;
  91217. },
  91218. enumerable: true,
  91219. configurable: true
  91220. });
  91221. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  91222. /**
  91223. * Gets wether the vignette effect is enabled.
  91224. */
  91225. get: function () {
  91226. return this.imageProcessingConfiguration.vignetteEnabled;
  91227. },
  91228. /**
  91229. * Sets wether the vignette effect is enabled.
  91230. */
  91231. set: function (value) {
  91232. this.imageProcessingConfiguration.vignetteEnabled = value;
  91233. },
  91234. enumerable: true,
  91235. configurable: true
  91236. });
  91237. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  91238. /**
  91239. * Gets wether the input of the processing is in Gamma or Linear Space.
  91240. */
  91241. get: function () {
  91242. return this._fromLinearSpace;
  91243. },
  91244. /**
  91245. * Sets wether the input of the processing is in Gamma or Linear Space.
  91246. */
  91247. set: function (value) {
  91248. if (this._fromLinearSpace === value) {
  91249. return;
  91250. }
  91251. this._fromLinearSpace = value;
  91252. this._updateParameters();
  91253. },
  91254. enumerable: true,
  91255. configurable: true
  91256. });
  91257. /**
  91258. * "ImageProcessingPostProcess"
  91259. * @returns "ImageProcessingPostProcess"
  91260. */
  91261. ImageProcessingPostProcess.prototype.getClassName = function () {
  91262. return "ImageProcessingPostProcess";
  91263. };
  91264. ImageProcessingPostProcess.prototype._updateParameters = function () {
  91265. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  91266. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  91267. var defines = "";
  91268. for (var define in this._defines) {
  91269. if (this._defines[define]) {
  91270. defines += "#define " + define + ";\r\n";
  91271. }
  91272. }
  91273. var samplers = ["textureSampler"];
  91274. var uniforms = ["scale"];
  91275. if (BABYLON.ImageProcessingConfiguration) {
  91276. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  91277. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  91278. }
  91279. this.updateEffect(defines, uniforms, samplers);
  91280. };
  91281. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  91282. _super.prototype.dispose.call(this, camera);
  91283. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91284. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91285. }
  91286. if (this._imageProcessingConfiguration) {
  91287. this.imageProcessingConfiguration.applyByPostProcess = false;
  91288. }
  91289. };
  91290. __decorate([
  91291. BABYLON.serialize()
  91292. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  91293. return ImageProcessingPostProcess;
  91294. }(BABYLON.PostProcess));
  91295. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  91296. })(BABYLON || (BABYLON = {}));
  91297. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  91298. var BABYLON;
  91299. (function (BABYLON) {
  91300. /**
  91301. * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.
  91302. * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.
  91303. * As an example, all you have to do is to create the post-process:
  91304. * var mb = new BABYLON.MotionBlurPostProcess(
  91305. * 'mb', // The name of the effect.
  91306. * scene, // The scene containing the objects to blur according to their velocity.
  91307. * 1.0, // The required width/height ratio to downsize to before computing the render pass.
  91308. * camera // The camera to apply the render pass to.
  91309. * );
  91310. * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.
  91311. */
  91312. var MotionBlurPostProcess = /** @class */ (function (_super) {
  91313. __extends(MotionBlurPostProcess, _super);
  91314. /**
  91315. * Creates a new instance MotionBlurPostProcess
  91316. * @param name The name of the effect.
  91317. * @param scene The scene containing the objects to blur according to their velocity.
  91318. * @param options The required width/height ratio to downsize to before computing the render pass.
  91319. * @param camera The camera to apply the render pass to.
  91320. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91321. * @param engine The engine which the post process will be applied. (default: current engine)
  91322. * @param reusable If the post process can be reused on the same frame. (default: false)
  91323. * @param textureType Type of textures used when performing the post process. (default: 0)
  91324. * @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)
  91325. */
  91326. function MotionBlurPostProcess(name, scene, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  91327. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91328. if (blockCompilation === void 0) { blockCompilation = false; }
  91329. var _this = _super.call(this, name, "motionBlur", ["motionStrength", "motionScale", "screenSize"], ["velocitySampler"], options, camera, samplingMode, engine, reusable, "#define SAMPLES 64.0", textureType, undefined, null, blockCompilation) || this;
  91330. /**
  91331. * Defines how much the image is blurred by the movement. Default value is equal to 1
  91332. */
  91333. _this.motionStrength = 1;
  91334. _this._motionBlurSamples = 32;
  91335. _this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  91336. if (_this._geometryBufferRenderer) {
  91337. if (!_this._geometryBufferRenderer.isSupported) {
  91338. BABYLON.Tools.Warn("Multiple Render Target support needed to compute object based motion blur");
  91339. _this.dispose();
  91340. return _this;
  91341. }
  91342. _this._geometryBufferRenderer.enableVelocity = true;
  91343. }
  91344. _this.onApply = function (effect) {
  91345. effect.setVector2("screenSize", new BABYLON.Vector2(_this.width, _this.height));
  91346. effect.setFloat("motionScale", scene.getAnimationRatio());
  91347. effect.setFloat("motionStrength", _this.motionStrength);
  91348. if (_this._geometryBufferRenderer) {
  91349. var velocityIndex = _this._geometryBufferRenderer.getTextureIndex(BABYLON.GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
  91350. effect.setTexture("velocitySampler", _this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
  91351. }
  91352. };
  91353. return _this;
  91354. }
  91355. Object.defineProperty(MotionBlurPostProcess.prototype, "motionBlurSamples", {
  91356. /**
  91357. * Gets the number of iterations are used for motion blur quality. Default value is equal to 32
  91358. */
  91359. get: function () {
  91360. return this._motionBlurSamples;
  91361. },
  91362. /**
  91363. * Sets the number of iterations to be used for motion blur quality
  91364. */
  91365. set: function (samples) {
  91366. this._motionBlurSamples = samples;
  91367. this.updateEffect("#define SAMPLES " + samples.toFixed(1));
  91368. },
  91369. enumerable: true,
  91370. configurable: true
  91371. });
  91372. /**
  91373. * Disposes the post process.
  91374. * @param camera The camera to dispose the post process on.
  91375. */
  91376. MotionBlurPostProcess.prototype.dispose = function (camera) {
  91377. if (this._geometryBufferRenderer) {
  91378. // Clear previous transformation matrices dictionary used to compute objects velocities
  91379. this._geometryBufferRenderer._previousTransformationMatrices = {};
  91380. }
  91381. _super.prototype.dispose.call(this, camera);
  91382. };
  91383. return MotionBlurPostProcess;
  91384. }(BABYLON.PostProcess));
  91385. BABYLON.MotionBlurPostProcess = MotionBlurPostProcess;
  91386. })(BABYLON || (BABYLON = {}));
  91387. //# sourceMappingURL=babylon.motionBlurPostProcess.js.map
  91388. var BABYLON;
  91389. (function (BABYLON) {
  91390. /**
  91391. * Class used to store bone information
  91392. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91393. */
  91394. var Bone = /** @class */ (function (_super) {
  91395. __extends(Bone, _super);
  91396. /**
  91397. * Create a new bone
  91398. * @param name defines the bone name
  91399. * @param skeleton defines the parent skeleton
  91400. * @param parentBone defines the parent (can be null if the bone is the root)
  91401. * @param localMatrix defines the local matrix
  91402. * @param restPose defines the rest pose matrix
  91403. * @param baseMatrix defines the base matrix
  91404. * @param index defines index of the bone in the hiearchy
  91405. */
  91406. function Bone(
  91407. /**
  91408. * defines the bone name
  91409. */
  91410. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  91411. if (parentBone === void 0) { parentBone = null; }
  91412. if (localMatrix === void 0) { localMatrix = null; }
  91413. if (restPose === void 0) { restPose = null; }
  91414. if (baseMatrix === void 0) { baseMatrix = null; }
  91415. if (index === void 0) { index = null; }
  91416. var _this = _super.call(this, name, skeleton.getScene()) || this;
  91417. _this.name = name;
  91418. /**
  91419. * Gets the list of child bones
  91420. */
  91421. _this.children = new Array();
  91422. /** Gets the animations associated with this bone */
  91423. _this.animations = new Array();
  91424. /**
  91425. * @hidden Internal only
  91426. * Set this value to map this bone to a different index in the transform matrices
  91427. * Set this value to -1 to exclude the bone from the transform matrices
  91428. */
  91429. _this._index = null;
  91430. _this._absoluteTransform = new BABYLON.Matrix();
  91431. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  91432. _this._scalingDeterminant = 1;
  91433. _this._worldTransform = new BABYLON.Matrix();
  91434. _this._needToDecompose = true;
  91435. _this._needToCompose = false;
  91436. _this._skeleton = skeleton;
  91437. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  91438. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  91439. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  91440. _this._index = index;
  91441. skeleton.bones.push(_this);
  91442. _this.setParent(parentBone, false);
  91443. if (baseMatrix || localMatrix) {
  91444. _this._updateDifferenceMatrix();
  91445. }
  91446. return _this;
  91447. }
  91448. Object.defineProperty(Bone.prototype, "_matrix", {
  91449. /** @hidden */
  91450. get: function () {
  91451. this._compose();
  91452. return this._localMatrix;
  91453. },
  91454. /** @hidden */
  91455. set: function (value) {
  91456. this._localMatrix.copyFrom(value);
  91457. this._needToDecompose = true;
  91458. },
  91459. enumerable: true,
  91460. configurable: true
  91461. });
  91462. // Members
  91463. /**
  91464. * Gets the parent skeleton
  91465. * @returns a skeleton
  91466. */
  91467. Bone.prototype.getSkeleton = function () {
  91468. return this._skeleton;
  91469. };
  91470. /**
  91471. * Gets parent bone
  91472. * @returns a bone or null if the bone is the root of the bone hierarchy
  91473. */
  91474. Bone.prototype.getParent = function () {
  91475. return this._parent;
  91476. };
  91477. /**
  91478. * Sets the parent bone
  91479. * @param parent defines the parent (can be null if the bone is the root)
  91480. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91481. */
  91482. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  91483. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91484. if (this._parent === parent) {
  91485. return;
  91486. }
  91487. if (this._parent) {
  91488. var index = this._parent.children.indexOf(this);
  91489. if (index !== -1) {
  91490. this._parent.children.splice(index, 1);
  91491. }
  91492. }
  91493. this._parent = parent;
  91494. if (this._parent) {
  91495. this._parent.children.push(this);
  91496. }
  91497. if (updateDifferenceMatrix) {
  91498. this._updateDifferenceMatrix();
  91499. }
  91500. this.markAsDirty();
  91501. };
  91502. /**
  91503. * Gets the local matrix
  91504. * @returns a matrix
  91505. */
  91506. Bone.prototype.getLocalMatrix = function () {
  91507. this._compose();
  91508. return this._localMatrix;
  91509. };
  91510. /**
  91511. * Gets the base matrix (initial matrix which remains unchanged)
  91512. * @returns a matrix
  91513. */
  91514. Bone.prototype.getBaseMatrix = function () {
  91515. return this._baseMatrix;
  91516. };
  91517. /**
  91518. * Gets the rest pose matrix
  91519. * @returns a matrix
  91520. */
  91521. Bone.prototype.getRestPose = function () {
  91522. return this._restPose;
  91523. };
  91524. /**
  91525. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  91526. */
  91527. Bone.prototype.getWorldMatrix = function () {
  91528. return this._worldTransform;
  91529. };
  91530. /**
  91531. * Sets the local matrix to rest pose matrix
  91532. */
  91533. Bone.prototype.returnToRest = function () {
  91534. this.updateMatrix(this._restPose.clone());
  91535. };
  91536. /**
  91537. * Gets the inverse of the absolute transform matrix.
  91538. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  91539. * @returns a matrix
  91540. */
  91541. Bone.prototype.getInvertedAbsoluteTransform = function () {
  91542. return this._invertedAbsoluteTransform;
  91543. };
  91544. /**
  91545. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  91546. * @returns a matrix
  91547. */
  91548. Bone.prototype.getAbsoluteTransform = function () {
  91549. return this._absoluteTransform;
  91550. };
  91551. Object.defineProperty(Bone.prototype, "position", {
  91552. // Properties (matches AbstractMesh properties)
  91553. /** Gets or sets current position (in local space) */
  91554. get: function () {
  91555. this._decompose();
  91556. return this._localPosition;
  91557. },
  91558. set: function (newPosition) {
  91559. this._decompose();
  91560. this._localPosition.copyFrom(newPosition);
  91561. this._markAsDirtyAndCompose();
  91562. },
  91563. enumerable: true,
  91564. configurable: true
  91565. });
  91566. Object.defineProperty(Bone.prototype, "rotation", {
  91567. /** Gets or sets current rotation (in local space) */
  91568. get: function () {
  91569. return this.getRotation();
  91570. },
  91571. set: function (newRotation) {
  91572. this.setRotation(newRotation);
  91573. },
  91574. enumerable: true,
  91575. configurable: true
  91576. });
  91577. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  91578. /** Gets or sets current rotation quaternion (in local space) */
  91579. get: function () {
  91580. this._decompose();
  91581. return this._localRotation;
  91582. },
  91583. set: function (newRotation) {
  91584. this.setRotationQuaternion(newRotation);
  91585. },
  91586. enumerable: true,
  91587. configurable: true
  91588. });
  91589. Object.defineProperty(Bone.prototype, "scaling", {
  91590. /** Gets or sets current scaling (in local space) */
  91591. get: function () {
  91592. return this.getScale();
  91593. },
  91594. set: function (newScaling) {
  91595. this.setScale(newScaling);
  91596. },
  91597. enumerable: true,
  91598. configurable: true
  91599. });
  91600. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  91601. /**
  91602. * Gets the animation properties override
  91603. */
  91604. get: function () {
  91605. return this._skeleton.animationPropertiesOverride;
  91606. },
  91607. enumerable: true,
  91608. configurable: true
  91609. });
  91610. // Methods
  91611. Bone.prototype._decompose = function () {
  91612. if (!this._needToDecompose) {
  91613. return;
  91614. }
  91615. this._needToDecompose = false;
  91616. if (!this._localScaling) {
  91617. this._localScaling = BABYLON.Vector3.Zero();
  91618. this._localRotation = BABYLON.Quaternion.Zero();
  91619. this._localPosition = BABYLON.Vector3.Zero();
  91620. }
  91621. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  91622. };
  91623. Bone.prototype._compose = function () {
  91624. if (!this._needToCompose) {
  91625. return;
  91626. }
  91627. this._needToCompose = false;
  91628. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  91629. };
  91630. /**
  91631. * Update the base and local matrices
  91632. * @param matrix defines the new base or local matrix
  91633. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91634. * @param updateLocalMatrix defines if the local matrix should be updated
  91635. */
  91636. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  91637. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91638. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  91639. this._baseMatrix.copyFrom(matrix);
  91640. if (updateDifferenceMatrix) {
  91641. this._updateDifferenceMatrix();
  91642. }
  91643. if (updateLocalMatrix) {
  91644. this._localMatrix.copyFrom(matrix);
  91645. this._markAsDirtyAndDecompose();
  91646. }
  91647. else {
  91648. this.markAsDirty();
  91649. }
  91650. };
  91651. /** @hidden */
  91652. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  91653. if (updateChildren === void 0) { updateChildren = true; }
  91654. if (!rootMatrix) {
  91655. rootMatrix = this._baseMatrix;
  91656. }
  91657. if (this._parent) {
  91658. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  91659. }
  91660. else {
  91661. this._absoluteTransform.copyFrom(rootMatrix);
  91662. }
  91663. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  91664. if (updateChildren) {
  91665. for (var index = 0; index < this.children.length; index++) {
  91666. this.children[index]._updateDifferenceMatrix();
  91667. }
  91668. }
  91669. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  91670. };
  91671. /**
  91672. * Flag the bone as dirty (Forcing it to update everything)
  91673. */
  91674. Bone.prototype.markAsDirty = function () {
  91675. this._currentRenderId++;
  91676. this._childRenderId++;
  91677. this._skeleton._markAsDirty();
  91678. };
  91679. Bone.prototype._markAsDirtyAndCompose = function () {
  91680. this.markAsDirty();
  91681. this._needToCompose = true;
  91682. };
  91683. Bone.prototype._markAsDirtyAndDecompose = function () {
  91684. this.markAsDirty();
  91685. this._needToDecompose = true;
  91686. };
  91687. /**
  91688. * Copy an animation range from another bone
  91689. * @param source defines the source bone
  91690. * @param rangeName defines the range name to copy
  91691. * @param frameOffset defines the frame offset
  91692. * @param rescaleAsRequired defines if rescaling must be applied if required
  91693. * @param skelDimensionsRatio defines the scaling ratio
  91694. * @returns true if operation was successful
  91695. */
  91696. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  91697. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91698. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  91699. // all animation may be coming from a library skeleton, so may need to create animation
  91700. if (this.animations.length === 0) {
  91701. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  91702. this.animations[0].setKeys([]);
  91703. }
  91704. // get animation info / verify there is such a range from the source bone
  91705. var sourceRange = source.animations[0].getRange(rangeName);
  91706. if (!sourceRange) {
  91707. return false;
  91708. }
  91709. var from = sourceRange.from;
  91710. var to = sourceRange.to;
  91711. var sourceKeys = source.animations[0].getKeys();
  91712. // rescaling prep
  91713. var sourceBoneLength = source.length;
  91714. var sourceParent = source.getParent();
  91715. var parent = this.getParent();
  91716. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  91717. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  91718. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  91719. var destKeys = this.animations[0].getKeys();
  91720. // loop vars declaration
  91721. var orig;
  91722. var origTranslation;
  91723. var mat;
  91724. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  91725. orig = sourceKeys[key];
  91726. if (orig.frame >= from && orig.frame <= to) {
  91727. if (rescaleAsRequired) {
  91728. mat = orig.value.clone();
  91729. // scale based on parent ratio, when bone has parent
  91730. if (parentScalingReqd) {
  91731. origTranslation = mat.getTranslation();
  91732. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  91733. // scale based on skeleton dimension ratio when root bone, and value is passed
  91734. }
  91735. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  91736. origTranslation = mat.getTranslation();
  91737. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  91738. // use original when root bone, and no data for skelDimensionsRatio
  91739. }
  91740. else {
  91741. mat = orig.value;
  91742. }
  91743. }
  91744. else {
  91745. mat = orig.value;
  91746. }
  91747. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  91748. }
  91749. }
  91750. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  91751. return true;
  91752. };
  91753. /**
  91754. * Translate the bone in local or world space
  91755. * @param vec The amount to translate the bone
  91756. * @param space The space that the translation is in
  91757. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91758. */
  91759. Bone.prototype.translate = function (vec, space, mesh) {
  91760. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91761. var lm = this.getLocalMatrix();
  91762. if (space == BABYLON.Space.LOCAL) {
  91763. lm.m[12] += vec.x;
  91764. lm.m[13] += vec.y;
  91765. lm.m[14] += vec.z;
  91766. }
  91767. else {
  91768. var wm = null;
  91769. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91770. if (mesh) {
  91771. wm = mesh.getWorldMatrix();
  91772. }
  91773. this._skeleton.computeAbsoluteTransforms();
  91774. var tmat = Bone._tmpMats[0];
  91775. var tvec = Bone._tmpVecs[0];
  91776. if (this._parent) {
  91777. if (mesh && wm) {
  91778. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91779. tmat.multiplyToRef(wm, tmat);
  91780. }
  91781. else {
  91782. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91783. }
  91784. }
  91785. tmat.m[12] = 0;
  91786. tmat.m[13] = 0;
  91787. tmat.m[14] = 0;
  91788. tmat.invert();
  91789. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  91790. lm.m[12] += tvec.x;
  91791. lm.m[13] += tvec.y;
  91792. lm.m[14] += tvec.z;
  91793. }
  91794. this._markAsDirtyAndDecompose();
  91795. };
  91796. /**
  91797. * Set the postion of the bone in local or world space
  91798. * @param position The position to set the bone
  91799. * @param space The space that the position is in
  91800. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91801. */
  91802. Bone.prototype.setPosition = function (position, space, mesh) {
  91803. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91804. var lm = this.getLocalMatrix();
  91805. if (space == BABYLON.Space.LOCAL) {
  91806. lm.m[12] = position.x;
  91807. lm.m[13] = position.y;
  91808. lm.m[14] = position.z;
  91809. }
  91810. else {
  91811. var wm = null;
  91812. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91813. if (mesh) {
  91814. wm = mesh.getWorldMatrix();
  91815. }
  91816. this._skeleton.computeAbsoluteTransforms();
  91817. var tmat = Bone._tmpMats[0];
  91818. var vec = Bone._tmpVecs[0];
  91819. if (this._parent) {
  91820. if (mesh && wm) {
  91821. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91822. tmat.multiplyToRef(wm, tmat);
  91823. }
  91824. else {
  91825. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91826. }
  91827. }
  91828. tmat.invert();
  91829. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  91830. lm.m[12] = vec.x;
  91831. lm.m[13] = vec.y;
  91832. lm.m[14] = vec.z;
  91833. }
  91834. this._markAsDirtyAndDecompose();
  91835. };
  91836. /**
  91837. * Set the absolute position of the bone (world space)
  91838. * @param position The position to set the bone
  91839. * @param mesh The mesh that this bone is attached to
  91840. */
  91841. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  91842. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  91843. };
  91844. /**
  91845. * Scale the bone on the x, y and z axes (in local space)
  91846. * @param x The amount to scale the bone on the x axis
  91847. * @param y The amount to scale the bone on the y axis
  91848. * @param z The amount to scale the bone on the z axis
  91849. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  91850. */
  91851. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  91852. if (scaleChildren === void 0) { scaleChildren = false; }
  91853. var locMat = this.getLocalMatrix();
  91854. // Apply new scaling on top of current local matrix
  91855. var scaleMat = Bone._tmpMats[0];
  91856. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  91857. scaleMat.multiplyToRef(locMat, locMat);
  91858. // Invert scaling matrix and apply the inverse to all children
  91859. scaleMat.invert();
  91860. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  91861. var child = _a[_i];
  91862. var cm = child.getLocalMatrix();
  91863. cm.multiplyToRef(scaleMat, cm);
  91864. cm.m[12] *= x;
  91865. cm.m[13] *= y;
  91866. cm.m[14] *= z;
  91867. child._markAsDirtyAndDecompose();
  91868. }
  91869. this._markAsDirtyAndDecompose();
  91870. if (scaleChildren) {
  91871. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  91872. var child = _c[_b];
  91873. child.scale(x, y, z, scaleChildren);
  91874. }
  91875. }
  91876. };
  91877. /**
  91878. * Set the bone scaling in local space
  91879. * @param scale defines the scaling vector
  91880. */
  91881. Bone.prototype.setScale = function (scale) {
  91882. this._decompose();
  91883. this._localScaling.copyFrom(scale);
  91884. this._markAsDirtyAndCompose();
  91885. };
  91886. /**
  91887. * Gets the current scaling in local space
  91888. * @returns the current scaling vector
  91889. */
  91890. Bone.prototype.getScale = function () {
  91891. this._decompose();
  91892. return this._localScaling;
  91893. };
  91894. /**
  91895. * Gets the current scaling in local space and stores it in a target vector
  91896. * @param result defines the target vector
  91897. */
  91898. Bone.prototype.getScaleToRef = function (result) {
  91899. this._decompose();
  91900. result.copyFrom(this._localScaling);
  91901. };
  91902. /**
  91903. * Set the yaw, pitch, and roll of the bone in local or world space
  91904. * @param yaw The rotation of the bone on the y axis
  91905. * @param pitch The rotation of the bone on the x axis
  91906. * @param roll The rotation of the bone on the z axis
  91907. * @param space The space that the axes of rotation are in
  91908. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91909. */
  91910. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  91911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91912. if (space === BABYLON.Space.LOCAL) {
  91913. var quat = Bone._tmpQuat;
  91914. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  91915. this.setRotationQuaternion(quat, space, mesh);
  91916. return;
  91917. }
  91918. var rotMatInv = Bone._tmpMats[0];
  91919. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91920. return;
  91921. }
  91922. var rotMat = Bone._tmpMats[1];
  91923. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  91924. rotMatInv.multiplyToRef(rotMat, rotMat);
  91925. this._rotateWithMatrix(rotMat, space, mesh);
  91926. };
  91927. /**
  91928. * Add a rotation to the bone on an axis in local or world space
  91929. * @param axis The axis to rotate the bone on
  91930. * @param amount The amount to rotate the bone
  91931. * @param space The space that the axis is in
  91932. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91933. */
  91934. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  91935. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91936. var rmat = Bone._tmpMats[0];
  91937. rmat.m[12] = 0;
  91938. rmat.m[13] = 0;
  91939. rmat.m[14] = 0;
  91940. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  91941. this._rotateWithMatrix(rmat, space, mesh);
  91942. };
  91943. /**
  91944. * Set the rotation of the bone to a particular axis angle in local or world space
  91945. * @param axis The axis to rotate the bone on
  91946. * @param angle The angle that the bone should be rotated to
  91947. * @param space The space that the axis is in
  91948. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91949. */
  91950. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  91951. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91952. if (space === BABYLON.Space.LOCAL) {
  91953. var quat = Bone._tmpQuat;
  91954. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  91955. this.setRotationQuaternion(quat, space, mesh);
  91956. return;
  91957. }
  91958. var rotMatInv = Bone._tmpMats[0];
  91959. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91960. return;
  91961. }
  91962. var rotMat = Bone._tmpMats[1];
  91963. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  91964. rotMatInv.multiplyToRef(rotMat, rotMat);
  91965. this._rotateWithMatrix(rotMat, space, mesh);
  91966. };
  91967. /**
  91968. * Set the euler rotation of the bone in local of world space
  91969. * @param rotation The euler rotation that the bone should be set to
  91970. * @param space The space that the rotation is in
  91971. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91972. */
  91973. Bone.prototype.setRotation = function (rotation, space, mesh) {
  91974. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91975. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  91976. };
  91977. /**
  91978. * Set the quaternion rotation of the bone in local of world space
  91979. * @param quat The quaternion rotation that the bone should be set to
  91980. * @param space The space that the rotation is in
  91981. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91982. */
  91983. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  91984. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91985. if (space === BABYLON.Space.LOCAL) {
  91986. this._decompose();
  91987. this._localRotation.copyFrom(quat);
  91988. this._markAsDirtyAndCompose();
  91989. return;
  91990. }
  91991. var rotMatInv = Bone._tmpMats[0];
  91992. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91993. return;
  91994. }
  91995. var rotMat = Bone._tmpMats[1];
  91996. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  91997. rotMatInv.multiplyToRef(rotMat, rotMat);
  91998. this._rotateWithMatrix(rotMat, space, mesh);
  91999. };
  92000. /**
  92001. * Set the rotation matrix of the bone in local of world space
  92002. * @param rotMat The rotation matrix that the bone should be set to
  92003. * @param space The space that the rotation is in
  92004. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92005. */
  92006. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  92007. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92008. if (space === BABYLON.Space.LOCAL) {
  92009. var quat = Bone._tmpQuat;
  92010. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  92011. this.setRotationQuaternion(quat, space, mesh);
  92012. return;
  92013. }
  92014. var rotMatInv = Bone._tmpMats[0];
  92015. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92016. return;
  92017. }
  92018. var rotMat2 = Bone._tmpMats[1];
  92019. rotMat2.copyFrom(rotMat);
  92020. rotMatInv.multiplyToRef(rotMat, rotMat2);
  92021. this._rotateWithMatrix(rotMat2, space, mesh);
  92022. };
  92023. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  92024. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92025. var lmat = this.getLocalMatrix();
  92026. var lx = lmat.m[12];
  92027. var ly = lmat.m[13];
  92028. var lz = lmat.m[14];
  92029. var parent = this.getParent();
  92030. var parentScale = Bone._tmpMats[3];
  92031. var parentScaleInv = Bone._tmpMats[4];
  92032. if (parent && space == BABYLON.Space.WORLD) {
  92033. if (mesh) {
  92034. parentScale.copyFrom(mesh.getWorldMatrix());
  92035. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  92036. }
  92037. else {
  92038. parentScale.copyFrom(parent.getAbsoluteTransform());
  92039. }
  92040. parentScaleInv.copyFrom(parentScale);
  92041. parentScaleInv.invert();
  92042. lmat.multiplyToRef(parentScale, lmat);
  92043. lmat.multiplyToRef(rmat, lmat);
  92044. lmat.multiplyToRef(parentScaleInv, lmat);
  92045. }
  92046. else {
  92047. if (space == BABYLON.Space.WORLD && mesh) {
  92048. parentScale.copyFrom(mesh.getWorldMatrix());
  92049. parentScaleInv.copyFrom(parentScale);
  92050. parentScaleInv.invert();
  92051. lmat.multiplyToRef(parentScale, lmat);
  92052. lmat.multiplyToRef(rmat, lmat);
  92053. lmat.multiplyToRef(parentScaleInv, lmat);
  92054. }
  92055. else {
  92056. lmat.multiplyToRef(rmat, lmat);
  92057. }
  92058. }
  92059. lmat.m[12] = lx;
  92060. lmat.m[13] = ly;
  92061. lmat.m[14] = lz;
  92062. this.computeAbsoluteTransforms();
  92063. this._markAsDirtyAndDecompose();
  92064. };
  92065. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  92066. var scaleMatrix = Bone._tmpMats[2];
  92067. rotMatInv.copyFrom(this.getAbsoluteTransform());
  92068. if (mesh) {
  92069. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  92070. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  92071. }
  92072. rotMatInv.invert();
  92073. if (isNaN(rotMatInv.m[0])) {
  92074. // Matrix failed to invert.
  92075. // This can happen if scale is zero for example.
  92076. return false;
  92077. }
  92078. scaleMatrix.m[0] *= this._scalingDeterminant;
  92079. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  92080. return true;
  92081. };
  92082. /**
  92083. * Get the position of the bone in local or world space
  92084. * @param space The space that the returned position is in
  92085. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92086. * @returns The position of the bone
  92087. */
  92088. Bone.prototype.getPosition = function (space, mesh) {
  92089. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92090. if (mesh === void 0) { mesh = null; }
  92091. var pos = BABYLON.Vector3.Zero();
  92092. this.getPositionToRef(space, mesh, pos);
  92093. return pos;
  92094. };
  92095. /**
  92096. * Copy the position of the bone to a vector3 in local or world space
  92097. * @param space The space that the returned position is in
  92098. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92099. * @param result The vector3 to copy the position to
  92100. */
  92101. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  92102. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92103. if (space == BABYLON.Space.LOCAL) {
  92104. var lm = this.getLocalMatrix();
  92105. result.x = lm.m[12];
  92106. result.y = lm.m[13];
  92107. result.z = lm.m[14];
  92108. }
  92109. else {
  92110. var wm = null;
  92111. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92112. if (mesh) {
  92113. wm = mesh.getWorldMatrix();
  92114. }
  92115. this._skeleton.computeAbsoluteTransforms();
  92116. var tmat = Bone._tmpMats[0];
  92117. if (mesh && wm) {
  92118. tmat.copyFrom(this.getAbsoluteTransform());
  92119. tmat.multiplyToRef(wm, tmat);
  92120. }
  92121. else {
  92122. tmat = this.getAbsoluteTransform();
  92123. }
  92124. result.x = tmat.m[12];
  92125. result.y = tmat.m[13];
  92126. result.z = tmat.m[14];
  92127. }
  92128. };
  92129. /**
  92130. * Get the absolute position of the bone (world space)
  92131. * @param mesh The mesh that this bone is attached to
  92132. * @returns The absolute position of the bone
  92133. */
  92134. Bone.prototype.getAbsolutePosition = function (mesh) {
  92135. if (mesh === void 0) { mesh = null; }
  92136. var pos = BABYLON.Vector3.Zero();
  92137. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  92138. return pos;
  92139. };
  92140. /**
  92141. * Copy the absolute position of the bone (world space) to the result param
  92142. * @param mesh The mesh that this bone is attached to
  92143. * @param result The vector3 to copy the absolute position to
  92144. */
  92145. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  92146. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  92147. };
  92148. /**
  92149. * Compute the absolute transforms of this bone and its children
  92150. */
  92151. Bone.prototype.computeAbsoluteTransforms = function () {
  92152. this._compose();
  92153. if (this._parent) {
  92154. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92155. }
  92156. else {
  92157. this._absoluteTransform.copyFrom(this._localMatrix);
  92158. var poseMatrix = this._skeleton.getPoseMatrix();
  92159. if (poseMatrix) {
  92160. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  92161. }
  92162. }
  92163. var children = this.children;
  92164. var len = children.length;
  92165. for (var i = 0; i < len; i++) {
  92166. children[i].computeAbsoluteTransforms();
  92167. }
  92168. };
  92169. /**
  92170. * Get the world direction from an axis that is in the local space of the bone
  92171. * @param localAxis The local direction that is used to compute the world direction
  92172. * @param mesh The mesh that this bone is attached to
  92173. * @returns The world direction
  92174. */
  92175. Bone.prototype.getDirection = function (localAxis, mesh) {
  92176. if (mesh === void 0) { mesh = null; }
  92177. var result = BABYLON.Vector3.Zero();
  92178. this.getDirectionToRef(localAxis, mesh, result);
  92179. return result;
  92180. };
  92181. /**
  92182. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  92183. * @param localAxis The local direction that is used to compute the world direction
  92184. * @param mesh The mesh that this bone is attached to
  92185. * @param result The vector3 that the world direction will be copied to
  92186. */
  92187. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  92188. if (mesh === void 0) { mesh = null; }
  92189. var wm = null;
  92190. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92191. if (mesh) {
  92192. wm = mesh.getWorldMatrix();
  92193. }
  92194. this._skeleton.computeAbsoluteTransforms();
  92195. var mat = Bone._tmpMats[0];
  92196. mat.copyFrom(this.getAbsoluteTransform());
  92197. if (mesh && wm) {
  92198. mat.multiplyToRef(wm, mat);
  92199. }
  92200. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  92201. result.normalize();
  92202. };
  92203. /**
  92204. * Get the euler rotation of the bone in local or world space
  92205. * @param space The space that the rotation should be in
  92206. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92207. * @returns The euler rotation
  92208. */
  92209. Bone.prototype.getRotation = function (space, mesh) {
  92210. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92211. if (mesh === void 0) { mesh = null; }
  92212. var result = BABYLON.Vector3.Zero();
  92213. this.getRotationToRef(space, mesh, result);
  92214. return result;
  92215. };
  92216. /**
  92217. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  92218. * @param space The space that the rotation should be in
  92219. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92220. * @param result The vector3 that the rotation should be copied to
  92221. */
  92222. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  92223. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92224. if (mesh === void 0) { mesh = null; }
  92225. var quat = Bone._tmpQuat;
  92226. this.getRotationQuaternionToRef(space, mesh, quat);
  92227. quat.toEulerAnglesToRef(result);
  92228. };
  92229. /**
  92230. * Get the quaternion rotation of the bone in either local or world space
  92231. * @param space The space that the rotation should be in
  92232. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92233. * @returns The quaternion rotation
  92234. */
  92235. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  92236. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92237. if (mesh === void 0) { mesh = null; }
  92238. var result = BABYLON.Quaternion.Identity();
  92239. this.getRotationQuaternionToRef(space, mesh, result);
  92240. return result;
  92241. };
  92242. /**
  92243. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  92244. * @param space The space that the rotation should be in
  92245. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92246. * @param result The quaternion that the rotation should be copied to
  92247. */
  92248. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  92249. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92250. if (mesh === void 0) { mesh = null; }
  92251. if (space == BABYLON.Space.LOCAL) {
  92252. this._decompose();
  92253. result.copyFrom(this._localRotation);
  92254. }
  92255. else {
  92256. var mat = Bone._tmpMats[0];
  92257. var amat = this.getAbsoluteTransform();
  92258. if (mesh) {
  92259. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92260. }
  92261. else {
  92262. mat.copyFrom(amat);
  92263. }
  92264. mat.m[0] *= this._scalingDeterminant;
  92265. mat.m[1] *= this._scalingDeterminant;
  92266. mat.m[2] *= this._scalingDeterminant;
  92267. mat.decompose(undefined, result, undefined);
  92268. }
  92269. };
  92270. /**
  92271. * Get the rotation matrix of the bone in local or world space
  92272. * @param space The space that the rotation should be in
  92273. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92274. * @returns The rotation matrix
  92275. */
  92276. Bone.prototype.getRotationMatrix = function (space, mesh) {
  92277. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92278. var result = BABYLON.Matrix.Identity();
  92279. this.getRotationMatrixToRef(space, mesh, result);
  92280. return result;
  92281. };
  92282. /**
  92283. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  92284. * @param space The space that the rotation should be in
  92285. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92286. * @param result The quaternion that the rotation should be copied to
  92287. */
  92288. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  92289. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92290. if (space == BABYLON.Space.LOCAL) {
  92291. this.getLocalMatrix().getRotationMatrixToRef(result);
  92292. }
  92293. else {
  92294. var mat = Bone._tmpMats[0];
  92295. var amat = this.getAbsoluteTransform();
  92296. if (mesh) {
  92297. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92298. }
  92299. else {
  92300. mat.copyFrom(amat);
  92301. }
  92302. mat.m[0] *= this._scalingDeterminant;
  92303. mat.m[1] *= this._scalingDeterminant;
  92304. mat.m[2] *= this._scalingDeterminant;
  92305. mat.getRotationMatrixToRef(result);
  92306. }
  92307. };
  92308. /**
  92309. * Get the world position of a point that is in the local space of the bone
  92310. * @param position The local position
  92311. * @param mesh The mesh that this bone is attached to
  92312. * @returns The world position
  92313. */
  92314. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  92315. if (mesh === void 0) { mesh = null; }
  92316. var result = BABYLON.Vector3.Zero();
  92317. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  92318. return result;
  92319. };
  92320. /**
  92321. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  92322. * @param position The local position
  92323. * @param mesh The mesh that this bone is attached to
  92324. * @param result The vector3 that the world position should be copied to
  92325. */
  92326. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  92327. if (mesh === void 0) { mesh = null; }
  92328. var wm = null;
  92329. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92330. if (mesh) {
  92331. wm = mesh.getWorldMatrix();
  92332. }
  92333. this._skeleton.computeAbsoluteTransforms();
  92334. var tmat = Bone._tmpMats[0];
  92335. if (mesh && wm) {
  92336. tmat.copyFrom(this.getAbsoluteTransform());
  92337. tmat.multiplyToRef(wm, tmat);
  92338. }
  92339. else {
  92340. tmat = this.getAbsoluteTransform();
  92341. }
  92342. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92343. };
  92344. /**
  92345. * Get the local position of a point that is in world space
  92346. * @param position The world position
  92347. * @param mesh The mesh that this bone is attached to
  92348. * @returns The local position
  92349. */
  92350. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  92351. if (mesh === void 0) { mesh = null; }
  92352. var result = BABYLON.Vector3.Zero();
  92353. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  92354. return result;
  92355. };
  92356. /**
  92357. * Get the local position of a point that is in world space and copy it to the result param
  92358. * @param position The world position
  92359. * @param mesh The mesh that this bone is attached to
  92360. * @param result The vector3 that the local position should be copied to
  92361. */
  92362. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  92363. if (mesh === void 0) { mesh = null; }
  92364. var wm = null;
  92365. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92366. if (mesh) {
  92367. wm = mesh.getWorldMatrix();
  92368. }
  92369. this._skeleton.computeAbsoluteTransforms();
  92370. var tmat = Bone._tmpMats[0];
  92371. tmat.copyFrom(this.getAbsoluteTransform());
  92372. if (mesh && wm) {
  92373. tmat.multiplyToRef(wm, tmat);
  92374. }
  92375. tmat.invert();
  92376. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92377. };
  92378. Bone._tmpVecs = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  92379. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  92380. Bone._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92381. return Bone;
  92382. }(BABYLON.Node));
  92383. BABYLON.Bone = Bone;
  92384. })(BABYLON || (BABYLON = {}));
  92385. //# sourceMappingURL=babylon.bone.js.map
  92386. var BABYLON;
  92387. (function (BABYLON) {
  92388. /**
  92389. * Class used to apply inverse kinematics to bones
  92390. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  92391. */
  92392. var BoneIKController = /** @class */ (function () {
  92393. /**
  92394. * Creates a new BoneIKController
  92395. * @param mesh defines the mesh to control
  92396. * @param bone defines the bone to control
  92397. * @param options defines options to set up the controller
  92398. */
  92399. function BoneIKController(mesh, bone, options) {
  92400. /**
  92401. * Gets or sets the target position
  92402. */
  92403. this.targetPosition = BABYLON.Vector3.Zero();
  92404. /**
  92405. * Gets or sets the pole target position
  92406. */
  92407. this.poleTargetPosition = BABYLON.Vector3.Zero();
  92408. /**
  92409. * Gets or sets the pole target local offset
  92410. */
  92411. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  92412. /**
  92413. * Gets or sets the pole angle
  92414. */
  92415. this.poleAngle = 0;
  92416. /**
  92417. * 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)
  92418. */
  92419. this.slerpAmount = 1;
  92420. this._bone1Quat = BABYLON.Quaternion.Identity();
  92421. this._bone1Mat = BABYLON.Matrix.Identity();
  92422. this._bone2Ang = Math.PI;
  92423. this._maxAngle = Math.PI;
  92424. this._rightHandedSystem = false;
  92425. this._bendAxis = BABYLON.Vector3.Right();
  92426. this._slerping = false;
  92427. this._adjustRoll = 0;
  92428. this._bone2 = bone;
  92429. this._bone1 = bone.getParent();
  92430. if (!this._bone1) {
  92431. return;
  92432. }
  92433. this.mesh = mesh;
  92434. var bonePos = bone.getPosition();
  92435. if (bone.getAbsoluteTransform().determinant() > 0) {
  92436. this._rightHandedSystem = true;
  92437. this._bendAxis.x = 0;
  92438. this._bendAxis.y = 0;
  92439. this._bendAxis.z = -1;
  92440. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  92441. this._adjustRoll = Math.PI * .5;
  92442. this._bendAxis.z = 1;
  92443. }
  92444. }
  92445. if (this._bone1.length) {
  92446. var boneScale1 = this._bone1.getScale();
  92447. var boneScale2 = this._bone2.getScale();
  92448. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  92449. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  92450. }
  92451. else if (this._bone1.children[0]) {
  92452. mesh.computeWorldMatrix(true);
  92453. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  92454. var pos2 = this._bone2.getAbsolutePosition(mesh);
  92455. var pos3 = this._bone1.getAbsolutePosition(mesh);
  92456. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  92457. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  92458. }
  92459. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  92460. this.maxAngle = Math.PI;
  92461. if (options) {
  92462. if (options.targetMesh) {
  92463. this.targetMesh = options.targetMesh;
  92464. this.targetMesh.computeWorldMatrix(true);
  92465. }
  92466. if (options.poleTargetMesh) {
  92467. this.poleTargetMesh = options.poleTargetMesh;
  92468. this.poleTargetMesh.computeWorldMatrix(true);
  92469. }
  92470. else if (options.poleTargetBone) {
  92471. this.poleTargetBone = options.poleTargetBone;
  92472. }
  92473. else if (this._bone1.getParent()) {
  92474. this.poleTargetBone = this._bone1.getParent();
  92475. }
  92476. if (options.poleTargetLocalOffset) {
  92477. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  92478. }
  92479. if (options.poleAngle) {
  92480. this.poleAngle = options.poleAngle;
  92481. }
  92482. if (options.bendAxis) {
  92483. this._bendAxis.copyFrom(options.bendAxis);
  92484. }
  92485. if (options.maxAngle) {
  92486. this.maxAngle = options.maxAngle;
  92487. }
  92488. if (options.slerpAmount) {
  92489. this.slerpAmount = options.slerpAmount;
  92490. }
  92491. }
  92492. }
  92493. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  92494. /**
  92495. * Gets or sets maximum allowed angle
  92496. */
  92497. get: function () {
  92498. return this._maxAngle;
  92499. },
  92500. set: function (value) {
  92501. this._setMaxAngle(value);
  92502. },
  92503. enumerable: true,
  92504. configurable: true
  92505. });
  92506. BoneIKController.prototype._setMaxAngle = function (ang) {
  92507. if (ang < 0) {
  92508. ang = 0;
  92509. }
  92510. if (ang > Math.PI || ang == undefined) {
  92511. ang = Math.PI;
  92512. }
  92513. this._maxAngle = ang;
  92514. var a = this._bone1Length;
  92515. var b = this._bone2Length;
  92516. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  92517. };
  92518. /**
  92519. * Force the controller to update the bones
  92520. */
  92521. BoneIKController.prototype.update = function () {
  92522. var bone1 = this._bone1;
  92523. if (!bone1) {
  92524. return;
  92525. }
  92526. var target = this.targetPosition;
  92527. var poleTarget = this.poleTargetPosition;
  92528. var mat1 = BoneIKController._tmpMats[0];
  92529. var mat2 = BoneIKController._tmpMats[1];
  92530. if (this.targetMesh) {
  92531. target.copyFrom(this.targetMesh.getAbsolutePosition());
  92532. }
  92533. if (this.poleTargetBone) {
  92534. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  92535. }
  92536. else if (this.poleTargetMesh) {
  92537. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  92538. }
  92539. var bonePos = BoneIKController._tmpVecs[0];
  92540. var zaxis = BoneIKController._tmpVecs[1];
  92541. var xaxis = BoneIKController._tmpVecs[2];
  92542. var yaxis = BoneIKController._tmpVecs[3];
  92543. var upAxis = BoneIKController._tmpVecs[4];
  92544. var _tmpQuat = BoneIKController._tmpQuat;
  92545. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  92546. poleTarget.subtractToRef(bonePos, upAxis);
  92547. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  92548. upAxis.y = 1;
  92549. }
  92550. else {
  92551. upAxis.normalize();
  92552. }
  92553. target.subtractToRef(bonePos, yaxis);
  92554. yaxis.normalize();
  92555. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  92556. zaxis.normalize();
  92557. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  92558. xaxis.normalize();
  92559. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  92560. var a = this._bone1Length;
  92561. var b = this._bone2Length;
  92562. var c = BABYLON.Vector3.Distance(bonePos, target);
  92563. if (this._maxReach > 0) {
  92564. c = Math.min(this._maxReach, c);
  92565. }
  92566. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  92567. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  92568. if (acosa > 1) {
  92569. acosa = 1;
  92570. }
  92571. if (acosb > 1) {
  92572. acosb = 1;
  92573. }
  92574. if (acosa < -1) {
  92575. acosa = -1;
  92576. }
  92577. if (acosb < -1) {
  92578. acosb = -1;
  92579. }
  92580. var angA = Math.acos(acosa);
  92581. var angB = Math.acos(acosb);
  92582. var angC = -angA - angB;
  92583. if (this._rightHandedSystem) {
  92584. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  92585. mat2.multiplyToRef(mat1, mat1);
  92586. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  92587. mat2.multiplyToRef(mat1, mat1);
  92588. }
  92589. else {
  92590. var _tmpVec = BoneIKController._tmpVecs[5];
  92591. _tmpVec.copyFrom(this._bendAxis);
  92592. _tmpVec.x *= -1;
  92593. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  92594. mat2.multiplyToRef(mat1, mat1);
  92595. }
  92596. if (this.poleAngle) {
  92597. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  92598. mat1.multiplyToRef(mat2, mat1);
  92599. }
  92600. if (this._bone1) {
  92601. if (this.slerpAmount < 1) {
  92602. if (!this._slerping) {
  92603. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  92604. }
  92605. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  92606. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  92607. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  92608. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  92609. this._slerping = true;
  92610. }
  92611. else {
  92612. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  92613. this._bone1Mat.copyFrom(mat1);
  92614. this._slerping = false;
  92615. }
  92616. }
  92617. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  92618. this._bone2Ang = angC;
  92619. };
  92620. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  92621. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  92622. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  92623. return BoneIKController;
  92624. }());
  92625. BABYLON.BoneIKController = BoneIKController;
  92626. })(BABYLON || (BABYLON = {}));
  92627. //# sourceMappingURL=babylon.boneIKController.js.map
  92628. var BABYLON;
  92629. (function (BABYLON) {
  92630. /**
  92631. * Class used to make a bone look toward a point in space
  92632. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  92633. */
  92634. var BoneLookController = /** @class */ (function () {
  92635. /**
  92636. * Create a BoneLookController
  92637. * @param mesh the mesh that the bone belongs to
  92638. * @param bone the bone that will be looking to the target
  92639. * @param target the target Vector3 to look at
  92640. * @param settings optional settings:
  92641. * * maxYaw: the maximum angle the bone will yaw to
  92642. * * minYaw: the minimum angle the bone will yaw to
  92643. * * maxPitch: the maximum angle the bone will pitch to
  92644. * * minPitch: the minimum angle the bone will yaw to
  92645. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  92646. * * upAxis: the up axis of the coordinate system
  92647. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  92648. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  92649. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  92650. * * adjustYaw: used to make an adjustment to the yaw of the bone
  92651. * * adjustPitch: used to make an adjustment to the pitch of the bone
  92652. * * adjustRoll: used to make an adjustment to the roll of the bone
  92653. **/
  92654. function BoneLookController(mesh, bone, target, options) {
  92655. /**
  92656. * The up axis of the coordinate system that is used when the bone is rotated
  92657. */
  92658. this.upAxis = BABYLON.Vector3.Up();
  92659. /**
  92660. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  92661. */
  92662. this.upAxisSpace = BABYLON.Space.LOCAL;
  92663. /**
  92664. * Used to make an adjustment to the yaw of the bone
  92665. */
  92666. this.adjustYaw = 0;
  92667. /**
  92668. * Used to make an adjustment to the pitch of the bone
  92669. */
  92670. this.adjustPitch = 0;
  92671. /**
  92672. * Used to make an adjustment to the roll of the bone
  92673. */
  92674. this.adjustRoll = 0;
  92675. /**
  92676. * 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)
  92677. */
  92678. this.slerpAmount = 1;
  92679. this._boneQuat = BABYLON.Quaternion.Identity();
  92680. this._slerping = false;
  92681. this._firstFrameSkipped = false;
  92682. this._fowardAxis = BABYLON.Vector3.Forward();
  92683. this.mesh = mesh;
  92684. this.bone = bone;
  92685. this.target = target;
  92686. if (options) {
  92687. if (options.adjustYaw) {
  92688. this.adjustYaw = options.adjustYaw;
  92689. }
  92690. if (options.adjustPitch) {
  92691. this.adjustPitch = options.adjustPitch;
  92692. }
  92693. if (options.adjustRoll) {
  92694. this.adjustRoll = options.adjustRoll;
  92695. }
  92696. if (options.maxYaw != null) {
  92697. this.maxYaw = options.maxYaw;
  92698. }
  92699. else {
  92700. this.maxYaw = Math.PI;
  92701. }
  92702. if (options.minYaw != null) {
  92703. this.minYaw = options.minYaw;
  92704. }
  92705. else {
  92706. this.minYaw = -Math.PI;
  92707. }
  92708. if (options.maxPitch != null) {
  92709. this.maxPitch = options.maxPitch;
  92710. }
  92711. else {
  92712. this.maxPitch = Math.PI;
  92713. }
  92714. if (options.minPitch != null) {
  92715. this.minPitch = options.minPitch;
  92716. }
  92717. else {
  92718. this.minPitch = -Math.PI;
  92719. }
  92720. if (options.slerpAmount != null) {
  92721. this.slerpAmount = options.slerpAmount;
  92722. }
  92723. if (options.upAxis != null) {
  92724. this.upAxis = options.upAxis;
  92725. }
  92726. if (options.upAxisSpace != null) {
  92727. this.upAxisSpace = options.upAxisSpace;
  92728. }
  92729. if (options.yawAxis != null || options.pitchAxis != null) {
  92730. var newYawAxis = BABYLON.Axis.Y;
  92731. var newPitchAxis = BABYLON.Axis.X;
  92732. if (options.yawAxis != null) {
  92733. newYawAxis = options.yawAxis.clone();
  92734. newYawAxis.normalize();
  92735. }
  92736. if (options.pitchAxis != null) {
  92737. newPitchAxis = options.pitchAxis.clone();
  92738. newPitchAxis.normalize();
  92739. }
  92740. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  92741. this._transformYawPitch = BABYLON.Matrix.Identity();
  92742. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  92743. this._transformYawPitchInv = this._transformYawPitch.clone();
  92744. this._transformYawPitch.invert();
  92745. }
  92746. }
  92747. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  92748. this.upAxisSpace = BABYLON.Space.LOCAL;
  92749. }
  92750. }
  92751. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  92752. /**
  92753. * Gets or sets the minimum yaw angle that the bone can look to
  92754. */
  92755. get: function () {
  92756. return this._minYaw;
  92757. },
  92758. set: function (value) {
  92759. this._minYaw = value;
  92760. this._minYawSin = Math.sin(value);
  92761. this._minYawCos = Math.cos(value);
  92762. if (this._maxYaw != null) {
  92763. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92764. this._yawRange = this._maxYaw - this._minYaw;
  92765. }
  92766. },
  92767. enumerable: true,
  92768. configurable: true
  92769. });
  92770. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  92771. /**
  92772. * Gets or sets the maximum yaw angle that the bone can look to
  92773. */
  92774. get: function () {
  92775. return this._maxYaw;
  92776. },
  92777. set: function (value) {
  92778. this._maxYaw = value;
  92779. this._maxYawSin = Math.sin(value);
  92780. this._maxYawCos = Math.cos(value);
  92781. if (this._minYaw != null) {
  92782. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92783. this._yawRange = this._maxYaw - this._minYaw;
  92784. }
  92785. },
  92786. enumerable: true,
  92787. configurable: true
  92788. });
  92789. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  92790. /**
  92791. * Gets or sets the minimum pitch angle that the bone can look to
  92792. */
  92793. get: function () {
  92794. return this._minPitch;
  92795. },
  92796. set: function (value) {
  92797. this._minPitch = value;
  92798. this._minPitchTan = Math.tan(value);
  92799. },
  92800. enumerable: true,
  92801. configurable: true
  92802. });
  92803. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  92804. /**
  92805. * Gets or sets the maximum pitch angle that the bone can look to
  92806. */
  92807. get: function () {
  92808. return this._maxPitch;
  92809. },
  92810. set: function (value) {
  92811. this._maxPitch = value;
  92812. this._maxPitchTan = Math.tan(value);
  92813. },
  92814. enumerable: true,
  92815. configurable: true
  92816. });
  92817. /**
  92818. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  92819. */
  92820. BoneLookController.prototype.update = function () {
  92821. //skip the first frame when slerping so that the mesh rotation is correct
  92822. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  92823. this._firstFrameSkipped = true;
  92824. return;
  92825. }
  92826. var bone = this.bone;
  92827. var bonePos = BoneLookController._tmpVecs[0];
  92828. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  92829. var target = this.target;
  92830. var _tmpMat1 = BoneLookController._tmpMats[0];
  92831. var _tmpMat2 = BoneLookController._tmpMats[1];
  92832. var mesh = this.mesh;
  92833. var parentBone = bone.getParent();
  92834. var upAxis = BoneLookController._tmpVecs[1];
  92835. upAxis.copyFrom(this.upAxis);
  92836. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  92837. if (this._transformYawPitch) {
  92838. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  92839. }
  92840. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  92841. }
  92842. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  92843. mesh.getDirectionToRef(upAxis, upAxis);
  92844. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  92845. upAxis.normalize();
  92846. }
  92847. }
  92848. var checkYaw = false;
  92849. var checkPitch = false;
  92850. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  92851. checkYaw = true;
  92852. }
  92853. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  92854. checkPitch = true;
  92855. }
  92856. if (checkYaw || checkPitch) {
  92857. var spaceMat = BoneLookController._tmpMats[2];
  92858. var spaceMatInv = BoneLookController._tmpMats[3];
  92859. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  92860. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  92861. }
  92862. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  92863. spaceMat.copyFrom(mesh.getWorldMatrix());
  92864. }
  92865. else {
  92866. var forwardAxis = BoneLookController._tmpVecs[2];
  92867. forwardAxis.copyFrom(this._fowardAxis);
  92868. if (this._transformYawPitch) {
  92869. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  92870. }
  92871. if (parentBone) {
  92872. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  92873. }
  92874. else {
  92875. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  92876. }
  92877. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  92878. rightAxis.normalize();
  92879. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  92880. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  92881. }
  92882. spaceMat.invertToRef(spaceMatInv);
  92883. var xzlen = null;
  92884. if (checkPitch) {
  92885. var localTarget = BoneLookController._tmpVecs[3];
  92886. target.subtractToRef(bonePos, localTarget);
  92887. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92888. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92889. var pitch = Math.atan2(localTarget.y, xzlen);
  92890. var newPitch = pitch;
  92891. if (pitch > this._maxPitch) {
  92892. localTarget.y = this._maxPitchTan * xzlen;
  92893. newPitch = this._maxPitch;
  92894. }
  92895. else if (pitch < this._minPitch) {
  92896. localTarget.y = this._minPitchTan * xzlen;
  92897. newPitch = this._minPitch;
  92898. }
  92899. if (pitch != newPitch) {
  92900. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92901. localTarget.addInPlace(bonePos);
  92902. target = localTarget;
  92903. }
  92904. }
  92905. if (checkYaw) {
  92906. var localTarget = BoneLookController._tmpVecs[4];
  92907. target.subtractToRef(bonePos, localTarget);
  92908. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92909. var yaw = Math.atan2(localTarget.x, localTarget.z);
  92910. var newYaw = yaw;
  92911. if (yaw > this._maxYaw || yaw < this._minYaw) {
  92912. if (xzlen == null) {
  92913. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92914. }
  92915. if (this._yawRange > Math.PI) {
  92916. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  92917. localTarget.z = this._maxYawCos * xzlen;
  92918. localTarget.x = this._maxYawSin * xzlen;
  92919. newYaw = this._maxYaw;
  92920. }
  92921. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  92922. localTarget.z = this._minYawCos * xzlen;
  92923. localTarget.x = this._minYawSin * xzlen;
  92924. newYaw = this._minYaw;
  92925. }
  92926. }
  92927. else {
  92928. if (yaw > this._maxYaw) {
  92929. localTarget.z = this._maxYawCos * xzlen;
  92930. localTarget.x = this._maxYawSin * xzlen;
  92931. newYaw = this._maxYaw;
  92932. }
  92933. else if (yaw < this._minYaw) {
  92934. localTarget.z = this._minYawCos * xzlen;
  92935. localTarget.x = this._minYawSin * xzlen;
  92936. newYaw = this._minYaw;
  92937. }
  92938. }
  92939. }
  92940. if (this._slerping && this._yawRange > Math.PI) {
  92941. //are we going to be crossing into the min/max region?
  92942. var boneFwd = BoneLookController._tmpVecs[8];
  92943. boneFwd.copyFrom(BABYLON.Axis.Z);
  92944. if (this._transformYawPitch) {
  92945. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  92946. }
  92947. var boneRotMat = BoneLookController._tmpMats[4];
  92948. this._boneQuat.toRotationMatrix(boneRotMat);
  92949. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  92950. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  92951. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  92952. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  92953. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  92954. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  92955. if (angBtwTar > angBtwMidYaw) {
  92956. if (xzlen == null) {
  92957. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92958. }
  92959. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  92960. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  92961. if (angBtwMin < angBtwMax) {
  92962. newYaw = boneYaw + Math.PI * .75;
  92963. localTarget.z = Math.cos(newYaw) * xzlen;
  92964. localTarget.x = Math.sin(newYaw) * xzlen;
  92965. }
  92966. else {
  92967. newYaw = boneYaw - Math.PI * .75;
  92968. localTarget.z = Math.cos(newYaw) * xzlen;
  92969. localTarget.x = Math.sin(newYaw) * xzlen;
  92970. }
  92971. }
  92972. }
  92973. if (yaw != newYaw) {
  92974. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92975. localTarget.addInPlace(bonePos);
  92976. target = localTarget;
  92977. }
  92978. }
  92979. }
  92980. var zaxis = BoneLookController._tmpVecs[5];
  92981. var xaxis = BoneLookController._tmpVecs[6];
  92982. var yaxis = BoneLookController._tmpVecs[7];
  92983. var _tmpQuat = BoneLookController._tmpQuat;
  92984. target.subtractToRef(bonePos, zaxis);
  92985. zaxis.normalize();
  92986. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  92987. xaxis.normalize();
  92988. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  92989. yaxis.normalize();
  92990. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  92991. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  92992. return;
  92993. }
  92994. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  92995. return;
  92996. }
  92997. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  92998. return;
  92999. }
  93000. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  93001. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  93002. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  93003. }
  93004. if (this.slerpAmount < 1) {
  93005. if (!this._slerping) {
  93006. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  93007. }
  93008. if (this._transformYawPitch) {
  93009. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  93010. }
  93011. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  93012. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  93013. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  93014. this._slerping = true;
  93015. }
  93016. else {
  93017. if (this._transformYawPitch) {
  93018. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  93019. }
  93020. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  93021. this._slerping = false;
  93022. }
  93023. };
  93024. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  93025. var angDiff = ang2 - ang1;
  93026. angDiff %= Math.PI * 2;
  93027. if (angDiff > Math.PI) {
  93028. angDiff -= Math.PI * 2;
  93029. }
  93030. else if (angDiff < -Math.PI) {
  93031. angDiff += Math.PI * 2;
  93032. }
  93033. return angDiff;
  93034. };
  93035. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  93036. ang1 %= (2 * Math.PI);
  93037. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  93038. ang2 %= (2 * Math.PI);
  93039. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  93040. var ab = 0;
  93041. if (ang1 < ang2) {
  93042. ab = ang2 - ang1;
  93043. }
  93044. else {
  93045. ab = ang1 - ang2;
  93046. }
  93047. if (ab > Math.PI) {
  93048. ab = Math.PI * 2 - ab;
  93049. }
  93050. return ab;
  93051. };
  93052. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  93053. ang %= (2 * Math.PI);
  93054. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  93055. ang1 %= (2 * Math.PI);
  93056. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  93057. ang2 %= (2 * Math.PI);
  93058. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  93059. if (ang1 < ang2) {
  93060. if (ang > ang1 && ang < ang2) {
  93061. return true;
  93062. }
  93063. }
  93064. else {
  93065. if (ang > ang2 && ang < ang1) {
  93066. return true;
  93067. }
  93068. }
  93069. return false;
  93070. };
  93071. BoneLookController._tmpVecs = BABYLON.Tools.BuildArray(10, BABYLON.Vector3.Zero);
  93072. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  93073. BoneLookController._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  93074. return BoneLookController;
  93075. }());
  93076. BABYLON.BoneLookController = BoneLookController;
  93077. })(BABYLON || (BABYLON = {}));
  93078. //# sourceMappingURL=babylon.boneLookController.js.map
  93079. var BABYLON;
  93080. (function (BABYLON) {
  93081. /**
  93082. * Class used to handle skinning animations
  93083. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  93084. */
  93085. var Skeleton = /** @class */ (function () {
  93086. /**
  93087. * Creates a new skeleton
  93088. * @param name defines the skeleton name
  93089. * @param id defines the skeleton Id
  93090. * @param scene defines the hosting scene
  93091. */
  93092. function Skeleton(
  93093. /** defines the skeleton name */
  93094. name,
  93095. /** defines the skeleton Id */
  93096. id, scene) {
  93097. this.name = name;
  93098. this.id = id;
  93099. /**
  93100. * Gets the list of child bones
  93101. */
  93102. this.bones = new Array();
  93103. /**
  93104. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  93105. */
  93106. this.needInitialSkinMatrix = false;
  93107. this._isDirty = true;
  93108. this._meshesWithPoseMatrix = new Array();
  93109. this._identity = BABYLON.Matrix.Identity();
  93110. this._ranges = {};
  93111. this._lastAbsoluteTransformsUpdateId = -1;
  93112. /**
  93113. * Specifies if the skeleton should be serialized
  93114. */
  93115. this.doNotSerialize = false;
  93116. this._animationPropertiesOverride = null;
  93117. // Events
  93118. /**
  93119. * An observable triggered before computing the skeleton's matrices
  93120. */
  93121. this.onBeforeComputeObservable = new BABYLON.Observable();
  93122. this.bones = [];
  93123. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93124. scene.skeletons.push(this);
  93125. //make sure it will recalculate the matrix next time prepare is called.
  93126. this._isDirty = true;
  93127. }
  93128. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  93129. /**
  93130. * Gets or sets the animation properties override
  93131. */
  93132. get: function () {
  93133. if (!this._animationPropertiesOverride) {
  93134. return this._scene.animationPropertiesOverride;
  93135. }
  93136. return this._animationPropertiesOverride;
  93137. },
  93138. set: function (value) {
  93139. this._animationPropertiesOverride = value;
  93140. },
  93141. enumerable: true,
  93142. configurable: true
  93143. });
  93144. // Members
  93145. /**
  93146. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  93147. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  93148. * @returns a Float32Array containing matrices data
  93149. */
  93150. Skeleton.prototype.getTransformMatrices = function (mesh) {
  93151. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  93152. return mesh._bonesTransformMatrices;
  93153. }
  93154. if (!this._transformMatrices) {
  93155. this.prepare();
  93156. }
  93157. return this._transformMatrices;
  93158. };
  93159. /**
  93160. * Gets the current hosting scene
  93161. * @returns a scene object
  93162. */
  93163. Skeleton.prototype.getScene = function () {
  93164. return this._scene;
  93165. };
  93166. // Methods
  93167. /**
  93168. * Gets a string representing the current skeleton data
  93169. * @param fullDetails defines a boolean indicating if we want a verbose version
  93170. * @returns a string representing the current skeleton data
  93171. */
  93172. Skeleton.prototype.toString = function (fullDetails) {
  93173. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  93174. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  93175. if (fullDetails) {
  93176. ret += ", Ranges: {";
  93177. var first = true;
  93178. for (var name_1 in this._ranges) {
  93179. if (first) {
  93180. ret += ", ";
  93181. first = false;
  93182. }
  93183. ret += name_1;
  93184. }
  93185. ret += "}";
  93186. }
  93187. return ret;
  93188. };
  93189. /**
  93190. * Get bone's index searching by name
  93191. * @param name defines bone's name to search for
  93192. * @return the indice of the bone. Returns -1 if not found
  93193. */
  93194. Skeleton.prototype.getBoneIndexByName = function (name) {
  93195. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  93196. if (this.bones[boneIndex].name === name) {
  93197. return boneIndex;
  93198. }
  93199. }
  93200. return -1;
  93201. };
  93202. /**
  93203. * Creater a new animation range
  93204. * @param name defines the name of the range
  93205. * @param from defines the start key
  93206. * @param to defines the end key
  93207. */
  93208. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  93209. // check name not already in use
  93210. if (!this._ranges[name]) {
  93211. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  93212. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93213. if (this.bones[i].animations[0]) {
  93214. this.bones[i].animations[0].createRange(name, from, to);
  93215. }
  93216. }
  93217. }
  93218. };
  93219. /**
  93220. * Delete a specific animation range
  93221. * @param name defines the name of the range
  93222. * @param deleteFrames defines if frames must be removed as well
  93223. */
  93224. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  93225. if (deleteFrames === void 0) { deleteFrames = true; }
  93226. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93227. if (this.bones[i].animations[0]) {
  93228. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  93229. }
  93230. }
  93231. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  93232. };
  93233. /**
  93234. * Gets a specific animation range
  93235. * @param name defines the name of the range to look for
  93236. * @returns the requested animation range or null if not found
  93237. */
  93238. Skeleton.prototype.getAnimationRange = function (name) {
  93239. return this._ranges[name];
  93240. };
  93241. /**
  93242. * Gets the list of all animation ranges defined on this skeleton
  93243. * @returns an array
  93244. */
  93245. Skeleton.prototype.getAnimationRanges = function () {
  93246. var animationRanges = [];
  93247. var name;
  93248. var i = 0;
  93249. for (name in this._ranges) {
  93250. animationRanges[i] = this._ranges[name];
  93251. i++;
  93252. }
  93253. return animationRanges;
  93254. };
  93255. /**
  93256. * Copy animation range from a source skeleton.
  93257. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  93258. * @param source defines the source skeleton
  93259. * @param name defines the name of the range to copy
  93260. * @param rescaleAsRequired defines if rescaling must be applied if required
  93261. * @returns true if operation was successful
  93262. */
  93263. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  93264. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  93265. if (this._ranges[name] || !source.getAnimationRange(name)) {
  93266. return false;
  93267. }
  93268. var ret = true;
  93269. var frameOffset = this._getHighestAnimationFrame() + 1;
  93270. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  93271. var boneDict = {};
  93272. var sourceBones = source.bones;
  93273. var nBones;
  93274. var i;
  93275. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  93276. boneDict[sourceBones[i].name] = sourceBones[i];
  93277. }
  93278. if (this.bones.length !== sourceBones.length) {
  93279. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  93280. ret = false;
  93281. }
  93282. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  93283. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  93284. var boneName = this.bones[i].name;
  93285. var sourceBone = boneDict[boneName];
  93286. if (sourceBone) {
  93287. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  93288. }
  93289. else {
  93290. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  93291. ret = false;
  93292. }
  93293. }
  93294. // do not call createAnimationRange(), since it also is done to bones, which was already done
  93295. var range = source.getAnimationRange(name);
  93296. if (range) {
  93297. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  93298. }
  93299. return ret;
  93300. };
  93301. /**
  93302. * Forces the skeleton to go to rest pose
  93303. */
  93304. Skeleton.prototype.returnToRest = function () {
  93305. for (var index = 0; index < this.bones.length; index++) {
  93306. this.bones[index].returnToRest();
  93307. }
  93308. };
  93309. Skeleton.prototype._getHighestAnimationFrame = function () {
  93310. var ret = 0;
  93311. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93312. if (this.bones[i].animations[0]) {
  93313. var highest = this.bones[i].animations[0].getHighestFrame();
  93314. if (ret < highest) {
  93315. ret = highest;
  93316. }
  93317. }
  93318. }
  93319. return ret;
  93320. };
  93321. /**
  93322. * Begin a specific animation range
  93323. * @param name defines the name of the range to start
  93324. * @param loop defines if looping must be turned on (false by default)
  93325. * @param speedRatio defines the speed ratio to apply (1 by default)
  93326. * @param onAnimationEnd defines a callback which will be called when animation will end
  93327. * @returns a new animatable
  93328. */
  93329. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  93330. var range = this.getAnimationRange(name);
  93331. if (!range) {
  93332. return null;
  93333. }
  93334. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  93335. };
  93336. /** @hidden */
  93337. Skeleton.prototype._markAsDirty = function () {
  93338. this._isDirty = true;
  93339. };
  93340. /** @hidden */
  93341. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  93342. this._meshesWithPoseMatrix.push(mesh);
  93343. };
  93344. /** @hidden */
  93345. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  93346. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  93347. if (index > -1) {
  93348. this._meshesWithPoseMatrix.splice(index, 1);
  93349. }
  93350. };
  93351. /** @hidden */
  93352. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  93353. this.onBeforeComputeObservable.notifyObservers(this);
  93354. for (var index = 0; index < this.bones.length; index++) {
  93355. var bone = this.bones[index];
  93356. var parentBone = bone.getParent();
  93357. if (parentBone) {
  93358. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  93359. }
  93360. else {
  93361. if (initialSkinMatrix) {
  93362. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  93363. }
  93364. else {
  93365. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  93366. }
  93367. }
  93368. if (bone._index !== -1) {
  93369. var mappedIndex = bone._index === null ? index : bone._index;
  93370. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  93371. }
  93372. }
  93373. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  93374. };
  93375. /**
  93376. * Build all resources required to render a skeleton
  93377. */
  93378. Skeleton.prototype.prepare = function () {
  93379. if (!this._isDirty) {
  93380. return;
  93381. }
  93382. if (this.needInitialSkinMatrix) {
  93383. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  93384. var mesh = this._meshesWithPoseMatrix[index];
  93385. var poseMatrix = mesh.getPoseMatrix();
  93386. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  93387. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93388. }
  93389. if (this._synchronizedWithMesh !== mesh) {
  93390. this._synchronizedWithMesh = mesh;
  93391. // Prepare bones
  93392. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  93393. var bone = this.bones[boneIndex];
  93394. if (!bone.getParent()) {
  93395. var matrix = bone.getBaseMatrix();
  93396. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  93397. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  93398. }
  93399. }
  93400. }
  93401. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  93402. }
  93403. }
  93404. else {
  93405. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  93406. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93407. }
  93408. this._computeTransformMatrices(this._transformMatrices, null);
  93409. }
  93410. this._isDirty = false;
  93411. this._scene._activeBones.addCount(this.bones.length, false);
  93412. };
  93413. /**
  93414. * Gets the list of animatables currently running for this skeleton
  93415. * @returns an array of animatables
  93416. */
  93417. Skeleton.prototype.getAnimatables = function () {
  93418. if (!this._animatables || this._animatables.length !== this.bones.length) {
  93419. this._animatables = [];
  93420. for (var index = 0; index < this.bones.length; index++) {
  93421. this._animatables.push(this.bones[index]);
  93422. }
  93423. }
  93424. return this._animatables;
  93425. };
  93426. /**
  93427. * Clone the current skeleton
  93428. * @param name defines the name of the new skeleton
  93429. * @param id defines the id of the enw skeleton
  93430. * @returns the new skeleton
  93431. */
  93432. Skeleton.prototype.clone = function (name, id) {
  93433. var result = new Skeleton(name, id || name, this._scene);
  93434. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93435. for (var index = 0; index < this.bones.length; index++) {
  93436. var source = this.bones[index];
  93437. var parentBone = null;
  93438. var parent_1 = source.getParent();
  93439. if (parent_1) {
  93440. var parentIndex = this.bones.indexOf(parent_1);
  93441. parentBone = result.bones[parentIndex];
  93442. }
  93443. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  93444. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  93445. }
  93446. if (this._ranges) {
  93447. result._ranges = {};
  93448. for (var rangeName in this._ranges) {
  93449. var range = this._ranges[rangeName];
  93450. if (range) {
  93451. result._ranges[rangeName] = range.clone();
  93452. }
  93453. }
  93454. }
  93455. this._isDirty = true;
  93456. return result;
  93457. };
  93458. /**
  93459. * Enable animation blending for this skeleton
  93460. * @param blendingSpeed defines the blending speed to apply
  93461. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  93462. */
  93463. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  93464. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  93465. this.bones.forEach(function (bone) {
  93466. bone.animations.forEach(function (animation) {
  93467. animation.enableBlending = true;
  93468. animation.blendingSpeed = blendingSpeed;
  93469. });
  93470. });
  93471. };
  93472. /**
  93473. * Releases all resources associated with the current skeleton
  93474. */
  93475. Skeleton.prototype.dispose = function () {
  93476. this._meshesWithPoseMatrix = [];
  93477. // Animations
  93478. this.getScene().stopAnimation(this);
  93479. // Remove from scene
  93480. this.getScene().removeSkeleton(this);
  93481. };
  93482. /**
  93483. * Serialize the skeleton in a JSON object
  93484. * @returns a JSON object
  93485. */
  93486. Skeleton.prototype.serialize = function () {
  93487. var serializationObject = {};
  93488. serializationObject.name = this.name;
  93489. serializationObject.id = this.id;
  93490. if (this.dimensionsAtRest) {
  93491. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  93492. }
  93493. serializationObject.bones = [];
  93494. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93495. for (var index = 0; index < this.bones.length; index++) {
  93496. var bone = this.bones[index];
  93497. var parent_2 = bone.getParent();
  93498. var serializedBone = {
  93499. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  93500. name: bone.name,
  93501. matrix: bone.getBaseMatrix().toArray(),
  93502. rest: bone.getRestPose().toArray()
  93503. };
  93504. serializationObject.bones.push(serializedBone);
  93505. if (bone.length) {
  93506. serializedBone.length = bone.length;
  93507. }
  93508. if (bone.metadata) {
  93509. serializedBone.metadata = bone.metadata;
  93510. }
  93511. if (bone.animations && bone.animations.length > 0) {
  93512. serializedBone.animation = bone.animations[0].serialize();
  93513. }
  93514. serializationObject.ranges = [];
  93515. for (var name in this._ranges) {
  93516. var source = this._ranges[name];
  93517. if (!source) {
  93518. continue;
  93519. }
  93520. var range = {};
  93521. range.name = name;
  93522. range.from = source.from;
  93523. range.to = source.to;
  93524. serializationObject.ranges.push(range);
  93525. }
  93526. }
  93527. return serializationObject;
  93528. };
  93529. /**
  93530. * Creates a new skeleton from serialized data
  93531. * @param parsedSkeleton defines the serialized data
  93532. * @param scene defines the hosting scene
  93533. * @returns a new skeleton
  93534. */
  93535. Skeleton.Parse = function (parsedSkeleton, scene) {
  93536. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  93537. if (parsedSkeleton.dimensionsAtRest) {
  93538. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  93539. }
  93540. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  93541. var index;
  93542. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  93543. var parsedBone = parsedSkeleton.bones[index];
  93544. var parentBone = null;
  93545. if (parsedBone.parentBoneIndex > -1) {
  93546. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  93547. }
  93548. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  93549. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  93550. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  93551. bone.id = parsedBone.id;
  93552. }
  93553. if (parsedBone.length) {
  93554. bone.length = parsedBone.length;
  93555. }
  93556. if (parsedBone.metadata) {
  93557. bone.metadata = parsedBone.metadata;
  93558. }
  93559. if (parsedBone.animation) {
  93560. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  93561. }
  93562. }
  93563. // placed after bones, so createAnimationRange can cascade down
  93564. if (parsedSkeleton.ranges) {
  93565. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  93566. var data = parsedSkeleton.ranges[index];
  93567. skeleton.createAnimationRange(data.name, data.from, data.to);
  93568. }
  93569. }
  93570. return skeleton;
  93571. };
  93572. /**
  93573. * Compute all node absolute transforms
  93574. * @param forceUpdate defines if computation must be done even if cache is up to date
  93575. */
  93576. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  93577. if (forceUpdate === void 0) { forceUpdate = false; }
  93578. var renderId = this._scene.getRenderId();
  93579. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  93580. this.bones[0].computeAbsoluteTransforms();
  93581. this._lastAbsoluteTransformsUpdateId = renderId;
  93582. }
  93583. };
  93584. /**
  93585. * Gets the root pose matrix
  93586. * @returns a matrix
  93587. */
  93588. Skeleton.prototype.getPoseMatrix = function () {
  93589. var poseMatrix = null;
  93590. if (this._meshesWithPoseMatrix.length > 0) {
  93591. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  93592. }
  93593. return poseMatrix;
  93594. };
  93595. /**
  93596. * Sorts bones per internal index
  93597. */
  93598. Skeleton.prototype.sortBones = function () {
  93599. var bones = new Array();
  93600. var visited = new Array(this.bones.length);
  93601. for (var index = 0; index < this.bones.length; index++) {
  93602. this._sortBones(index, bones, visited);
  93603. }
  93604. this.bones = bones;
  93605. };
  93606. Skeleton.prototype._sortBones = function (index, bones, visited) {
  93607. if (visited[index]) {
  93608. return;
  93609. }
  93610. visited[index] = true;
  93611. var bone = this.bones[index];
  93612. if (bone._index === undefined) {
  93613. bone._index = index;
  93614. }
  93615. var parentBone = bone.getParent();
  93616. if (parentBone) {
  93617. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  93618. }
  93619. bones.push(bone);
  93620. };
  93621. return Skeleton;
  93622. }());
  93623. BABYLON.Skeleton = Skeleton;
  93624. })(BABYLON || (BABYLON = {}));
  93625. //# sourceMappingURL=babylon.skeleton.js.map
  93626. var BABYLON;
  93627. (function (BABYLON) {
  93628. /**
  93629. * This groups tools to convert HDR texture to native colors array.
  93630. */
  93631. var HDRTools = /** @class */ (function () {
  93632. function HDRTools() {
  93633. }
  93634. HDRTools.Ldexp = function (mantissa, exponent) {
  93635. if (exponent > 1023) {
  93636. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  93637. }
  93638. if (exponent < -1074) {
  93639. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  93640. }
  93641. return mantissa * Math.pow(2, exponent);
  93642. };
  93643. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  93644. if (exponent > 0) { /*nonzero pixel*/
  93645. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  93646. float32array[index + 0] = red * exponent;
  93647. float32array[index + 1] = green * exponent;
  93648. float32array[index + 2] = blue * exponent;
  93649. }
  93650. else {
  93651. float32array[index + 0] = 0;
  93652. float32array[index + 1] = 0;
  93653. float32array[index + 2] = 0;
  93654. }
  93655. };
  93656. HDRTools.readStringLine = function (uint8array, startIndex) {
  93657. var line = "";
  93658. var character = "";
  93659. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  93660. character = String.fromCharCode(uint8array[i]);
  93661. if (character == "\n") {
  93662. break;
  93663. }
  93664. line += character;
  93665. }
  93666. return line;
  93667. };
  93668. /**
  93669. * Reads header information from an RGBE texture stored in a native array.
  93670. * More information on this format are available here:
  93671. * https://en.wikipedia.org/wiki/RGBE_image_format
  93672. *
  93673. * @param uint8array The binary file stored in native array.
  93674. * @return The header information.
  93675. */
  93676. HDRTools.RGBE_ReadHeader = function (uint8array) {
  93677. var height = 0;
  93678. var width = 0;
  93679. var line = this.readStringLine(uint8array, 0);
  93680. if (line[0] != '#' || line[1] != '?') {
  93681. throw "Bad HDR Format.";
  93682. }
  93683. var endOfHeader = false;
  93684. var findFormat = false;
  93685. var lineIndex = 0;
  93686. do {
  93687. lineIndex += (line.length + 1);
  93688. line = this.readStringLine(uint8array, lineIndex);
  93689. if (line == "FORMAT=32-bit_rle_rgbe") {
  93690. findFormat = true;
  93691. }
  93692. else if (line.length == 0) {
  93693. endOfHeader = true;
  93694. }
  93695. } while (!endOfHeader);
  93696. if (!findFormat) {
  93697. throw "HDR Bad header format, unsupported FORMAT";
  93698. }
  93699. lineIndex += (line.length + 1);
  93700. line = this.readStringLine(uint8array, lineIndex);
  93701. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  93702. var match = sizeRegexp.exec(line);
  93703. // TODO. Support +Y and -X if needed.
  93704. if (!match || match.length < 3) {
  93705. throw "HDR Bad header format, no size";
  93706. }
  93707. width = parseInt(match[2]);
  93708. height = parseInt(match[1]);
  93709. if (width < 8 || width > 0x7fff) {
  93710. throw "HDR Bad header format, unsupported size";
  93711. }
  93712. lineIndex += (line.length + 1);
  93713. return {
  93714. height: height,
  93715. width: width,
  93716. dataPosition: lineIndex
  93717. };
  93718. };
  93719. /**
  93720. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  93721. * This RGBE texture needs to store the information as a panorama.
  93722. *
  93723. * More information on this format are available here:
  93724. * https://en.wikipedia.org/wiki/RGBE_image_format
  93725. *
  93726. * @param buffer The binary file stored in an array buffer.
  93727. * @param size The expected size of the extracted cubemap.
  93728. * @return The Cube Map information.
  93729. */
  93730. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  93731. var uint8array = new Uint8Array(buffer);
  93732. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  93733. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93734. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  93735. return cubeMapData;
  93736. };
  93737. /**
  93738. * Returns the pixels data extracted from an RGBE texture.
  93739. * This pixels will be stored left to right up to down in the R G B order in one array.
  93740. *
  93741. * More information on this format are available here:
  93742. * https://en.wikipedia.org/wiki/RGBE_image_format
  93743. *
  93744. * @param uint8array The binary file stored in an array buffer.
  93745. * @param hdrInfo The header information of the file.
  93746. * @return The pixels data in RGB right to left up to down order.
  93747. */
  93748. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  93749. // Keep for multi format supports.
  93750. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93751. };
  93752. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  93753. var num_scanlines = hdrInfo.height;
  93754. var scanline_width = hdrInfo.width;
  93755. var a, b, c, d, count;
  93756. var dataIndex = hdrInfo.dataPosition;
  93757. var index = 0, endIndex = 0, i = 0;
  93758. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  93759. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  93760. // 3 channels of 4 bytes per pixel in float.
  93761. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  93762. var resultArray = new Float32Array(resultBuffer);
  93763. // read in each successive scanline
  93764. while (num_scanlines > 0) {
  93765. a = uint8array[dataIndex++];
  93766. b = uint8array[dataIndex++];
  93767. c = uint8array[dataIndex++];
  93768. d = uint8array[dataIndex++];
  93769. if (a != 2 || b != 2 || (c & 0x80)) {
  93770. // this file is not run length encoded
  93771. throw "HDR Bad header format, not RLE";
  93772. }
  93773. if (((c << 8) | d) != scanline_width) {
  93774. throw "HDR Bad header format, wrong scan line width";
  93775. }
  93776. index = 0;
  93777. // read each of the four channels for the scanline into the buffer
  93778. for (i = 0; i < 4; i++) {
  93779. endIndex = (i + 1) * scanline_width;
  93780. while (index < endIndex) {
  93781. a = uint8array[dataIndex++];
  93782. b = uint8array[dataIndex++];
  93783. if (a > 128) {
  93784. // a run of the same value
  93785. count = a - 128;
  93786. if ((count == 0) || (count > endIndex - index)) {
  93787. throw "HDR Bad Format, bad scanline data (run)";
  93788. }
  93789. while (count-- > 0) {
  93790. scanLineArray[index++] = b;
  93791. }
  93792. }
  93793. else {
  93794. // a non-run
  93795. count = a;
  93796. if ((count == 0) || (count > endIndex - index)) {
  93797. throw "HDR Bad Format, bad scanline data (non-run)";
  93798. }
  93799. scanLineArray[index++] = b;
  93800. if (--count > 0) {
  93801. for (var j = 0; j < count; j++) {
  93802. scanLineArray[index++] = uint8array[dataIndex++];
  93803. }
  93804. }
  93805. }
  93806. }
  93807. }
  93808. // now convert data from buffer into floats
  93809. for (i = 0; i < scanline_width; i++) {
  93810. a = scanLineArray[i];
  93811. b = scanLineArray[i + scanline_width];
  93812. c = scanLineArray[i + 2 * scanline_width];
  93813. d = scanLineArray[i + 3 * scanline_width];
  93814. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  93815. }
  93816. num_scanlines--;
  93817. }
  93818. return resultArray;
  93819. };
  93820. return HDRTools;
  93821. }());
  93822. BABYLON.HDRTools = HDRTools;
  93823. })(BABYLON || (BABYLON = {}));
  93824. //# sourceMappingURL=babylon.hdr.js.map
  93825. var BABYLON;
  93826. (function (BABYLON) {
  93827. /**
  93828. * This represents a texture coming from an HDR input.
  93829. *
  93830. * The only supported format is currently panorama picture stored in RGBE format.
  93831. * Example of such files can be found on HDRLib: http://hdrlib.com/
  93832. */
  93833. var HDRCubeTexture = /** @class */ (function (_super) {
  93834. __extends(HDRCubeTexture, _super);
  93835. /**
  93836. * Instantiates an HDRTexture from the following parameters.
  93837. *
  93838. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  93839. * @param scene The scene the texture will be used in
  93840. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  93841. * @param noMipmap Forces to not generate the mipmap if true
  93842. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  93843. * @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)
  93844. * @param reserved Reserved flag for internal use.
  93845. */
  93846. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  93847. if (noMipmap === void 0) { noMipmap = false; }
  93848. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93849. if (gammaSpace === void 0) { gammaSpace = false; }
  93850. if (reserved === void 0) { reserved = false; }
  93851. if (onLoad === void 0) { onLoad = null; }
  93852. if (onError === void 0) { onError = null; }
  93853. var _this = _super.call(this, scene) || this;
  93854. _this._generateHarmonics = true;
  93855. _this._onLoad = null;
  93856. _this._onError = null;
  93857. /**
  93858. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  93859. */
  93860. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  93861. _this._isBlocking = true;
  93862. _this._rotationY = 0;
  93863. /**
  93864. * Gets or sets the center of the bounding box associated with the cube texture
  93865. * It must define where the camera used to render the texture was set
  93866. */
  93867. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  93868. if (!url) {
  93869. return _this;
  93870. }
  93871. _this.name = url;
  93872. _this.url = url;
  93873. _this.hasAlpha = false;
  93874. _this.isCube = true;
  93875. _this._textureMatrix = BABYLON.Matrix.Identity();
  93876. _this._onLoad = onLoad;
  93877. _this._onError = onError;
  93878. _this.gammaSpace = gammaSpace;
  93879. _this._noMipmap = noMipmap;
  93880. _this._size = size;
  93881. _this._texture = _this._getFromCache(url, _this._noMipmap);
  93882. if (!_this._texture) {
  93883. if (!scene.useDelayedTextureLoading) {
  93884. _this.loadTexture();
  93885. }
  93886. else {
  93887. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  93888. }
  93889. }
  93890. return _this;
  93891. }
  93892. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  93893. /**
  93894. * Gets wether or not the texture is blocking during loading.
  93895. */
  93896. get: function () {
  93897. return this._isBlocking;
  93898. },
  93899. /**
  93900. * Sets wether or not the texture is blocking during loading.
  93901. */
  93902. set: function (value) {
  93903. this._isBlocking = value;
  93904. },
  93905. enumerable: true,
  93906. configurable: true
  93907. });
  93908. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  93909. /**
  93910. * Gets texture matrix rotation angle around Y axis radians.
  93911. */
  93912. get: function () {
  93913. return this._rotationY;
  93914. },
  93915. /**
  93916. * Sets texture matrix rotation angle around Y axis in radians.
  93917. */
  93918. set: function (value) {
  93919. this._rotationY = value;
  93920. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  93921. },
  93922. enumerable: true,
  93923. configurable: true
  93924. });
  93925. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  93926. get: function () {
  93927. return this._boundingBoxSize;
  93928. },
  93929. /**
  93930. * Gets or sets the size of the bounding box associated with the cube texture
  93931. * When defined, the cubemap will switch to local mode
  93932. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  93933. * @example https://www.babylonjs-playground.com/#RNASML
  93934. */
  93935. set: function (value) {
  93936. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  93937. return;
  93938. }
  93939. this._boundingBoxSize = value;
  93940. var scene = this.getScene();
  93941. if (scene) {
  93942. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  93943. }
  93944. },
  93945. enumerable: true,
  93946. configurable: true
  93947. });
  93948. /**
  93949. * Occurs when the file is raw .hdr file.
  93950. */
  93951. HDRCubeTexture.prototype.loadTexture = function () {
  93952. var _this = this;
  93953. var callback = function (buffer) {
  93954. _this.lodGenerationOffset = 0.0;
  93955. _this.lodGenerationScale = 0.8;
  93956. var scene = _this.getScene();
  93957. if (!scene) {
  93958. return null;
  93959. }
  93960. // Extract the raw linear data.
  93961. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  93962. // Generate harmonics if needed.
  93963. if (_this._generateHarmonics) {
  93964. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  93965. _this.sphericalPolynomial = sphericalPolynomial;
  93966. }
  93967. var results = [];
  93968. var byteArray = null;
  93969. // Push each faces.
  93970. for (var j = 0; j < 6; j++) {
  93971. // Create uintarray fallback.
  93972. if (!scene.getEngine().getCaps().textureFloat) {
  93973. // 3 channels of 1 bytes per pixel in bytes.
  93974. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  93975. byteArray = new Uint8Array(byteBuffer);
  93976. }
  93977. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  93978. // If special cases.
  93979. if (_this.gammaSpace || byteArray) {
  93980. for (var i = 0; i < _this._size * _this._size; i++) {
  93981. // Put in gamma space if requested.
  93982. if (_this.gammaSpace) {
  93983. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  93984. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  93985. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  93986. }
  93987. // Convert to int texture for fallback.
  93988. if (byteArray) {
  93989. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  93990. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  93991. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  93992. // May use luminance instead if the result is not accurate.
  93993. var max = Math.max(Math.max(r, g), b);
  93994. if (max > 255) {
  93995. var scale = 255 / max;
  93996. r *= scale;
  93997. g *= scale;
  93998. b *= scale;
  93999. }
  94000. byteArray[(i * 3) + 0] = r;
  94001. byteArray[(i * 3) + 1] = g;
  94002. byteArray[(i * 3) + 2] = b;
  94003. }
  94004. }
  94005. }
  94006. if (byteArray) {
  94007. results.push(byteArray);
  94008. }
  94009. else {
  94010. results.push(dataFace);
  94011. }
  94012. }
  94013. return results;
  94014. };
  94015. var scene = this.getScene();
  94016. if (scene) {
  94017. 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);
  94018. }
  94019. };
  94020. HDRCubeTexture.prototype.clone = function () {
  94021. var scene = this.getScene();
  94022. if (!scene) {
  94023. return this;
  94024. }
  94025. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  94026. // Base texture
  94027. newTexture.level = this.level;
  94028. newTexture.wrapU = this.wrapU;
  94029. newTexture.wrapV = this.wrapV;
  94030. newTexture.coordinatesIndex = this.coordinatesIndex;
  94031. newTexture.coordinatesMode = this.coordinatesMode;
  94032. return newTexture;
  94033. };
  94034. // Methods
  94035. HDRCubeTexture.prototype.delayLoad = function () {
  94036. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  94037. return;
  94038. }
  94039. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  94040. this._texture = this._getFromCache(this.url, this._noMipmap);
  94041. if (!this._texture) {
  94042. this.loadTexture();
  94043. }
  94044. };
  94045. /**
  94046. * Get the texture reflection matrix used to rotate/transform the reflection.
  94047. * @returns the reflection matrix
  94048. */
  94049. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  94050. return this._textureMatrix;
  94051. };
  94052. /**
  94053. * Set the texture reflection matrix used to rotate/transform the reflection.
  94054. * @param value Define the reflection matrix to set
  94055. */
  94056. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  94057. this._textureMatrix = value;
  94058. };
  94059. /**
  94060. * Parses a JSON representation of an HDR Texture in order to create the texture
  94061. * @param parsedTexture Define the JSON representation
  94062. * @param scene Define the scene the texture should be created in
  94063. * @param rootUrl Define the root url in case we need to load relative dependencies
  94064. * @returns the newly created texture after parsing
  94065. */
  94066. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  94067. var texture = null;
  94068. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  94069. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  94070. texture.name = parsedTexture.name;
  94071. texture.hasAlpha = parsedTexture.hasAlpha;
  94072. texture.level = parsedTexture.level;
  94073. texture.coordinatesMode = parsedTexture.coordinatesMode;
  94074. texture.isBlocking = parsedTexture.isBlocking;
  94075. }
  94076. if (texture) {
  94077. if (parsedTexture.boundingBoxPosition) {
  94078. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  94079. }
  94080. if (parsedTexture.boundingBoxSize) {
  94081. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  94082. }
  94083. if (parsedTexture.rotationY) {
  94084. texture.rotationY = parsedTexture.rotationY;
  94085. }
  94086. }
  94087. return texture;
  94088. };
  94089. HDRCubeTexture.prototype.serialize = function () {
  94090. if (!this.name) {
  94091. return null;
  94092. }
  94093. var serializationObject = {};
  94094. serializationObject.name = this.name;
  94095. serializationObject.hasAlpha = this.hasAlpha;
  94096. serializationObject.isCube = true;
  94097. serializationObject.level = this.level;
  94098. serializationObject.size = this._size;
  94099. serializationObject.coordinatesMode = this.coordinatesMode;
  94100. serializationObject.useInGammaSpace = this.gammaSpace;
  94101. serializationObject.generateHarmonics = this._generateHarmonics;
  94102. serializationObject.customType = "BABYLON.HDRCubeTexture";
  94103. serializationObject.noMipmap = this._noMipmap;
  94104. serializationObject.isBlocking = this._isBlocking;
  94105. serializationObject.rotationY = this._rotationY;
  94106. return serializationObject;
  94107. };
  94108. HDRCubeTexture._facesMapping = [
  94109. "right",
  94110. "left",
  94111. "up",
  94112. "down",
  94113. "front",
  94114. "back"
  94115. ];
  94116. return HDRCubeTexture;
  94117. }(BABYLON.BaseTexture));
  94118. BABYLON.HDRCubeTexture = HDRCubeTexture;
  94119. })(BABYLON || (BABYLON = {}));
  94120. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  94121. var BABYLON;
  94122. (function (BABYLON) {
  94123. /**
  94124. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  94125. */
  94126. var PanoramaToCubeMapTools = /** @class */ (function () {
  94127. function PanoramaToCubeMapTools() {
  94128. }
  94129. /**
  94130. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  94131. *
  94132. * @param float32Array The source data.
  94133. * @param inputWidth The width of the input panorama.
  94134. * @param inputHeight The height of the input panorama.
  94135. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  94136. * @return The cubemap data
  94137. */
  94138. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  94139. if (!float32Array) {
  94140. throw "ConvertPanoramaToCubemap: input cannot be null";
  94141. }
  94142. if (float32Array.length != inputWidth * inputHeight * 3) {
  94143. throw "ConvertPanoramaToCubemap: input size is wrong";
  94144. }
  94145. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  94146. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  94147. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  94148. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  94149. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  94150. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  94151. return {
  94152. front: textureFront,
  94153. back: textureBack,
  94154. left: textureLeft,
  94155. right: textureRight,
  94156. up: textureUp,
  94157. down: textureDown,
  94158. size: size,
  94159. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94160. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  94161. gammaSpace: false,
  94162. };
  94163. };
  94164. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  94165. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  94166. var textureArray = new Float32Array(buffer);
  94167. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  94168. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  94169. var dy = 1 / texSize;
  94170. var fy = 0;
  94171. for (var y = 0; y < texSize; y++) {
  94172. var xv1 = faceData[0];
  94173. var xv2 = faceData[2];
  94174. for (var x = 0; x < texSize; x++) {
  94175. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  94176. v.normalize();
  94177. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  94178. // 3 channels per pixels
  94179. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  94180. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  94181. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  94182. xv1 = xv1.add(rotDX1);
  94183. xv2 = xv2.add(rotDX2);
  94184. }
  94185. fy += dy;
  94186. }
  94187. return textureArray;
  94188. };
  94189. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  94190. var theta = Math.atan2(vDir.z, vDir.x);
  94191. var phi = Math.acos(vDir.y);
  94192. while (theta < -Math.PI) {
  94193. theta += 2 * Math.PI;
  94194. }
  94195. while (theta > Math.PI) {
  94196. theta -= 2 * Math.PI;
  94197. }
  94198. var dx = theta / Math.PI;
  94199. var dy = phi / Math.PI;
  94200. // recenter.
  94201. dx = dx * 0.5 + 0.5;
  94202. var px = Math.round(dx * inputWidth);
  94203. if (px < 0) {
  94204. px = 0;
  94205. }
  94206. else if (px >= inputWidth) {
  94207. px = inputWidth - 1;
  94208. }
  94209. var py = Math.round(dy * inputHeight);
  94210. if (py < 0) {
  94211. py = 0;
  94212. }
  94213. else if (py >= inputHeight) {
  94214. py = inputHeight - 1;
  94215. }
  94216. var inputY = (inputHeight - py - 1);
  94217. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  94218. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  94219. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  94220. return {
  94221. r: r,
  94222. g: g,
  94223. b: b
  94224. };
  94225. };
  94226. PanoramaToCubeMapTools.FACE_FRONT = [
  94227. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94228. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94229. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94230. new BABYLON.Vector3(1.0, 1.0, -1.0)
  94231. ];
  94232. PanoramaToCubeMapTools.FACE_BACK = [
  94233. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94234. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94235. new BABYLON.Vector3(1.0, 1.0, 1.0),
  94236. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  94237. ];
  94238. PanoramaToCubeMapTools.FACE_RIGHT = [
  94239. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94240. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94241. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94242. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94243. ];
  94244. PanoramaToCubeMapTools.FACE_LEFT = [
  94245. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94246. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94247. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94248. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  94249. ];
  94250. PanoramaToCubeMapTools.FACE_DOWN = [
  94251. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94252. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94253. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94254. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94255. ];
  94256. PanoramaToCubeMapTools.FACE_UP = [
  94257. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94258. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94259. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94260. new BABYLON.Vector3(1.0, -1.0, -1.0)
  94261. ];
  94262. return PanoramaToCubeMapTools;
  94263. }());
  94264. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  94265. })(BABYLON || (BABYLON = {}));
  94266. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  94267. var BABYLON;
  94268. (function (BABYLON) {
  94269. /**
  94270. * Vector2 wth index property
  94271. */
  94272. var IndexedVector2 = /** @class */ (function (_super) {
  94273. __extends(IndexedVector2, _super);
  94274. function IndexedVector2(original,
  94275. /** Index of the vector2 */
  94276. index) {
  94277. var _this = _super.call(this, original.x, original.y) || this;
  94278. _this.index = index;
  94279. return _this;
  94280. }
  94281. return IndexedVector2;
  94282. }(BABYLON.Vector2));
  94283. /**
  94284. * Defines points to create a polygon
  94285. */
  94286. var PolygonPoints = /** @class */ (function () {
  94287. function PolygonPoints() {
  94288. this.elements = new Array();
  94289. }
  94290. PolygonPoints.prototype.add = function (originalPoints) {
  94291. var _this = this;
  94292. var result = new Array();
  94293. originalPoints.forEach(function (point) {
  94294. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  94295. var newPoint = new IndexedVector2(point, _this.elements.length);
  94296. result.push(newPoint);
  94297. _this.elements.push(newPoint);
  94298. }
  94299. });
  94300. return result;
  94301. };
  94302. PolygonPoints.prototype.computeBounds = function () {
  94303. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94304. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94305. this.elements.forEach(function (point) {
  94306. // x
  94307. if (point.x < lmin.x) {
  94308. lmin.x = point.x;
  94309. }
  94310. else if (point.x > lmax.x) {
  94311. lmax.x = point.x;
  94312. }
  94313. // y
  94314. if (point.y < lmin.y) {
  94315. lmin.y = point.y;
  94316. }
  94317. else if (point.y > lmax.y) {
  94318. lmax.y = point.y;
  94319. }
  94320. });
  94321. return {
  94322. min: lmin,
  94323. max: lmax,
  94324. width: lmax.x - lmin.x,
  94325. height: lmax.y - lmin.y
  94326. };
  94327. };
  94328. return PolygonPoints;
  94329. }());
  94330. /**
  94331. * Polygon
  94332. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  94333. */
  94334. var Polygon = /** @class */ (function () {
  94335. function Polygon() {
  94336. }
  94337. /**
  94338. * Creates a rectangle
  94339. * @param xmin bottom X coord
  94340. * @param ymin bottom Y coord
  94341. * @param xmax top X coord
  94342. * @param ymax top Y coord
  94343. * @returns points that make the resulting rectation
  94344. */
  94345. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  94346. return [
  94347. new BABYLON.Vector2(xmin, ymin),
  94348. new BABYLON.Vector2(xmax, ymin),
  94349. new BABYLON.Vector2(xmax, ymax),
  94350. new BABYLON.Vector2(xmin, ymax)
  94351. ];
  94352. };
  94353. /**
  94354. * Creates a circle
  94355. * @param radius radius of circle
  94356. * @param cx scale in x
  94357. * @param cy scale in y
  94358. * @param numberOfSides number of sides that make up the circle
  94359. * @returns points that make the resulting circle
  94360. */
  94361. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  94362. if (cx === void 0) { cx = 0; }
  94363. if (cy === void 0) { cy = 0; }
  94364. if (numberOfSides === void 0) { numberOfSides = 32; }
  94365. var result = new Array();
  94366. var angle = 0;
  94367. var increment = (Math.PI * 2) / numberOfSides;
  94368. for (var i = 0; i < numberOfSides; i++) {
  94369. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  94370. angle -= increment;
  94371. }
  94372. return result;
  94373. };
  94374. /**
  94375. * Creates a polygon from input string
  94376. * @param input Input polygon data
  94377. * @returns the parsed points
  94378. */
  94379. Polygon.Parse = function (input) {
  94380. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  94381. var i, result = [];
  94382. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  94383. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  94384. }
  94385. return result;
  94386. };
  94387. /**
  94388. * Starts building a polygon from x and y coordinates
  94389. * @param x x coordinate
  94390. * @param y y coordinate
  94391. * @returns the started path2
  94392. */
  94393. Polygon.StartingAt = function (x, y) {
  94394. return BABYLON.Path2.StartingAt(x, y);
  94395. };
  94396. return Polygon;
  94397. }());
  94398. BABYLON.Polygon = Polygon;
  94399. /**
  94400. * Builds a polygon
  94401. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  94402. */
  94403. var PolygonMeshBuilder = /** @class */ (function () {
  94404. /**
  94405. * Creates a PolygonMeshBuilder
  94406. * @param name name of the builder
  94407. * @param contours Path of the polygon
  94408. * @param scene scene to add to
  94409. */
  94410. function PolygonMeshBuilder(name, contours, scene) {
  94411. this._points = new PolygonPoints();
  94412. this._outlinepoints = new PolygonPoints();
  94413. this._holes = new Array();
  94414. this._epoints = new Array();
  94415. this._eholes = new Array();
  94416. this._name = name;
  94417. this._scene = scene;
  94418. var points;
  94419. if (contours instanceof BABYLON.Path2) {
  94420. points = contours.getPoints();
  94421. }
  94422. else {
  94423. points = contours;
  94424. }
  94425. this._addToepoint(points);
  94426. this._points.add(points);
  94427. this._outlinepoints.add(points);
  94428. if (typeof earcut === 'undefined') {
  94429. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  94430. }
  94431. }
  94432. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  94433. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  94434. var p = points_1[_i];
  94435. this._epoints.push(p.x, p.y);
  94436. }
  94437. };
  94438. /**
  94439. * Adds a whole within the polygon
  94440. * @param hole Array of points defining the hole
  94441. * @returns this
  94442. */
  94443. PolygonMeshBuilder.prototype.addHole = function (hole) {
  94444. this._points.add(hole);
  94445. var holepoints = new PolygonPoints();
  94446. holepoints.add(hole);
  94447. this._holes.push(holepoints);
  94448. this._eholes.push(this._epoints.length / 2);
  94449. this._addToepoint(hole);
  94450. return this;
  94451. };
  94452. /**
  94453. * Creates the polygon
  94454. * @param updatable If the mesh should be updatable
  94455. * @param depth The depth of the mesh created
  94456. * @returns the created mesh
  94457. */
  94458. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  94459. var _this = this;
  94460. if (updatable === void 0) { updatable = false; }
  94461. if (depth === void 0) { depth = 0; }
  94462. var result = new BABYLON.Mesh(this._name, this._scene);
  94463. var normals = new Array();
  94464. var positions = new Array();
  94465. var uvs = new Array();
  94466. var bounds = this._points.computeBounds();
  94467. this._points.elements.forEach(function (p) {
  94468. normals.push(0, 1.0, 0);
  94469. positions.push(p.x, 0, p.y);
  94470. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  94471. });
  94472. var indices = new Array();
  94473. var res = earcut(this._epoints, this._eholes, 2);
  94474. for (var i = 0; i < res.length; i++) {
  94475. indices.push(res[i]);
  94476. }
  94477. if (depth > 0) {
  94478. var positionscount = (positions.length / 3); //get the current pointcount
  94479. this._points.elements.forEach(function (p) {
  94480. normals.push(0, -1.0, 0);
  94481. positions.push(p.x, -depth, p.y);
  94482. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  94483. });
  94484. var totalCount = indices.length;
  94485. for (var i = 0; i < totalCount; i += 3) {
  94486. var i0 = indices[i + 0];
  94487. var i1 = indices[i + 1];
  94488. var i2 = indices[i + 2];
  94489. indices.push(i2 + positionscount);
  94490. indices.push(i1 + positionscount);
  94491. indices.push(i0 + positionscount);
  94492. }
  94493. //Add the sides
  94494. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  94495. this._holes.forEach(function (hole) {
  94496. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  94497. });
  94498. }
  94499. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  94500. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  94501. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  94502. result.setIndices(indices);
  94503. return result;
  94504. };
  94505. /**
  94506. * Adds a side to the polygon
  94507. * @param positions points that make the polygon
  94508. * @param normals normals of the polygon
  94509. * @param uvs uvs of the polygon
  94510. * @param indices indices of the polygon
  94511. * @param bounds bounds of the polygon
  94512. * @param points points of the polygon
  94513. * @param depth depth of the polygon
  94514. * @param flip flip of the polygon
  94515. */
  94516. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  94517. var StartIndex = positions.length / 3;
  94518. var ulength = 0;
  94519. for (var i = 0; i < points.elements.length; i++) {
  94520. var p = points.elements[i];
  94521. var p1;
  94522. if ((i + 1) > points.elements.length - 1) {
  94523. p1 = points.elements[0];
  94524. }
  94525. else {
  94526. p1 = points.elements[i + 1];
  94527. }
  94528. positions.push(p.x, 0, p.y);
  94529. positions.push(p.x, -depth, p.y);
  94530. positions.push(p1.x, 0, p1.y);
  94531. positions.push(p1.x, -depth, p1.y);
  94532. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  94533. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  94534. var v3 = v2.subtract(v1);
  94535. var v4 = new BABYLON.Vector3(0, 1, 0);
  94536. var vn = BABYLON.Vector3.Cross(v3, v4);
  94537. vn = vn.normalize();
  94538. uvs.push(ulength / bounds.width, 0);
  94539. uvs.push(ulength / bounds.width, 1);
  94540. ulength += v3.length();
  94541. uvs.push((ulength / bounds.width), 0);
  94542. uvs.push((ulength / bounds.width), 1);
  94543. if (!flip) {
  94544. normals.push(-vn.x, -vn.y, -vn.z);
  94545. normals.push(-vn.x, -vn.y, -vn.z);
  94546. normals.push(-vn.x, -vn.y, -vn.z);
  94547. normals.push(-vn.x, -vn.y, -vn.z);
  94548. indices.push(StartIndex);
  94549. indices.push(StartIndex + 1);
  94550. indices.push(StartIndex + 2);
  94551. indices.push(StartIndex + 1);
  94552. indices.push(StartIndex + 3);
  94553. indices.push(StartIndex + 2);
  94554. }
  94555. else {
  94556. normals.push(vn.x, vn.y, vn.z);
  94557. normals.push(vn.x, vn.y, vn.z);
  94558. normals.push(vn.x, vn.y, vn.z);
  94559. normals.push(vn.x, vn.y, vn.z);
  94560. indices.push(StartIndex);
  94561. indices.push(StartIndex + 2);
  94562. indices.push(StartIndex + 1);
  94563. indices.push(StartIndex + 1);
  94564. indices.push(StartIndex + 2);
  94565. indices.push(StartIndex + 3);
  94566. }
  94567. StartIndex += 4;
  94568. }
  94569. };
  94570. return PolygonMeshBuilder;
  94571. }());
  94572. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  94573. })(BABYLON || (BABYLON = {}));
  94574. //# sourceMappingURL=babylon.polygonMesh.js.map
  94575. var BABYLON;
  94576. (function (BABYLON) {
  94577. /**
  94578. * Unique ID when we import meshes from Babylon to CSG
  94579. */
  94580. var currentCSGMeshId = 0;
  94581. /**
  94582. * Represents a vertex of a polygon. Use your own vertex class instead of this
  94583. * one to provide additional features like texture coordinates and vertex
  94584. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  94585. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  94586. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  94587. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  94588. * is not used anywhere else.
  94589. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  94590. */
  94591. var Vertex = /** @class */ (function () {
  94592. /**
  94593. * Initializes the vertex
  94594. * @param pos The position of the vertex
  94595. * @param normal The normal of the vertex
  94596. * @param uv The texture coordinate of the vertex
  94597. */
  94598. function Vertex(
  94599. /**
  94600. * The position of the vertex
  94601. */
  94602. pos,
  94603. /**
  94604. * The normal of the vertex
  94605. */
  94606. normal,
  94607. /**
  94608. * The texture coordinate of the vertex
  94609. */
  94610. uv) {
  94611. this.pos = pos;
  94612. this.normal = normal;
  94613. this.uv = uv;
  94614. }
  94615. /**
  94616. * Make a clone, or deep copy, of the vertex
  94617. * @returns A new Vertex
  94618. */
  94619. Vertex.prototype.clone = function () {
  94620. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  94621. };
  94622. /**
  94623. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  94624. * orientation of a polygon is flipped.
  94625. */
  94626. Vertex.prototype.flip = function () {
  94627. this.normal = this.normal.scale(-1);
  94628. };
  94629. /**
  94630. * Create a new vertex between this vertex and `other` by linearly
  94631. * interpolating all properties using a parameter of `t`. Subclasses should
  94632. * override this to interpolate additional properties.
  94633. * @param other the vertex to interpolate against
  94634. * @param t The factor used to linearly interpolate between the vertices
  94635. */
  94636. Vertex.prototype.interpolate = function (other, t) {
  94637. 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));
  94638. };
  94639. return Vertex;
  94640. }());
  94641. /**
  94642. * Represents a plane in 3D space.
  94643. */
  94644. var Plane = /** @class */ (function () {
  94645. /**
  94646. * Initializes the plane
  94647. * @param normal The normal for the plane
  94648. * @param w
  94649. */
  94650. function Plane(normal, w) {
  94651. this.normal = normal;
  94652. this.w = w;
  94653. }
  94654. /**
  94655. * Construct a plane from three points
  94656. * @param a Point a
  94657. * @param b Point b
  94658. * @param c Point c
  94659. */
  94660. Plane.FromPoints = function (a, b, c) {
  94661. var v0 = c.subtract(a);
  94662. var v1 = b.subtract(a);
  94663. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  94664. return null;
  94665. }
  94666. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  94667. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  94668. };
  94669. /**
  94670. * Clone, or make a deep copy of the plane
  94671. * @returns a new Plane
  94672. */
  94673. Plane.prototype.clone = function () {
  94674. return new Plane(this.normal.clone(), this.w);
  94675. };
  94676. /**
  94677. * Flip the face of the plane
  94678. */
  94679. Plane.prototype.flip = function () {
  94680. this.normal.scaleInPlace(-1);
  94681. this.w = -this.w;
  94682. };
  94683. /**
  94684. * Split `polygon` by this plane if needed, then put the polygon or polygon
  94685. * fragments in the appropriate lists. Coplanar polygons go into either
  94686. `* coplanarFront` or `coplanarBack` depending on their orientation with
  94687. * respect to this plane. Polygons in front or in back of this plane go into
  94688. * either `front` or `back`
  94689. * @param polygon The polygon to be split
  94690. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  94691. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  94692. * @param front Will contain the polygons in front of the plane
  94693. * @param back Will contain the polygons begind the plane
  94694. */
  94695. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  94696. var COPLANAR = 0;
  94697. var FRONT = 1;
  94698. var BACK = 2;
  94699. var SPANNING = 3;
  94700. // Classify each point as well as the entire polygon into one of the above
  94701. // four classes.
  94702. var polygonType = 0;
  94703. var types = [];
  94704. var i;
  94705. var t;
  94706. for (i = 0; i < polygon.vertices.length; i++) {
  94707. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  94708. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  94709. polygonType |= type;
  94710. types.push(type);
  94711. }
  94712. // Put the polygon in the correct list, splitting it when necessary
  94713. switch (polygonType) {
  94714. case COPLANAR:
  94715. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  94716. break;
  94717. case FRONT:
  94718. front.push(polygon);
  94719. break;
  94720. case BACK:
  94721. back.push(polygon);
  94722. break;
  94723. case SPANNING:
  94724. var f = [], b = [];
  94725. for (i = 0; i < polygon.vertices.length; i++) {
  94726. var j = (i + 1) % polygon.vertices.length;
  94727. var ti = types[i], tj = types[j];
  94728. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  94729. if (ti !== BACK) {
  94730. f.push(vi);
  94731. }
  94732. if (ti !== FRONT) {
  94733. b.push(ti !== BACK ? vi.clone() : vi);
  94734. }
  94735. if ((ti | tj) === SPANNING) {
  94736. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  94737. var v = vi.interpolate(vj, t);
  94738. f.push(v);
  94739. b.push(v.clone());
  94740. }
  94741. }
  94742. var poly;
  94743. if (f.length >= 3) {
  94744. poly = new Polygon(f, polygon.shared);
  94745. if (poly.plane) {
  94746. front.push(poly);
  94747. }
  94748. }
  94749. if (b.length >= 3) {
  94750. poly = new Polygon(b, polygon.shared);
  94751. if (poly.plane) {
  94752. back.push(poly);
  94753. }
  94754. }
  94755. break;
  94756. }
  94757. };
  94758. /**
  94759. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  94760. * point is on the plane
  94761. */
  94762. Plane.EPSILON = 1e-5;
  94763. return Plane;
  94764. }());
  94765. /**
  94766. * Represents a convex polygon. The vertices used to initialize a polygon must
  94767. * be coplanar and form a convex loop.
  94768. *
  94769. * Each convex polygon has a `shared` property, which is shared between all
  94770. * polygons that are clones of each other or were split from the same polygon.
  94771. * This can be used to define per-polygon properties (such as surface color)
  94772. */
  94773. var Polygon = /** @class */ (function () {
  94774. /**
  94775. * Initializes the polygon
  94776. * @param vertices The vertices of the polygon
  94777. * @param shared The properties shared across all polygons
  94778. */
  94779. function Polygon(vertices, shared) {
  94780. this.vertices = vertices;
  94781. this.shared = shared;
  94782. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  94783. }
  94784. /**
  94785. * Clones, or makes a deep copy, or the polygon
  94786. */
  94787. Polygon.prototype.clone = function () {
  94788. var vertices = this.vertices.map(function (v) { return v.clone(); });
  94789. return new Polygon(vertices, this.shared);
  94790. };
  94791. /**
  94792. * Flips the faces of the polygon
  94793. */
  94794. Polygon.prototype.flip = function () {
  94795. this.vertices.reverse().map(function (v) { v.flip(); });
  94796. this.plane.flip();
  94797. };
  94798. return Polygon;
  94799. }());
  94800. /**
  94801. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  94802. * by picking a polygon to split along. That polygon (and all other coplanar
  94803. * polygons) are added directly to that node and the other polygons are added to
  94804. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  94805. * no distinction between internal and leaf nodes
  94806. */
  94807. var Node = /** @class */ (function () {
  94808. /**
  94809. * Initializes the node
  94810. * @param polygons A collection of polygons held in the node
  94811. */
  94812. function Node(polygons) {
  94813. this.plane = null;
  94814. this.front = null;
  94815. this.back = null;
  94816. this.polygons = new Array();
  94817. if (polygons) {
  94818. this.build(polygons);
  94819. }
  94820. }
  94821. /**
  94822. * Clones, or makes a deep copy, of the node
  94823. * @returns The cloned node
  94824. */
  94825. Node.prototype.clone = function () {
  94826. var node = new Node();
  94827. node.plane = this.plane && this.plane.clone();
  94828. node.front = this.front && this.front.clone();
  94829. node.back = this.back && this.back.clone();
  94830. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  94831. return node;
  94832. };
  94833. /**
  94834. * Convert solid space to empty space and empty space to solid space
  94835. */
  94836. Node.prototype.invert = function () {
  94837. for (var i = 0; i < this.polygons.length; i++) {
  94838. this.polygons[i].flip();
  94839. }
  94840. if (this.plane) {
  94841. this.plane.flip();
  94842. }
  94843. if (this.front) {
  94844. this.front.invert();
  94845. }
  94846. if (this.back) {
  94847. this.back.invert();
  94848. }
  94849. var temp = this.front;
  94850. this.front = this.back;
  94851. this.back = temp;
  94852. };
  94853. /**
  94854. * Recursively remove all polygons in `polygons` that are inside this BSP
  94855. * tree.
  94856. * @param polygons Polygons to remove from the BSP
  94857. * @returns Polygons clipped from the BSP
  94858. */
  94859. Node.prototype.clipPolygons = function (polygons) {
  94860. if (!this.plane) {
  94861. return polygons.slice();
  94862. }
  94863. var front = new Array(), back = new Array();
  94864. for (var i = 0; i < polygons.length; i++) {
  94865. this.plane.splitPolygon(polygons[i], front, back, front, back);
  94866. }
  94867. if (this.front) {
  94868. front = this.front.clipPolygons(front);
  94869. }
  94870. if (this.back) {
  94871. back = this.back.clipPolygons(back);
  94872. }
  94873. else {
  94874. back = [];
  94875. }
  94876. return front.concat(back);
  94877. };
  94878. /**
  94879. * Remove all polygons in this BSP tree that are inside the other BSP tree
  94880. * `bsp`.
  94881. * @param bsp BSP containing polygons to remove from this BSP
  94882. */
  94883. Node.prototype.clipTo = function (bsp) {
  94884. this.polygons = bsp.clipPolygons(this.polygons);
  94885. if (this.front) {
  94886. this.front.clipTo(bsp);
  94887. }
  94888. if (this.back) {
  94889. this.back.clipTo(bsp);
  94890. }
  94891. };
  94892. /**
  94893. * Return a list of all polygons in this BSP tree
  94894. * @returns List of all polygons in this BSP tree
  94895. */
  94896. Node.prototype.allPolygons = function () {
  94897. var polygons = this.polygons.slice();
  94898. if (this.front) {
  94899. polygons = polygons.concat(this.front.allPolygons());
  94900. }
  94901. if (this.back) {
  94902. polygons = polygons.concat(this.back.allPolygons());
  94903. }
  94904. return polygons;
  94905. };
  94906. /**
  94907. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  94908. * new polygons are filtered down to the bottom of the tree and become new
  94909. * nodes there. Each set of polygons is partitioned using the first polygon
  94910. * (no heuristic is used to pick a good split)
  94911. * @param polygons Polygons used to construct the BSP tree
  94912. */
  94913. Node.prototype.build = function (polygons) {
  94914. if (!polygons.length) {
  94915. return;
  94916. }
  94917. if (!this.plane) {
  94918. this.plane = polygons[0].plane.clone();
  94919. }
  94920. var front = new Array(), back = new Array();
  94921. for (var i = 0; i < polygons.length; i++) {
  94922. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  94923. }
  94924. if (front.length) {
  94925. if (!this.front) {
  94926. this.front = new Node();
  94927. }
  94928. this.front.build(front);
  94929. }
  94930. if (back.length) {
  94931. if (!this.back) {
  94932. this.back = new Node();
  94933. }
  94934. this.back.build(back);
  94935. }
  94936. };
  94937. return Node;
  94938. }());
  94939. /**
  94940. * Class for building Constructive Solid Geometry
  94941. */
  94942. var CSG = /** @class */ (function () {
  94943. function CSG() {
  94944. this.polygons = new Array();
  94945. }
  94946. /**
  94947. * Convert the BABYLON.Mesh to BABYLON.CSG
  94948. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  94949. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  94950. */
  94951. CSG.FromMesh = function (mesh) {
  94952. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  94953. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  94954. if (mesh instanceof BABYLON.Mesh) {
  94955. mesh.computeWorldMatrix(true);
  94956. matrix = mesh.getWorldMatrix();
  94957. meshPosition = mesh.position.clone();
  94958. meshRotation = mesh.rotation.clone();
  94959. if (mesh.rotationQuaternion) {
  94960. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  94961. }
  94962. meshScaling = mesh.scaling.clone();
  94963. }
  94964. else {
  94965. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  94966. }
  94967. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94968. var subMeshes = mesh.subMeshes;
  94969. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  94970. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  94971. vertices = [];
  94972. for (var j = 0; j < 3; j++) {
  94973. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  94974. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  94975. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  94976. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  94977. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  94978. vertex = new Vertex(position, normal, uv);
  94979. vertices.push(vertex);
  94980. }
  94981. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  94982. // To handle the case of degenerated triangle
  94983. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  94984. if (polygon.plane) {
  94985. polygons.push(polygon);
  94986. }
  94987. }
  94988. }
  94989. var csg = CSG.FromPolygons(polygons);
  94990. csg.matrix = matrix;
  94991. csg.position = meshPosition;
  94992. csg.rotation = meshRotation;
  94993. csg.scaling = meshScaling;
  94994. csg.rotationQuaternion = meshRotationQuaternion;
  94995. currentCSGMeshId++;
  94996. return csg;
  94997. };
  94998. /**
  94999. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  95000. * @param polygons Polygons used to construct a BABYLON.CSG solid
  95001. */
  95002. CSG.FromPolygons = function (polygons) {
  95003. var csg = new CSG();
  95004. csg.polygons = polygons;
  95005. return csg;
  95006. };
  95007. /**
  95008. * Clones, or makes a deep copy, of the BABYLON.CSG
  95009. * @returns A new BABYLON.CSG
  95010. */
  95011. CSG.prototype.clone = function () {
  95012. var csg = new CSG();
  95013. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  95014. csg.copyTransformAttributes(this);
  95015. return csg;
  95016. };
  95017. /**
  95018. * Unions this CSG with another CSG
  95019. * @param csg The CSG to union against this CSG
  95020. * @returns The unioned CSG
  95021. */
  95022. CSG.prototype.union = function (csg) {
  95023. var a = new Node(this.clone().polygons);
  95024. var b = new Node(csg.clone().polygons);
  95025. a.clipTo(b);
  95026. b.clipTo(a);
  95027. b.invert();
  95028. b.clipTo(a);
  95029. b.invert();
  95030. a.build(b.allPolygons());
  95031. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95032. };
  95033. /**
  95034. * Unions this CSG with another CSG in place
  95035. * @param csg The CSG to union against this CSG
  95036. */
  95037. CSG.prototype.unionInPlace = function (csg) {
  95038. var a = new Node(this.polygons);
  95039. var b = new Node(csg.polygons);
  95040. a.clipTo(b);
  95041. b.clipTo(a);
  95042. b.invert();
  95043. b.clipTo(a);
  95044. b.invert();
  95045. a.build(b.allPolygons());
  95046. this.polygons = a.allPolygons();
  95047. };
  95048. /**
  95049. * Subtracts this CSG with another CSG
  95050. * @param csg The CSG to subtract against this CSG
  95051. * @returns A new BABYLON.CSG
  95052. */
  95053. CSG.prototype.subtract = function (csg) {
  95054. var a = new Node(this.clone().polygons);
  95055. var b = new Node(csg.clone().polygons);
  95056. a.invert();
  95057. a.clipTo(b);
  95058. b.clipTo(a);
  95059. b.invert();
  95060. b.clipTo(a);
  95061. b.invert();
  95062. a.build(b.allPolygons());
  95063. a.invert();
  95064. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95065. };
  95066. /**
  95067. * Subtracts this CSG with another CSG in place
  95068. * @param csg The CSG to subtact against this CSG
  95069. */
  95070. CSG.prototype.subtractInPlace = function (csg) {
  95071. var a = new Node(this.polygons);
  95072. var b = new Node(csg.polygons);
  95073. a.invert();
  95074. a.clipTo(b);
  95075. b.clipTo(a);
  95076. b.invert();
  95077. b.clipTo(a);
  95078. b.invert();
  95079. a.build(b.allPolygons());
  95080. a.invert();
  95081. this.polygons = a.allPolygons();
  95082. };
  95083. /**
  95084. * Intersect this CSG with another CSG
  95085. * @param csg The CSG to intersect against this CSG
  95086. * @returns A new BABYLON.CSG
  95087. */
  95088. CSG.prototype.intersect = function (csg) {
  95089. var a = new Node(this.clone().polygons);
  95090. var b = new Node(csg.clone().polygons);
  95091. a.invert();
  95092. b.clipTo(a);
  95093. b.invert();
  95094. a.clipTo(b);
  95095. b.clipTo(a);
  95096. a.build(b.allPolygons());
  95097. a.invert();
  95098. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95099. };
  95100. /**
  95101. * Intersects this CSG with another CSG in place
  95102. * @param csg The CSG to intersect against this CSG
  95103. */
  95104. CSG.prototype.intersectInPlace = function (csg) {
  95105. var a = new Node(this.polygons);
  95106. var b = new Node(csg.polygons);
  95107. a.invert();
  95108. b.clipTo(a);
  95109. b.invert();
  95110. a.clipTo(b);
  95111. b.clipTo(a);
  95112. a.build(b.allPolygons());
  95113. a.invert();
  95114. this.polygons = a.allPolygons();
  95115. };
  95116. /**
  95117. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  95118. * not modified.
  95119. * @returns A new BABYLON.CSG solid with solid and empty space switched
  95120. */
  95121. CSG.prototype.inverse = function () {
  95122. var csg = this.clone();
  95123. csg.inverseInPlace();
  95124. return csg;
  95125. };
  95126. /**
  95127. * Inverses the BABYLON.CSG in place
  95128. */
  95129. CSG.prototype.inverseInPlace = function () {
  95130. this.polygons.map(function (p) { p.flip(); });
  95131. };
  95132. /**
  95133. * This is used to keep meshes transformations so they can be restored
  95134. * when we build back a Babylon Mesh
  95135. * NB : All CSG operations are performed in world coordinates
  95136. * @param csg The BABYLON.CSG to copy the transform attributes from
  95137. * @returns This BABYLON.CSG
  95138. */
  95139. CSG.prototype.copyTransformAttributes = function (csg) {
  95140. this.matrix = csg.matrix;
  95141. this.position = csg.position;
  95142. this.rotation = csg.rotation;
  95143. this.scaling = csg.scaling;
  95144. this.rotationQuaternion = csg.rotationQuaternion;
  95145. return this;
  95146. };
  95147. /**
  95148. * Build Raw mesh from CSG
  95149. * Coordinates here are in world space
  95150. * @param name The name of the mesh geometry
  95151. * @param scene The BABYLON.Scene
  95152. * @param keepSubMeshes Specifies if the submeshes should be kept
  95153. * @returns A new BABYLON.Mesh
  95154. */
  95155. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  95156. var matrix = this.matrix.clone();
  95157. matrix.invert();
  95158. 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;
  95159. if (keepSubMeshes) {
  95160. // Sort Polygons, since subMeshes are indices range
  95161. polygons.sort(function (a, b) {
  95162. if (a.shared.meshId === b.shared.meshId) {
  95163. return a.shared.subMeshId - b.shared.subMeshId;
  95164. }
  95165. else {
  95166. return a.shared.meshId - b.shared.meshId;
  95167. }
  95168. });
  95169. }
  95170. for (var i = 0, il = polygons.length; i < il; i++) {
  95171. polygon = polygons[i];
  95172. // Building SubMeshes
  95173. if (!subMesh_dict[polygon.shared.meshId]) {
  95174. subMesh_dict[polygon.shared.meshId] = {};
  95175. }
  95176. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  95177. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  95178. indexStart: +Infinity,
  95179. indexEnd: -Infinity,
  95180. materialIndex: polygon.shared.materialIndex
  95181. };
  95182. }
  95183. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  95184. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  95185. polygonIndices[0] = 0;
  95186. polygonIndices[1] = j - 1;
  95187. polygonIndices[2] = j;
  95188. for (var k = 0; k < 3; k++) {
  95189. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  95190. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  95191. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  95192. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  95193. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  95194. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  95195. // Check if 2 points can be merged
  95196. if (!(typeof vertex_idx !== 'undefined' &&
  95197. normals[vertex_idx * 3] === localNormal.x &&
  95198. normals[vertex_idx * 3 + 1] === localNormal.y &&
  95199. normals[vertex_idx * 3 + 2] === localNormal.z &&
  95200. uvs[vertex_idx * 2] === uv.x &&
  95201. uvs[vertex_idx * 2 + 1] === uv.y)) {
  95202. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  95203. uvs.push(uv.x, uv.y);
  95204. normals.push(normal.x, normal.y, normal.z);
  95205. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  95206. }
  95207. indices.push(vertex_idx);
  95208. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  95209. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  95210. currentIndex++;
  95211. }
  95212. }
  95213. }
  95214. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  95215. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95216. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  95217. mesh.setIndices(indices, null);
  95218. if (keepSubMeshes) {
  95219. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  95220. var materialIndexOffset = 0, materialMaxIndex;
  95221. mesh.subMeshes = new Array();
  95222. for (var m in subMesh_dict) {
  95223. materialMaxIndex = -1;
  95224. for (var sm in subMesh_dict[m]) {
  95225. subMesh_obj = subMesh_dict[m][sm];
  95226. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  95227. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  95228. }
  95229. materialIndexOffset += ++materialMaxIndex;
  95230. }
  95231. }
  95232. return mesh;
  95233. };
  95234. /**
  95235. * Build Mesh from CSG taking material and transforms into account
  95236. * @param name The name of the BABYLON.Mesh
  95237. * @param material The material of the BABYLON.Mesh
  95238. * @param scene The BABYLON.Scene
  95239. * @param keepSubMeshes Specifies if submeshes should be kept
  95240. * @returns The new BABYLON.Mesh
  95241. */
  95242. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  95243. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  95244. mesh.material = material;
  95245. mesh.position.copyFrom(this.position);
  95246. mesh.rotation.copyFrom(this.rotation);
  95247. if (this.rotationQuaternion) {
  95248. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  95249. }
  95250. mesh.scaling.copyFrom(this.scaling);
  95251. mesh.computeWorldMatrix(true);
  95252. return mesh;
  95253. };
  95254. return CSG;
  95255. }());
  95256. BABYLON.CSG = CSG;
  95257. })(BABYLON || (BABYLON = {}));
  95258. //# sourceMappingURL=babylon.csg.js.map
  95259. var BABYLON;
  95260. (function (BABYLON) {
  95261. /**
  95262. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95263. * It controls one of the indiviual texture used in the effect.
  95264. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95265. */
  95266. var LensFlare = /** @class */ (function () {
  95267. /**
  95268. * Instantiates a new Lens Flare.
  95269. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95270. * It controls one of the indiviual texture used in the effect.
  95271. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95272. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  95273. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  95274. * @param color Define the lens color
  95275. * @param imgUrl Define the lens texture url
  95276. * @param system Define the `lensFlareSystem` this flare is part of
  95277. */
  95278. function LensFlare(
  95279. /**
  95280. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  95281. */
  95282. size,
  95283. /**
  95284. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  95285. */
  95286. position, color, imgUrl, system) {
  95287. this.size = size;
  95288. this.position = position;
  95289. /**
  95290. * Define the alpha mode to render this particular lens.
  95291. */
  95292. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  95293. this.color = color || new BABYLON.Color3(1, 1, 1);
  95294. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  95295. this._system = system;
  95296. system.lensFlares.push(this);
  95297. }
  95298. /**
  95299. * Creates a new Lens Flare.
  95300. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95301. * It controls one of the indiviual texture used in the effect.
  95302. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95303. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  95304. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  95305. * @param color Define the lens color
  95306. * @param imgUrl Define the lens texture url
  95307. * @param system Define the `lensFlareSystem` this flare is part of
  95308. * @returns The newly created Lens Flare
  95309. */
  95310. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  95311. return new LensFlare(size, position, color, imgUrl, system);
  95312. };
  95313. /**
  95314. * Dispose and release the lens flare with its associated resources.
  95315. */
  95316. LensFlare.prototype.dispose = function () {
  95317. if (this.texture) {
  95318. this.texture.dispose();
  95319. }
  95320. // Remove from scene
  95321. var index = this._system.lensFlares.indexOf(this);
  95322. this._system.lensFlares.splice(index, 1);
  95323. };
  95324. return LensFlare;
  95325. }());
  95326. BABYLON.LensFlare = LensFlare;
  95327. })(BABYLON || (BABYLON = {}));
  95328. //# sourceMappingURL=babylon.lensFlare.js.map
  95329. var BABYLON;
  95330. (function (BABYLON) {
  95331. // Adds the parser to the scene parsers.
  95332. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  95333. // Lens flares
  95334. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  95335. if (!container.lensFlareSystems) {
  95336. container.lensFlareSystems = new Array();
  95337. }
  95338. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  95339. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  95340. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  95341. container.lensFlareSystems.push(lf);
  95342. }
  95343. }
  95344. });
  95345. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  95346. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95347. if (this.lensFlareSystems[index].name === name) {
  95348. return this.lensFlareSystems[index];
  95349. }
  95350. }
  95351. return null;
  95352. };
  95353. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  95354. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95355. if (this.lensFlareSystems[index].id === id) {
  95356. return this.lensFlareSystems[index];
  95357. }
  95358. }
  95359. return null;
  95360. };
  95361. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  95362. var index = this.lensFlareSystems.indexOf(toRemove);
  95363. if (index !== -1) {
  95364. this.lensFlareSystems.splice(index, 1);
  95365. }
  95366. return index;
  95367. };
  95368. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  95369. this.lensFlareSystems.push(newLensFlareSystem);
  95370. };
  95371. /**
  95372. * Defines the lens flare scene component responsible to manage any lens flares
  95373. * in a given scene.
  95374. */
  95375. var LensFlareSystemSceneComponent = /** @class */ (function () {
  95376. /**
  95377. * Creates a new instance of the component for the given scene
  95378. * @param scene Defines the scene to register the component in
  95379. */
  95380. function LensFlareSystemSceneComponent(scene) {
  95381. /**
  95382. * The component name helpfull to identify the component in the list of scene components.
  95383. */
  95384. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  95385. this.scene = scene;
  95386. scene.lensFlareSystems = new Array();
  95387. }
  95388. /**
  95389. * Registers the component in a given scene
  95390. */
  95391. LensFlareSystemSceneComponent.prototype.register = function () {
  95392. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  95393. };
  95394. /**
  95395. * Rebuilds the elements related to this component in case of
  95396. * context lost for instance.
  95397. */
  95398. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  95399. // Nothing to do for lens flare
  95400. };
  95401. /**
  95402. * Adds all the element from the container to the scene
  95403. * @param container the container holding the elements
  95404. */
  95405. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  95406. var _this = this;
  95407. if (!container.lensFlareSystems) {
  95408. return;
  95409. }
  95410. container.lensFlareSystems.forEach(function (o) {
  95411. _this.scene.addLensFlareSystem(o);
  95412. });
  95413. };
  95414. /**
  95415. * Removes all the elements in the container from the scene
  95416. * @param container contains the elements to remove
  95417. */
  95418. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  95419. var _this = this;
  95420. if (!container.lensFlareSystems) {
  95421. return;
  95422. }
  95423. container.lensFlareSystems.forEach(function (o) {
  95424. _this.scene.removeLensFlareSystem(o);
  95425. });
  95426. };
  95427. /**
  95428. * Serializes the component data to the specified json object
  95429. * @param serializationObject The object to serialize to
  95430. */
  95431. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  95432. // Lens flares
  95433. serializationObject.lensFlareSystems = [];
  95434. var lensFlareSystems = this.scene.lensFlareSystems;
  95435. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  95436. var lensFlareSystem = lensFlareSystems_1[_i];
  95437. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  95438. }
  95439. };
  95440. /**
  95441. * Disposes the component and the associated ressources.
  95442. */
  95443. LensFlareSystemSceneComponent.prototype.dispose = function () {
  95444. var lensFlareSystems = this.scene.lensFlareSystems;
  95445. while (lensFlareSystems.length) {
  95446. lensFlareSystems[0].dispose();
  95447. }
  95448. };
  95449. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  95450. // Lens flares
  95451. if (this.scene.lensFlaresEnabled) {
  95452. var lensFlareSystems = this.scene.lensFlareSystems;
  95453. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95454. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  95455. var lensFlareSystem = lensFlareSystems_2[_i];
  95456. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  95457. lensFlareSystem.render();
  95458. }
  95459. }
  95460. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95461. }
  95462. };
  95463. return LensFlareSystemSceneComponent;
  95464. }());
  95465. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  95466. })(BABYLON || (BABYLON = {}));
  95467. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  95468. var BABYLON;
  95469. (function (BABYLON) {
  95470. /**
  95471. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95472. * It is usually composed of several `BABYLON.lensFlare`.
  95473. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95474. */
  95475. var LensFlareSystem = /** @class */ (function () {
  95476. /**
  95477. * Instantiates a lens flare system.
  95478. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95479. * It is usually composed of several `BABYLON.lensFlare`.
  95480. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95481. * @param name Define the name of the lens flare system in the scene
  95482. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  95483. * @param scene Define the scene the lens flare system belongs to
  95484. */
  95485. function LensFlareSystem(
  95486. /**
  95487. * Define the name of the lens flare system
  95488. */
  95489. name, emitter, scene) {
  95490. this.name = name;
  95491. /**
  95492. * List of lens flares used in this system.
  95493. */
  95494. this.lensFlares = new Array();
  95495. /**
  95496. * Define a limit from the border the lens flare can be visible.
  95497. */
  95498. this.borderLimit = 300;
  95499. /**
  95500. * Define a viewport border we do not want to see the lens flare in.
  95501. */
  95502. this.viewportBorder = 0;
  95503. /**
  95504. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  95505. */
  95506. this.layerMask = 0x0FFFFFFF;
  95507. this._vertexBuffers = {};
  95508. this._isEnabled = true;
  95509. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95510. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  95511. if (!component) {
  95512. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  95513. scene._addComponent(component);
  95514. }
  95515. this._emitter = emitter;
  95516. this.id = name;
  95517. scene.lensFlareSystems.push(this);
  95518. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  95519. var engine = scene.getEngine();
  95520. // VBO
  95521. var vertices = [];
  95522. vertices.push(1, 1);
  95523. vertices.push(-1, 1);
  95524. vertices.push(-1, -1);
  95525. vertices.push(1, -1);
  95526. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95527. // Indices
  95528. var indices = [];
  95529. indices.push(0);
  95530. indices.push(1);
  95531. indices.push(2);
  95532. indices.push(0);
  95533. indices.push(2);
  95534. indices.push(3);
  95535. this._indexBuffer = engine.createIndexBuffer(indices);
  95536. // Effects
  95537. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  95538. }
  95539. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  95540. /**
  95541. * Define if the lens flare system is enabled.
  95542. */
  95543. get: function () {
  95544. return this._isEnabled;
  95545. },
  95546. set: function (value) {
  95547. this._isEnabled = value;
  95548. },
  95549. enumerable: true,
  95550. configurable: true
  95551. });
  95552. /**
  95553. * Get the scene the effects belongs to.
  95554. * @returns the scene holding the lens flare system
  95555. */
  95556. LensFlareSystem.prototype.getScene = function () {
  95557. return this._scene;
  95558. };
  95559. /**
  95560. * Get the emitter of the lens flare system.
  95561. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95562. * @returns the emitter of the lens flare system
  95563. */
  95564. LensFlareSystem.prototype.getEmitter = function () {
  95565. return this._emitter;
  95566. };
  95567. /**
  95568. * Set the emitter of the lens flare system.
  95569. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95570. * @param newEmitter Define the new emitter of the system
  95571. */
  95572. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  95573. this._emitter = newEmitter;
  95574. };
  95575. /**
  95576. * Get the lens flare system emitter position.
  95577. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  95578. * @returns the position
  95579. */
  95580. LensFlareSystem.prototype.getEmitterPosition = function () {
  95581. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  95582. };
  95583. /**
  95584. * @hidden
  95585. */
  95586. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  95587. var position = this.getEmitterPosition();
  95588. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  95589. this._positionX = position.x;
  95590. this._positionY = position.y;
  95591. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  95592. if (this.viewportBorder > 0) {
  95593. globalViewport.x -= this.viewportBorder;
  95594. globalViewport.y -= this.viewportBorder;
  95595. globalViewport.width += this.viewportBorder * 2;
  95596. globalViewport.height += this.viewportBorder * 2;
  95597. position.x += this.viewportBorder;
  95598. position.y += this.viewportBorder;
  95599. this._positionX += this.viewportBorder;
  95600. this._positionY += this.viewportBorder;
  95601. }
  95602. if (position.z > 0) {
  95603. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  95604. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  95605. return true;
  95606. }
  95607. }
  95608. return true;
  95609. }
  95610. return false;
  95611. };
  95612. /** @hidden */
  95613. LensFlareSystem.prototype._isVisible = function () {
  95614. if (!this._isEnabled || !this._scene.activeCamera) {
  95615. return false;
  95616. }
  95617. var emitterPosition = this.getEmitterPosition();
  95618. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  95619. var distance = direction.length();
  95620. direction.normalize();
  95621. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  95622. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  95623. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  95624. };
  95625. /**
  95626. * @hidden
  95627. */
  95628. LensFlareSystem.prototype.render = function () {
  95629. if (!this._effect.isReady() || !this._scene.activeCamera) {
  95630. return false;
  95631. }
  95632. var engine = this._scene.getEngine();
  95633. var viewport = this._scene.activeCamera.viewport;
  95634. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  95635. // Position
  95636. if (!this.computeEffectivePosition(globalViewport)) {
  95637. return false;
  95638. }
  95639. // Visibility
  95640. if (!this._isVisible()) {
  95641. return false;
  95642. }
  95643. // Intensity
  95644. var awayX;
  95645. var awayY;
  95646. if (this._positionX < this.borderLimit + globalViewport.x) {
  95647. awayX = this.borderLimit + globalViewport.x - this._positionX;
  95648. }
  95649. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  95650. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  95651. }
  95652. else {
  95653. awayX = 0;
  95654. }
  95655. if (this._positionY < this.borderLimit + globalViewport.y) {
  95656. awayY = this.borderLimit + globalViewport.y - this._positionY;
  95657. }
  95658. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  95659. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  95660. }
  95661. else {
  95662. awayY = 0;
  95663. }
  95664. var away = (awayX > awayY) ? awayX : awayY;
  95665. away -= this.viewportBorder;
  95666. if (away > this.borderLimit) {
  95667. away = this.borderLimit;
  95668. }
  95669. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  95670. if (intensity < 0) {
  95671. return false;
  95672. }
  95673. if (intensity > 1.0) {
  95674. intensity = 1.0;
  95675. }
  95676. if (this.viewportBorder > 0) {
  95677. globalViewport.x += this.viewportBorder;
  95678. globalViewport.y += this.viewportBorder;
  95679. globalViewport.width -= this.viewportBorder * 2;
  95680. globalViewport.height -= this.viewportBorder * 2;
  95681. this._positionX -= this.viewportBorder;
  95682. this._positionY -= this.viewportBorder;
  95683. }
  95684. // Position
  95685. var centerX = globalViewport.x + globalViewport.width / 2;
  95686. var centerY = globalViewport.y + globalViewport.height / 2;
  95687. var distX = centerX - this._positionX;
  95688. var distY = centerY - this._positionY;
  95689. // Effects
  95690. engine.enableEffect(this._effect);
  95691. engine.setState(false);
  95692. engine.setDepthBuffer(false);
  95693. // VBOs
  95694. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  95695. // Flares
  95696. for (var index = 0; index < this.lensFlares.length; index++) {
  95697. var flare = this.lensFlares[index];
  95698. engine.setAlphaMode(flare.alphaMode);
  95699. var x = centerX - (distX * flare.position);
  95700. var y = centerY - (distY * flare.position);
  95701. var cw = flare.size;
  95702. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  95703. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  95704. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  95705. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  95706. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  95707. // Texture
  95708. this._effect.setTexture("textureSampler", flare.texture);
  95709. // Color
  95710. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  95711. // Draw order
  95712. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95713. }
  95714. engine.setDepthBuffer(true);
  95715. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  95716. return true;
  95717. };
  95718. /**
  95719. * Dispose and release the lens flare with its associated resources.
  95720. */
  95721. LensFlareSystem.prototype.dispose = function () {
  95722. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95723. if (vertexBuffer) {
  95724. vertexBuffer.dispose();
  95725. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95726. }
  95727. if (this._indexBuffer) {
  95728. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95729. this._indexBuffer = null;
  95730. }
  95731. while (this.lensFlares.length) {
  95732. this.lensFlares[0].dispose();
  95733. }
  95734. // Remove from scene
  95735. var index = this._scene.lensFlareSystems.indexOf(this);
  95736. this._scene.lensFlareSystems.splice(index, 1);
  95737. };
  95738. /**
  95739. * Parse a lens flare system from a JSON repressentation
  95740. * @param parsedLensFlareSystem Define the JSON to parse
  95741. * @param scene Define the scene the parsed system should be instantiated in
  95742. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  95743. * @returns the parsed system
  95744. */
  95745. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  95746. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  95747. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  95748. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  95749. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  95750. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  95751. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  95752. var parsedFlare = parsedLensFlareSystem.flares[index];
  95753. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  95754. }
  95755. return lensFlareSystem;
  95756. };
  95757. /**
  95758. * Serialize the current Lens Flare System into a JSON representation.
  95759. * @returns the serialized JSON
  95760. */
  95761. LensFlareSystem.prototype.serialize = function () {
  95762. var serializationObject = {};
  95763. serializationObject.id = this.id;
  95764. serializationObject.name = this.name;
  95765. serializationObject.emitterId = this.getEmitter().id;
  95766. serializationObject.borderLimit = this.borderLimit;
  95767. serializationObject.flares = [];
  95768. for (var index = 0; index < this.lensFlares.length; index++) {
  95769. var flare = this.lensFlares[index];
  95770. serializationObject.flares.push({
  95771. size: flare.size,
  95772. position: flare.position,
  95773. color: flare.color.asArray(),
  95774. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  95775. });
  95776. }
  95777. return serializationObject;
  95778. };
  95779. return LensFlareSystem;
  95780. }());
  95781. BABYLON.LensFlareSystem = LensFlareSystem;
  95782. })(BABYLON || (BABYLON = {}));
  95783. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  95784. var BABYLON;
  95785. (function (BABYLON) {
  95786. /**
  95787. * This is a holder class for the physics joint created by the physics plugin
  95788. * It holds a set of functions to control the underlying joint
  95789. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95790. */
  95791. var PhysicsJoint = /** @class */ (function () {
  95792. /**
  95793. * Initializes the physics joint
  95794. * @param type The type of the physics joint
  95795. * @param jointData The data for the physics joint
  95796. */
  95797. function PhysicsJoint(
  95798. /**
  95799. * The type of the physics joint
  95800. */
  95801. type,
  95802. /**
  95803. * The data for the physics joint
  95804. */
  95805. jointData) {
  95806. this.type = type;
  95807. this.jointData = jointData;
  95808. jointData.nativeParams = jointData.nativeParams || {};
  95809. }
  95810. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  95811. /**
  95812. * Gets the physics joint
  95813. */
  95814. get: function () {
  95815. return this._physicsJoint;
  95816. },
  95817. /**
  95818. * Sets the physics joint
  95819. */
  95820. set: function (newJoint) {
  95821. if (this._physicsJoint) {
  95822. //remove from the wolrd
  95823. }
  95824. this._physicsJoint = newJoint;
  95825. },
  95826. enumerable: true,
  95827. configurable: true
  95828. });
  95829. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  95830. /**
  95831. * Sets the physics plugin
  95832. */
  95833. set: function (physicsPlugin) {
  95834. this._physicsPlugin = physicsPlugin;
  95835. },
  95836. enumerable: true,
  95837. configurable: true
  95838. });
  95839. /**
  95840. * Execute a function that is physics-plugin specific.
  95841. * @param {Function} func the function that will be executed.
  95842. * It accepts two parameters: the physics world and the physics joint
  95843. */
  95844. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  95845. func(this._physicsPlugin.world, this._physicsJoint);
  95846. };
  95847. //TODO check if the native joints are the same
  95848. //Joint Types
  95849. /**
  95850. * Distance-Joint type
  95851. */
  95852. PhysicsJoint.DistanceJoint = 0;
  95853. /**
  95854. * Hinge-Joint type
  95855. */
  95856. PhysicsJoint.HingeJoint = 1;
  95857. /**
  95858. * Ball-and-Socket joint type
  95859. */
  95860. PhysicsJoint.BallAndSocketJoint = 2;
  95861. /**
  95862. * Wheel-Joint type
  95863. */
  95864. PhysicsJoint.WheelJoint = 3;
  95865. /**
  95866. * Slider-Joint type
  95867. */
  95868. PhysicsJoint.SliderJoint = 4;
  95869. //OIMO
  95870. /**
  95871. * Prismatic-Joint type
  95872. */
  95873. PhysicsJoint.PrismaticJoint = 5;
  95874. //
  95875. /**
  95876. * Universal-Joint type
  95877. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  95878. */
  95879. PhysicsJoint.UniversalJoint = 6;
  95880. /**
  95881. * Hinge-Joint 2 type
  95882. */
  95883. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  95884. //Cannon
  95885. /**
  95886. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  95887. */
  95888. PhysicsJoint.PointToPointJoint = 8;
  95889. //Cannon only at the moment
  95890. /**
  95891. * Spring-Joint type
  95892. */
  95893. PhysicsJoint.SpringJoint = 9;
  95894. /**
  95895. * Lock-Joint type
  95896. */
  95897. PhysicsJoint.LockJoint = 10;
  95898. return PhysicsJoint;
  95899. }());
  95900. BABYLON.PhysicsJoint = PhysicsJoint;
  95901. /**
  95902. * A class representing a physics distance joint
  95903. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95904. */
  95905. var DistanceJoint = /** @class */ (function (_super) {
  95906. __extends(DistanceJoint, _super);
  95907. /**
  95908. *
  95909. * @param jointData The data for the Distance-Joint
  95910. */
  95911. function DistanceJoint(jointData) {
  95912. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  95913. }
  95914. /**
  95915. * Update the predefined distance.
  95916. * @param maxDistance The maximum preferred distance
  95917. * @param minDistance The minimum preferred distance
  95918. */
  95919. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  95920. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  95921. };
  95922. return DistanceJoint;
  95923. }(PhysicsJoint));
  95924. BABYLON.DistanceJoint = DistanceJoint;
  95925. /**
  95926. * Represents a Motor-Enabled Joint
  95927. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95928. */
  95929. var MotorEnabledJoint = /** @class */ (function (_super) {
  95930. __extends(MotorEnabledJoint, _super);
  95931. /**
  95932. * Initializes the Motor-Enabled Joint
  95933. * @param type The type of the joint
  95934. * @param jointData The physica joint data for the joint
  95935. */
  95936. function MotorEnabledJoint(type, jointData) {
  95937. return _super.call(this, type, jointData) || this;
  95938. }
  95939. /**
  95940. * Set the motor values.
  95941. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95942. * @param force the force to apply
  95943. * @param maxForce max force for this motor.
  95944. */
  95945. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  95946. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95947. };
  95948. /**
  95949. * Set the motor's limits.
  95950. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95951. * @param upperLimit The upper limit of the motor
  95952. * @param lowerLimit The lower limit of the motor
  95953. */
  95954. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95955. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95956. };
  95957. return MotorEnabledJoint;
  95958. }(PhysicsJoint));
  95959. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  95960. /**
  95961. * This class represents a single physics Hinge-Joint
  95962. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95963. */
  95964. var HingeJoint = /** @class */ (function (_super) {
  95965. __extends(HingeJoint, _super);
  95966. /**
  95967. * Initializes the Hinge-Joint
  95968. * @param jointData The joint data for the Hinge-Joint
  95969. */
  95970. function HingeJoint(jointData) {
  95971. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  95972. }
  95973. /**
  95974. * Set the motor values.
  95975. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95976. * @param {number} force the force to apply
  95977. * @param {number} maxForce max force for this motor.
  95978. */
  95979. HingeJoint.prototype.setMotor = function (force, maxForce) {
  95980. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  95981. };
  95982. /**
  95983. * Set the motor's limits.
  95984. * Attention, this function is plugin specific. Engines won't react 100% the same.
  95985. * @param upperLimit The upper limit of the motor
  95986. * @param lowerLimit The lower limit of the motor
  95987. */
  95988. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  95989. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  95990. };
  95991. return HingeJoint;
  95992. }(MotorEnabledJoint));
  95993. BABYLON.HingeJoint = HingeJoint;
  95994. /**
  95995. * This class represents a dual hinge physics joint (same as wheel joint)
  95996. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95997. */
  95998. var Hinge2Joint = /** @class */ (function (_super) {
  95999. __extends(Hinge2Joint, _super);
  96000. /**
  96001. * Initializes the Hinge2-Joint
  96002. * @param jointData The joint data for the Hinge2-Joint
  96003. */
  96004. function Hinge2Joint(jointData) {
  96005. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  96006. }
  96007. /**
  96008. * Set the motor values.
  96009. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96010. * @param {number} force the force to apply
  96011. * @param {number} maxForce max force for this motor.
  96012. * @param {motorIndex} the motor's index, 0 or 1.
  96013. */
  96014. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  96015. if (motorIndex === void 0) { motorIndex = 0; }
  96016. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  96017. };
  96018. /**
  96019. * Set the motor limits.
  96020. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96021. * @param {number} upperLimit the upper limit
  96022. * @param {number} lowerLimit lower limit
  96023. * @param {motorIndex} the motor's index, 0 or 1.
  96024. */
  96025. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  96026. if (motorIndex === void 0) { motorIndex = 0; }
  96027. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  96028. };
  96029. return Hinge2Joint;
  96030. }(MotorEnabledJoint));
  96031. BABYLON.Hinge2Joint = Hinge2Joint;
  96032. })(BABYLON || (BABYLON = {}));
  96033. //# sourceMappingURL=babylon.physicsJoint.js.map
  96034. var BABYLON;
  96035. (function (BABYLON) {
  96036. /**
  96037. * Represents a physics imposter
  96038. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96039. */
  96040. var PhysicsImpostor = /** @class */ (function () {
  96041. /**
  96042. * Initializes the physics imposter
  96043. * @param object The physics-enabled object used as the physics imposter
  96044. * @param type The type of the physics imposter
  96045. * @param _options The options for the physics imposter
  96046. * @param _scene The Babylon scene
  96047. */
  96048. function PhysicsImpostor(
  96049. /**
  96050. * The physics-enabled object used as the physics imposter
  96051. */
  96052. object,
  96053. /**
  96054. * The type of the physics imposter
  96055. */
  96056. type, _options, _scene) {
  96057. if (_options === void 0) { _options = { mass: 0 }; }
  96058. var _this = this;
  96059. this.object = object;
  96060. this.type = type;
  96061. this._options = _options;
  96062. this._scene = _scene;
  96063. this._bodyUpdateRequired = false;
  96064. this._onBeforePhysicsStepCallbacks = new Array();
  96065. this._onAfterPhysicsStepCallbacks = new Array();
  96066. this._onPhysicsCollideCallbacks = [];
  96067. this._deltaPosition = BABYLON.Vector3.Zero();
  96068. this._isDisposed = false;
  96069. //temp variables for parent rotation calculations
  96070. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  96071. this._tmpQuat = new BABYLON.Quaternion();
  96072. this._tmpQuat2 = new BABYLON.Quaternion();
  96073. /**
  96074. * this function is executed by the physics engine.
  96075. */
  96076. this.beforeStep = function () {
  96077. if (!_this._physicsEngine) {
  96078. return;
  96079. }
  96080. _this.object.translate(_this._deltaPosition, -1);
  96081. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  96082. _this.object.computeWorldMatrix(false);
  96083. if (_this.object.parent && _this.object.rotationQuaternion) {
  96084. _this.getParentsRotation();
  96085. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  96086. }
  96087. else {
  96088. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  96089. }
  96090. if (!_this._options.disableBidirectionalTransformation) {
  96091. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  96092. }
  96093. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  96094. func(_this);
  96095. });
  96096. };
  96097. /**
  96098. * this function is executed by the physics engine
  96099. */
  96100. this.afterStep = function () {
  96101. if (!_this._physicsEngine) {
  96102. return;
  96103. }
  96104. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  96105. func(_this);
  96106. });
  96107. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  96108. // object has now its world rotation. needs to be converted to local.
  96109. if (_this.object.parent && _this.object.rotationQuaternion) {
  96110. _this.getParentsRotation();
  96111. _this._tmpQuat.conjugateInPlace();
  96112. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  96113. }
  96114. // take the position set and make it the absolute position of this object.
  96115. _this.object.setAbsolutePosition(_this.object.position);
  96116. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  96117. _this.object.translate(_this._deltaPosition, 1);
  96118. };
  96119. /**
  96120. * Legacy collision detection event support
  96121. */
  96122. this.onCollideEvent = null;
  96123. /**
  96124. * event and body object due to cannon's event-based architecture.
  96125. */
  96126. this.onCollide = function (e) {
  96127. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  96128. return;
  96129. }
  96130. if (!_this._physicsEngine) {
  96131. return;
  96132. }
  96133. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  96134. if (otherImpostor) {
  96135. // Legacy collision detection event support
  96136. if (_this.onCollideEvent) {
  96137. _this.onCollideEvent(_this, otherImpostor);
  96138. }
  96139. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  96140. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  96141. }).forEach(function (obj) {
  96142. obj.callback(_this, otherImpostor);
  96143. });
  96144. }
  96145. };
  96146. //sanity check!
  96147. if (!this.object) {
  96148. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  96149. return;
  96150. }
  96151. //legacy support for old syntax.
  96152. if (!this._scene && object.getScene) {
  96153. this._scene = object.getScene();
  96154. }
  96155. if (!this._scene) {
  96156. return;
  96157. }
  96158. this._physicsEngine = this._scene.getPhysicsEngine();
  96159. if (!this._physicsEngine) {
  96160. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  96161. }
  96162. else {
  96163. //set the object's quaternion, if not set
  96164. if (!this.object.rotationQuaternion) {
  96165. if (this.object.rotation) {
  96166. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  96167. }
  96168. else {
  96169. this.object.rotationQuaternion = new BABYLON.Quaternion();
  96170. }
  96171. }
  96172. //default options params
  96173. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  96174. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  96175. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  96176. this._joints = [];
  96177. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  96178. if (!this.object.parent || this._options.ignoreParent) {
  96179. this._init();
  96180. }
  96181. else if (this.object.parent.physicsImpostor) {
  96182. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  96183. }
  96184. }
  96185. }
  96186. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  96187. /**
  96188. * Specifies if the physics imposter is disposed
  96189. */
  96190. get: function () {
  96191. return this._isDisposed;
  96192. },
  96193. enumerable: true,
  96194. configurable: true
  96195. });
  96196. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  96197. /**
  96198. * Gets the mass of the physics imposter
  96199. */
  96200. get: function () {
  96201. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  96202. },
  96203. set: function (value) {
  96204. this.setMass(value);
  96205. },
  96206. enumerable: true,
  96207. configurable: true
  96208. });
  96209. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  96210. /**
  96211. * Gets the coefficient of friction
  96212. */
  96213. get: function () {
  96214. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  96215. },
  96216. /**
  96217. * Sets the coefficient of friction
  96218. */
  96219. set: function (value) {
  96220. if (!this._physicsEngine) {
  96221. return;
  96222. }
  96223. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  96224. },
  96225. enumerable: true,
  96226. configurable: true
  96227. });
  96228. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  96229. /**
  96230. * Gets the coefficient of restitution
  96231. */
  96232. get: function () {
  96233. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  96234. },
  96235. /**
  96236. * Sets the coefficient of restitution
  96237. */
  96238. set: function (value) {
  96239. if (!this._physicsEngine) {
  96240. return;
  96241. }
  96242. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  96243. },
  96244. enumerable: true,
  96245. configurable: true
  96246. });
  96247. /**
  96248. * This function will completly initialize this impostor.
  96249. * It will create a new body - but only if this mesh has no parent.
  96250. * If it has, this impostor will not be used other than to define the impostor
  96251. * of the child mesh.
  96252. * @hidden
  96253. */
  96254. PhysicsImpostor.prototype._init = function () {
  96255. if (!this._physicsEngine) {
  96256. return;
  96257. }
  96258. this._physicsEngine.removeImpostor(this);
  96259. this.physicsBody = null;
  96260. this._parent = this._parent || this._getPhysicsParent();
  96261. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  96262. this._physicsEngine.addImpostor(this);
  96263. }
  96264. };
  96265. PhysicsImpostor.prototype._getPhysicsParent = function () {
  96266. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  96267. var parentMesh = this.object.parent;
  96268. return parentMesh.physicsImpostor;
  96269. }
  96270. return null;
  96271. };
  96272. /**
  96273. * Should a new body be generated.
  96274. * @returns boolean specifying if body initialization is required
  96275. */
  96276. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  96277. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  96278. };
  96279. /**
  96280. * Sets the updated scaling
  96281. * @param updated Specifies if the scaling is updated
  96282. */
  96283. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  96284. this.forceUpdate();
  96285. };
  96286. /**
  96287. * Force a regeneration of this or the parent's impostor's body.
  96288. * Use under cautious - This will remove all joints already implemented.
  96289. */
  96290. PhysicsImpostor.prototype.forceUpdate = function () {
  96291. this._init();
  96292. if (this.parent && !this._options.ignoreParent) {
  96293. this.parent.forceUpdate();
  96294. }
  96295. };
  96296. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  96297. /*public get mesh(): AbstractMesh {
  96298. return this._mesh;
  96299. }*/
  96300. /**
  96301. * Gets the body that holds this impostor. Either its own, or its parent.
  96302. */
  96303. get: function () {
  96304. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  96305. },
  96306. /**
  96307. * Set the physics body. Used mainly by the physics engine/plugin
  96308. */
  96309. set: function (physicsBody) {
  96310. if (this._physicsBody && this._physicsEngine) {
  96311. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  96312. }
  96313. this._physicsBody = physicsBody;
  96314. this.resetUpdateFlags();
  96315. },
  96316. enumerable: true,
  96317. configurable: true
  96318. });
  96319. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  96320. /**
  96321. * Get the parent of the physics imposter
  96322. * @returns Physics imposter or null
  96323. */
  96324. get: function () {
  96325. return !this._options.ignoreParent && this._parent ? this._parent : null;
  96326. },
  96327. /**
  96328. * Sets the parent of the physics imposter
  96329. */
  96330. set: function (value) {
  96331. this._parent = value;
  96332. },
  96333. enumerable: true,
  96334. configurable: true
  96335. });
  96336. /**
  96337. * Resets the update flags
  96338. */
  96339. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  96340. this._bodyUpdateRequired = false;
  96341. };
  96342. /**
  96343. * Gets the object extend size
  96344. * @returns the object extend size
  96345. */
  96346. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  96347. if (this.object.getBoundingInfo) {
  96348. var q = this.object.rotationQuaternion;
  96349. //reset rotation
  96350. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  96351. //calculate the world matrix with no rotation
  96352. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96353. var boundingInfo = this.object.getBoundingInfo();
  96354. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  96355. //bring back the rotation
  96356. this.object.rotationQuaternion = q;
  96357. //calculate the world matrix with the new rotation
  96358. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96359. return size;
  96360. }
  96361. else {
  96362. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  96363. }
  96364. };
  96365. /**
  96366. * Gets the object center
  96367. * @returns The object center
  96368. */
  96369. PhysicsImpostor.prototype.getObjectCenter = function () {
  96370. if (this.object.getBoundingInfo) {
  96371. var boundingInfo = this.object.getBoundingInfo();
  96372. return boundingInfo.boundingBox.centerWorld;
  96373. }
  96374. else {
  96375. return this.object.position;
  96376. }
  96377. };
  96378. /**
  96379. * Get a specific parametes from the options parameter
  96380. * @param paramName The object parameter name
  96381. * @returns The object parameter
  96382. */
  96383. PhysicsImpostor.prototype.getParam = function (paramName) {
  96384. return this._options[paramName];
  96385. };
  96386. /**
  96387. * Sets a specific parameter in the options given to the physics plugin
  96388. * @param paramName The parameter name
  96389. * @param value The value of the parameter
  96390. */
  96391. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  96392. this._options[paramName] = value;
  96393. this._bodyUpdateRequired = true;
  96394. };
  96395. /**
  96396. * Specifically change the body's mass option. Won't recreate the physics body object
  96397. * @param mass The mass of the physics imposter
  96398. */
  96399. PhysicsImpostor.prototype.setMass = function (mass) {
  96400. if (this.getParam("mass") !== mass) {
  96401. this.setParam("mass", mass);
  96402. }
  96403. if (this._physicsEngine) {
  96404. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  96405. }
  96406. };
  96407. /**
  96408. * Gets the linear velocity
  96409. * @returns linear velocity or null
  96410. */
  96411. PhysicsImpostor.prototype.getLinearVelocity = function () {
  96412. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  96413. };
  96414. /**
  96415. * Sets the linear velocity
  96416. * @param velocity linear velocity or null
  96417. */
  96418. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  96419. if (this._physicsEngine) {
  96420. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  96421. }
  96422. };
  96423. /**
  96424. * Gets the angular velocity
  96425. * @returns angular velocity or null
  96426. */
  96427. PhysicsImpostor.prototype.getAngularVelocity = function () {
  96428. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  96429. };
  96430. /**
  96431. * Sets the angular velocity
  96432. * @param velocity The velocity or null
  96433. */
  96434. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  96435. if (this._physicsEngine) {
  96436. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  96437. }
  96438. };
  96439. /**
  96440. * Execute a function with the physics plugin native code
  96441. * Provide a function the will have two variables - the world object and the physics body object
  96442. * @param func The function to execute with the physics plugin native code
  96443. */
  96444. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  96445. if (this._physicsEngine) {
  96446. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  96447. }
  96448. };
  96449. /**
  96450. * Register a function that will be executed before the physics world is stepping forward
  96451. * @param func The function to execute before the physics world is stepped forward
  96452. */
  96453. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  96454. this._onBeforePhysicsStepCallbacks.push(func);
  96455. };
  96456. /**
  96457. * Unregister a function that will be executed before the physics world is stepping forward
  96458. * @param func The function to execute before the physics world is stepped forward
  96459. */
  96460. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  96461. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  96462. if (index > -1) {
  96463. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  96464. }
  96465. else {
  96466. BABYLON.Tools.Warn("Function to remove was not found");
  96467. }
  96468. };
  96469. /**
  96470. * Register a function that will be executed after the physics step
  96471. * @param func The function to execute after physics step
  96472. */
  96473. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  96474. this._onAfterPhysicsStepCallbacks.push(func);
  96475. };
  96476. /**
  96477. * Unregisters a function that will be executed after the physics step
  96478. * @param func The function to execute after physics step
  96479. */
  96480. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  96481. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  96482. if (index > -1) {
  96483. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  96484. }
  96485. else {
  96486. BABYLON.Tools.Warn("Function to remove was not found");
  96487. }
  96488. };
  96489. /**
  96490. * register a function that will be executed when this impostor collides against a different body
  96491. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  96492. * @param func Callback that is executed on collision
  96493. */
  96494. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  96495. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96496. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  96497. };
  96498. /**
  96499. * Unregisters the physics imposter on contact
  96500. * @param collideAgainst The physics object to collide against
  96501. * @param func Callback to execute on collision
  96502. */
  96503. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  96504. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96505. var index = -1;
  96506. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  96507. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  96508. // chcek the arrays match
  96509. var sameList = cbDef.otherImpostors.every(function (impostor) {
  96510. return collidedAgainstList.indexOf(impostor) > -1;
  96511. });
  96512. if (sameList) {
  96513. index = idx;
  96514. }
  96515. return sameList;
  96516. }
  96517. return false;
  96518. });
  96519. if (found) {
  96520. this._onPhysicsCollideCallbacks.splice(index, 1);
  96521. }
  96522. else {
  96523. BABYLON.Tools.Warn("Function to remove was not found");
  96524. }
  96525. };
  96526. /**
  96527. * Get the parent rotation
  96528. * @returns The parent rotation
  96529. */
  96530. PhysicsImpostor.prototype.getParentsRotation = function () {
  96531. var parent = this.object.parent;
  96532. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  96533. while (parent) {
  96534. if (parent.rotationQuaternion) {
  96535. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  96536. }
  96537. else {
  96538. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  96539. }
  96540. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  96541. parent = parent.parent;
  96542. }
  96543. return this._tmpQuat;
  96544. };
  96545. /**
  96546. * Apply a force
  96547. * @param force The force to apply
  96548. * @param contactPoint The contact point for the force
  96549. * @returns The physics imposter
  96550. */
  96551. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  96552. if (this._physicsEngine) {
  96553. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  96554. }
  96555. return this;
  96556. };
  96557. /**
  96558. * Apply an impulse
  96559. * @param force The impulse force
  96560. * @param contactPoint The contact point for the impulse force
  96561. * @returns The physics imposter
  96562. */
  96563. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  96564. if (this._physicsEngine) {
  96565. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  96566. }
  96567. return this;
  96568. };
  96569. /**
  96570. * A help function to create a joint
  96571. * @param otherImpostor A physics imposter used to create a joint
  96572. * @param jointType The type of joint
  96573. * @param jointData The data for the joint
  96574. * @returns The physics imposter
  96575. */
  96576. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  96577. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  96578. this.addJoint(otherImpostor, joint);
  96579. return this;
  96580. };
  96581. /**
  96582. * Add a joint to this impostor with a different impostor
  96583. * @param otherImpostor A physics imposter used to add a joint
  96584. * @param joint The joint to add
  96585. * @returns The physics imposter
  96586. */
  96587. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  96588. this._joints.push({
  96589. otherImpostor: otherImpostor,
  96590. joint: joint
  96591. });
  96592. if (this._physicsEngine) {
  96593. this._physicsEngine.addJoint(this, otherImpostor, joint);
  96594. }
  96595. return this;
  96596. };
  96597. /**
  96598. * Will keep this body still, in a sleep mode.
  96599. * @returns the physics imposter
  96600. */
  96601. PhysicsImpostor.prototype.sleep = function () {
  96602. if (this._physicsEngine) {
  96603. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  96604. }
  96605. return this;
  96606. };
  96607. /**
  96608. * Wake the body up.
  96609. * @returns The physics imposter
  96610. */
  96611. PhysicsImpostor.prototype.wakeUp = function () {
  96612. if (this._physicsEngine) {
  96613. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  96614. }
  96615. return this;
  96616. };
  96617. /**
  96618. * Clones the physics imposter
  96619. * @param newObject The physics imposter clones to this physics-enabled object
  96620. * @returns A nullable physics imposter
  96621. */
  96622. PhysicsImpostor.prototype.clone = function (newObject) {
  96623. if (!newObject) {
  96624. return null;
  96625. }
  96626. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  96627. };
  96628. /**
  96629. * Disposes the physics imposter
  96630. */
  96631. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  96632. var _this = this;
  96633. //no dispose if no physics engine is available.
  96634. if (!this._physicsEngine) {
  96635. return;
  96636. }
  96637. this._joints.forEach(function (j) {
  96638. if (_this._physicsEngine) {
  96639. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  96640. }
  96641. });
  96642. //dispose the physics body
  96643. this._physicsEngine.removeImpostor(this);
  96644. if (this.parent) {
  96645. this.parent.forceUpdate();
  96646. }
  96647. else {
  96648. /*this._object.getChildMeshes().forEach(function(mesh) {
  96649. if (mesh.physicsImpostor) {
  96650. if (disposeChildren) {
  96651. mesh.physicsImpostor.dispose();
  96652. mesh.physicsImpostor = null;
  96653. }
  96654. }
  96655. })*/
  96656. }
  96657. this._isDisposed = true;
  96658. };
  96659. /**
  96660. * Sets the delta position
  96661. * @param position The delta position amount
  96662. */
  96663. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  96664. this._deltaPosition.copyFrom(position);
  96665. };
  96666. /**
  96667. * Sets the delta rotation
  96668. * @param rotation The delta rotation amount
  96669. */
  96670. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  96671. if (!this._deltaRotation) {
  96672. this._deltaRotation = new BABYLON.Quaternion();
  96673. }
  96674. this._deltaRotation.copyFrom(rotation);
  96675. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  96676. };
  96677. /**
  96678. * Gets the box size of the physics imposter and stores the result in the input parameter
  96679. * @param result Stores the box size
  96680. * @returns The physics imposter
  96681. */
  96682. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  96683. if (this._physicsEngine) {
  96684. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  96685. }
  96686. return this;
  96687. };
  96688. /**
  96689. * Gets the radius of the physics imposter
  96690. * @returns Radius of the physics imposter
  96691. */
  96692. PhysicsImpostor.prototype.getRadius = function () {
  96693. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  96694. };
  96695. /**
  96696. * Sync a bone with this impostor
  96697. * @param bone The bone to sync to the impostor.
  96698. * @param boneMesh The mesh that the bone is influencing.
  96699. * @param jointPivot The pivot of the joint / bone in local space.
  96700. * @param distToJoint Optional distance from the impostor to the joint.
  96701. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96702. */
  96703. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  96704. var tempVec = PhysicsImpostor._tmpVecs[0];
  96705. var mesh = this.object;
  96706. if (mesh.rotationQuaternion) {
  96707. if (adjustRotation) {
  96708. var tempQuat = PhysicsImpostor._tmpQuat;
  96709. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  96710. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  96711. }
  96712. else {
  96713. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  96714. }
  96715. }
  96716. tempVec.x = 0;
  96717. tempVec.y = 0;
  96718. tempVec.z = 0;
  96719. if (jointPivot) {
  96720. tempVec.x = jointPivot.x;
  96721. tempVec.y = jointPivot.y;
  96722. tempVec.z = jointPivot.z;
  96723. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  96724. if (distToJoint === undefined || distToJoint === null) {
  96725. distToJoint = jointPivot.length();
  96726. }
  96727. tempVec.x *= distToJoint;
  96728. tempVec.y *= distToJoint;
  96729. tempVec.z *= distToJoint;
  96730. }
  96731. if (bone.getParent()) {
  96732. tempVec.addInPlace(mesh.getAbsolutePosition());
  96733. bone.setAbsolutePosition(tempVec, boneMesh);
  96734. }
  96735. else {
  96736. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  96737. boneMesh.position.x -= tempVec.x;
  96738. boneMesh.position.y -= tempVec.y;
  96739. boneMesh.position.z -= tempVec.z;
  96740. }
  96741. };
  96742. /**
  96743. * Sync impostor to a bone
  96744. * @param bone The bone that the impostor will be synced to.
  96745. * @param boneMesh The mesh that the bone is influencing.
  96746. * @param jointPivot The pivot of the joint / bone in local space.
  96747. * @param distToJoint Optional distance from the impostor to the joint.
  96748. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96749. * @param boneAxis Optional vector3 axis the bone is aligned with
  96750. */
  96751. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  96752. var mesh = this.object;
  96753. if (mesh.rotationQuaternion) {
  96754. if (adjustRotation) {
  96755. var tempQuat = PhysicsImpostor._tmpQuat;
  96756. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  96757. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  96758. }
  96759. else {
  96760. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  96761. }
  96762. }
  96763. var pos = PhysicsImpostor._tmpVecs[0];
  96764. var boneDir = PhysicsImpostor._tmpVecs[1];
  96765. if (!boneAxis) {
  96766. boneAxis = PhysicsImpostor._tmpVecs[2];
  96767. boneAxis.x = 0;
  96768. boneAxis.y = 1;
  96769. boneAxis.z = 0;
  96770. }
  96771. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  96772. bone.getAbsolutePositionToRef(boneMesh, pos);
  96773. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  96774. distToJoint = jointPivot.length();
  96775. }
  96776. if (distToJoint !== undefined && distToJoint !== null) {
  96777. pos.x += boneDir.x * distToJoint;
  96778. pos.y += boneDir.y * distToJoint;
  96779. pos.z += boneDir.z * distToJoint;
  96780. }
  96781. mesh.setAbsolutePosition(pos);
  96782. };
  96783. /**
  96784. * The default object size of the imposter
  96785. */
  96786. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  96787. /**
  96788. * The identity quaternion of the imposter
  96789. */
  96790. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  96791. PhysicsImpostor._tmpVecs = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  96792. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  96793. //Impostor types
  96794. /**
  96795. * No-Imposter type
  96796. */
  96797. PhysicsImpostor.NoImpostor = 0;
  96798. /**
  96799. * Sphere-Imposter type
  96800. */
  96801. PhysicsImpostor.SphereImpostor = 1;
  96802. /**
  96803. * Box-Imposter type
  96804. */
  96805. PhysicsImpostor.BoxImpostor = 2;
  96806. /**
  96807. * Plane-Imposter type
  96808. */
  96809. PhysicsImpostor.PlaneImpostor = 3;
  96810. /**
  96811. * Mesh-imposter type
  96812. */
  96813. PhysicsImpostor.MeshImpostor = 4;
  96814. /**
  96815. * Cylinder-Imposter type
  96816. */
  96817. PhysicsImpostor.CylinderImpostor = 7;
  96818. /**
  96819. * Particle-Imposter type
  96820. */
  96821. PhysicsImpostor.ParticleImpostor = 8;
  96822. /**
  96823. * Heightmap-Imposter type
  96824. */
  96825. PhysicsImpostor.HeightmapImpostor = 9;
  96826. return PhysicsImpostor;
  96827. }());
  96828. BABYLON.PhysicsImpostor = PhysicsImpostor;
  96829. })(BABYLON || (BABYLON = {}));
  96830. //# sourceMappingURL=babylon.physicsImpostor.js.map
  96831. var BABYLON;
  96832. (function (BABYLON) {
  96833. /**
  96834. * Class used to control physics engine
  96835. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  96836. */
  96837. var PhysicsEngine = /** @class */ (function () {
  96838. /**
  96839. * Creates a new Physics Engine
  96840. * @param gravity defines the gravity vector used by the simulation
  96841. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  96842. */
  96843. function PhysicsEngine(gravity, _physicsPlugin) {
  96844. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  96845. this._physicsPlugin = _physicsPlugin;
  96846. this._impostors = [];
  96847. this._joints = [];
  96848. if (!this._physicsPlugin.isSupported()) {
  96849. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  96850. + "Please make sure it is included.");
  96851. }
  96852. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  96853. this.setGravity(gravity);
  96854. this.setTimeStep();
  96855. }
  96856. /**
  96857. * Sets the gravity vector used by the simulation
  96858. * @param gravity defines the gravity vector to use
  96859. */
  96860. PhysicsEngine.prototype.setGravity = function (gravity) {
  96861. this.gravity = gravity;
  96862. this._physicsPlugin.setGravity(this.gravity);
  96863. };
  96864. /**
  96865. * Set the time step of the physics engine.
  96866. * Default is 1/60.
  96867. * To slow it down, enter 1/600 for example.
  96868. * To speed it up, 1/30
  96869. * @param newTimeStep defines the new timestep to apply to this world.
  96870. */
  96871. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  96872. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  96873. this._physicsPlugin.setTimeStep(newTimeStep);
  96874. };
  96875. /**
  96876. * Get the time step of the physics engine.
  96877. * @returns the current time step
  96878. */
  96879. PhysicsEngine.prototype.getTimeStep = function () {
  96880. return this._physicsPlugin.getTimeStep();
  96881. };
  96882. /**
  96883. * Release all resources
  96884. */
  96885. PhysicsEngine.prototype.dispose = function () {
  96886. this._impostors.forEach(function (impostor) {
  96887. impostor.dispose();
  96888. });
  96889. this._physicsPlugin.dispose();
  96890. };
  96891. /**
  96892. * Gets the name of the current physics plugin
  96893. * @returns the name of the plugin
  96894. */
  96895. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  96896. return this._physicsPlugin.name;
  96897. };
  96898. /**
  96899. * Adding a new impostor for the impostor tracking.
  96900. * This will be done by the impostor itself.
  96901. * @param impostor the impostor to add
  96902. */
  96903. PhysicsEngine.prototype.addImpostor = function (impostor) {
  96904. impostor.uniqueId = this._impostors.push(impostor);
  96905. //if no parent, generate the body
  96906. if (!impostor.parent) {
  96907. this._physicsPlugin.generatePhysicsBody(impostor);
  96908. }
  96909. };
  96910. /**
  96911. * Remove an impostor from the engine.
  96912. * This impostor and its mesh will not longer be updated by the physics engine.
  96913. * @param impostor the impostor to remove
  96914. */
  96915. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  96916. var index = this._impostors.indexOf(impostor);
  96917. if (index > -1) {
  96918. var removed = this._impostors.splice(index, 1);
  96919. //Is it needed?
  96920. if (removed.length) {
  96921. //this will also remove it from the world.
  96922. removed[0].physicsBody = null;
  96923. }
  96924. }
  96925. };
  96926. /**
  96927. * Add a joint to the physics engine
  96928. * @param mainImpostor defines the main impostor to which the joint is added.
  96929. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  96930. * @param joint defines the joint that will connect both impostors.
  96931. */
  96932. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  96933. var impostorJoint = {
  96934. mainImpostor: mainImpostor,
  96935. connectedImpostor: connectedImpostor,
  96936. joint: joint
  96937. };
  96938. joint.physicsPlugin = this._physicsPlugin;
  96939. this._joints.push(impostorJoint);
  96940. this._physicsPlugin.generateJoint(impostorJoint);
  96941. };
  96942. /**
  96943. * Removes a joint from the simulation
  96944. * @param mainImpostor defines the impostor used with the joint
  96945. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  96946. * @param joint defines the joint to remove
  96947. */
  96948. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  96949. var matchingJoints = this._joints.filter(function (impostorJoint) {
  96950. return (impostorJoint.connectedImpostor === connectedImpostor
  96951. && impostorJoint.joint === joint
  96952. && impostorJoint.mainImpostor === mainImpostor);
  96953. });
  96954. if (matchingJoints.length) {
  96955. this._physicsPlugin.removeJoint(matchingJoints[0]);
  96956. //TODO remove it from the list as well
  96957. }
  96958. };
  96959. /**
  96960. * Called by the scene. No need to call it.
  96961. * @param delta defines the timespam between frames
  96962. */
  96963. PhysicsEngine.prototype._step = function (delta) {
  96964. var _this = this;
  96965. //check if any mesh has no body / requires an update
  96966. this._impostors.forEach(function (impostor) {
  96967. if (impostor.isBodyInitRequired()) {
  96968. _this._physicsPlugin.generatePhysicsBody(impostor);
  96969. }
  96970. });
  96971. if (delta > 0.1) {
  96972. delta = 0.1;
  96973. }
  96974. else if (delta <= 0) {
  96975. delta = 1.0 / 60.0;
  96976. }
  96977. this._physicsPlugin.executeStep(delta, this._impostors);
  96978. };
  96979. /**
  96980. * Gets the current plugin used to run the simulation
  96981. * @returns current plugin
  96982. */
  96983. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  96984. return this._physicsPlugin;
  96985. };
  96986. /**
  96987. * Gets the list of physic impostors
  96988. * @returns an array of PhysicsImpostor
  96989. */
  96990. PhysicsEngine.prototype.getImpostors = function () {
  96991. return this._impostors;
  96992. };
  96993. /**
  96994. * Gets the impostor for a physics enabled object
  96995. * @param object defines the object impersonated by the impostor
  96996. * @returns the PhysicsImpostor or null if not found
  96997. */
  96998. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  96999. for (var i = 0; i < this._impostors.length; ++i) {
  97000. if (this._impostors[i].object === object) {
  97001. return this._impostors[i];
  97002. }
  97003. }
  97004. return null;
  97005. };
  97006. /**
  97007. * Gets the impostor for a physics body object
  97008. * @param body defines physics body used by the impostor
  97009. * @returns the PhysicsImpostor or null if not found
  97010. */
  97011. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  97012. for (var i = 0; i < this._impostors.length; ++i) {
  97013. if (this._impostors[i].physicsBody === body) {
  97014. return this._impostors[i];
  97015. }
  97016. }
  97017. return null;
  97018. };
  97019. /**
  97020. * Global value used to control the smallest number supported by the simulation
  97021. */
  97022. PhysicsEngine.Epsilon = 0.001;
  97023. return PhysicsEngine;
  97024. }());
  97025. BABYLON.PhysicsEngine = PhysicsEngine;
  97026. })(BABYLON || (BABYLON = {}));
  97027. //# sourceMappingURL=babylon.physicsEngine.js.map
  97028. var BABYLON;
  97029. (function (BABYLON) {
  97030. /**
  97031. * A helper for physics simulations
  97032. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97033. */
  97034. var PhysicsHelper = /** @class */ (function () {
  97035. /**
  97036. * Initializes the Physics helper
  97037. * @param scene Babylon.js scene
  97038. */
  97039. function PhysicsHelper(scene) {
  97040. this._scene = scene;
  97041. this._physicsEngine = this._scene.getPhysicsEngine();
  97042. if (!this._physicsEngine) {
  97043. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  97044. }
  97045. }
  97046. /**
  97047. * Applies a radial explosion impulse
  97048. * @param origin the origin of the explosion
  97049. * @param radius the explosion radius
  97050. * @param strength the explosion strength
  97051. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97052. * @returns A physics radial explosion event, or null
  97053. */
  97054. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  97055. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97056. if (!this._physicsEngine) {
  97057. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  97058. return null;
  97059. }
  97060. var impostors = this._physicsEngine.getImpostors();
  97061. if (impostors.length === 0) {
  97062. return null;
  97063. }
  97064. var event = new PhysicsRadialExplosionEvent(this._scene);
  97065. impostors.forEach(function (impostor) {
  97066. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97067. if (!impostorForceAndContactPoint) {
  97068. return;
  97069. }
  97070. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97071. });
  97072. event.dispose(false);
  97073. return event;
  97074. };
  97075. /**
  97076. * Applies a radial explosion force
  97077. * @param origin the origin of the explosion
  97078. * @param radius the explosion radius
  97079. * @param strength the explosion strength
  97080. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97081. * @returns A physics radial explosion event, or null
  97082. */
  97083. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  97084. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97085. if (!this._physicsEngine) {
  97086. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97087. return null;
  97088. }
  97089. var impostors = this._physicsEngine.getImpostors();
  97090. if (impostors.length === 0) {
  97091. return null;
  97092. }
  97093. var event = new PhysicsRadialExplosionEvent(this._scene);
  97094. impostors.forEach(function (impostor) {
  97095. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97096. if (!impostorForceAndContactPoint) {
  97097. return;
  97098. }
  97099. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97100. });
  97101. event.dispose(false);
  97102. return event;
  97103. };
  97104. /**
  97105. * Creates a gravitational field
  97106. * @param origin the origin of the explosion
  97107. * @param radius the explosion radius
  97108. * @param strength the explosion strength
  97109. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97110. * @returns A physics gravitational field event, or null
  97111. */
  97112. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  97113. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97114. if (!this._physicsEngine) {
  97115. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97116. return null;
  97117. }
  97118. var impostors = this._physicsEngine.getImpostors();
  97119. if (impostors.length === 0) {
  97120. return null;
  97121. }
  97122. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  97123. event.dispose(false);
  97124. return event;
  97125. };
  97126. /**
  97127. * Creates a physics updraft event
  97128. * @param origin the origin of the updraft
  97129. * @param radius the radius of the updraft
  97130. * @param strength the strength of the updraft
  97131. * @param height the height of the updraft
  97132. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  97133. * @returns A physics updraft event, or null
  97134. */
  97135. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  97136. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  97137. if (!this._physicsEngine) {
  97138. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97139. return null;
  97140. }
  97141. if (this._physicsEngine.getImpostors().length === 0) {
  97142. return null;
  97143. }
  97144. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  97145. event.dispose(false);
  97146. return event;
  97147. };
  97148. /**
  97149. * Creates a physics vortex event
  97150. * @param origin the of the vortex
  97151. * @param radius the radius of the vortex
  97152. * @param strength the strength of the vortex
  97153. * @param height the height of the vortex
  97154. * @returns a Physics vortex event, or null
  97155. * A physics vortex event or null
  97156. */
  97157. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  97158. if (!this._physicsEngine) {
  97159. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97160. return null;
  97161. }
  97162. if (this._physicsEngine.getImpostors().length === 0) {
  97163. return null;
  97164. }
  97165. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  97166. event.dispose(false);
  97167. return event;
  97168. };
  97169. return PhysicsHelper;
  97170. }());
  97171. BABYLON.PhysicsHelper = PhysicsHelper;
  97172. /**
  97173. * Represents a physics radial explosion event
  97174. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97175. */
  97176. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  97177. /**
  97178. * Initializes a radial explosioin event
  97179. * @param scene BabylonJS scene
  97180. */
  97181. function PhysicsRadialExplosionEvent(scene) {
  97182. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  97183. this._rays = [];
  97184. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  97185. this._scene = scene;
  97186. }
  97187. /**
  97188. * Returns the data related to the radial explosion event (sphere & rays).
  97189. * @returns The radial explosion event data
  97190. */
  97191. PhysicsRadialExplosionEvent.prototype.getData = function () {
  97192. this._dataFetched = true;
  97193. return {
  97194. sphere: this._sphere,
  97195. rays: this._rays,
  97196. };
  97197. };
  97198. /**
  97199. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  97200. * @param impostor A physics imposter
  97201. * @param origin the origin of the explosion
  97202. * @param radius the explosion radius
  97203. * @param strength the explosion strength
  97204. * @param falloff possible options: Constant & Linear
  97205. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  97206. */
  97207. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  97208. if (impostor.mass === 0) {
  97209. return null;
  97210. }
  97211. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  97212. return null;
  97213. }
  97214. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97215. return null;
  97216. }
  97217. var impostorObjectCenter = impostor.getObjectCenter();
  97218. var direction = impostorObjectCenter.subtract(origin);
  97219. var ray = new BABYLON.Ray(origin, direction, radius);
  97220. this._rays.push(ray);
  97221. var hit = ray.intersectsMesh(impostor.object);
  97222. var contactPoint = hit.pickedPoint;
  97223. if (!contactPoint) {
  97224. return null;
  97225. }
  97226. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  97227. if (distanceFromOrigin > radius) {
  97228. return null;
  97229. }
  97230. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  97231. ? strength
  97232. : strength * (1 - (distanceFromOrigin / radius));
  97233. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97234. return { force: force, contactPoint: contactPoint };
  97235. };
  97236. /**
  97237. * Disposes the sphere.
  97238. * @param force Specifies if the sphere should be disposed by force
  97239. */
  97240. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  97241. var _this = this;
  97242. if (force === void 0) { force = true; }
  97243. if (force) {
  97244. this._sphere.dispose();
  97245. }
  97246. else {
  97247. setTimeout(function () {
  97248. if (!_this._dataFetched) {
  97249. _this._sphere.dispose();
  97250. }
  97251. }, 0);
  97252. }
  97253. };
  97254. /*** Helpers ***/
  97255. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  97256. if (!this._sphere) {
  97257. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  97258. this._sphere.isVisible = false;
  97259. }
  97260. };
  97261. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  97262. var impostorObject = impostor.object;
  97263. this._prepareSphere();
  97264. this._sphere.position = origin;
  97265. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  97266. this._sphere._updateBoundingInfo();
  97267. this._sphere.computeWorldMatrix(true);
  97268. return this._sphere.intersectsMesh(impostorObject, true);
  97269. };
  97270. return PhysicsRadialExplosionEvent;
  97271. }());
  97272. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  97273. /**
  97274. * Represents a gravitational field event
  97275. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97276. */
  97277. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  97278. /**
  97279. * Initializes the physics gravitational field event
  97280. * @param physicsHelper A physics helper
  97281. * @param scene BabylonJS scene
  97282. * @param origin The origin position of the gravitational field event
  97283. * @param radius The radius of the gravitational field event
  97284. * @param strength The strength of the gravitational field event
  97285. * @param falloff The falloff for the gravitational field event
  97286. */
  97287. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  97288. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97289. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97290. this._physicsHelper = physicsHelper;
  97291. this._scene = scene;
  97292. this._origin = origin;
  97293. this._radius = radius;
  97294. this._strength = strength;
  97295. this._falloff = falloff;
  97296. this._tickCallback = this._tick.bind(this);
  97297. }
  97298. /**
  97299. * Returns the data related to the gravitational field event (sphere).
  97300. * @returns A gravitational field event
  97301. */
  97302. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  97303. this._dataFetched = true;
  97304. return {
  97305. sphere: this._sphere,
  97306. };
  97307. };
  97308. /**
  97309. * Enables the gravitational field.
  97310. */
  97311. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  97312. this._tickCallback.call(this);
  97313. this._scene.registerBeforeRender(this._tickCallback);
  97314. };
  97315. /**
  97316. * Disables the gravitational field.
  97317. */
  97318. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  97319. this._scene.unregisterBeforeRender(this._tickCallback);
  97320. };
  97321. /**
  97322. * Disposes the sphere.
  97323. * @param force The force to dispose from the gravitational field event
  97324. */
  97325. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  97326. var _this = this;
  97327. if (force === void 0) { force = true; }
  97328. if (force) {
  97329. this._sphere.dispose();
  97330. }
  97331. else {
  97332. setTimeout(function () {
  97333. if (!_this._dataFetched) {
  97334. _this._sphere.dispose();
  97335. }
  97336. }, 0);
  97337. }
  97338. };
  97339. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  97340. // Since the params won't change, we fetch the event only once
  97341. if (this._sphere) {
  97342. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97343. }
  97344. else {
  97345. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97346. if (radialExplosionEvent) {
  97347. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  97348. }
  97349. }
  97350. };
  97351. return PhysicsGravitationalFieldEvent;
  97352. }());
  97353. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  97354. /**
  97355. * Represents a physics updraft event
  97356. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97357. */
  97358. var PhysicsUpdraftEvent = /** @class */ (function () {
  97359. /**
  97360. * Initializes the physics updraft event
  97361. * @param _scene BabylonJS scene
  97362. * @param _origin The origin position of the updraft
  97363. * @param _radius The radius of the updraft
  97364. * @param _strength The strength of the updraft
  97365. * @param _height The height of the updraft
  97366. * @param _updraftMode The mode of the updraft
  97367. */
  97368. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  97369. this._scene = _scene;
  97370. this._origin = _origin;
  97371. this._radius = _radius;
  97372. this._strength = _strength;
  97373. this._height = _height;
  97374. this._updraftMode = _updraftMode;
  97375. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97376. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  97377. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97378. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97379. this._physicsEngine = this._scene.getPhysicsEngine();
  97380. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97381. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97382. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97383. this._originDirection = this._origin.subtract(this._originTop).normalize();
  97384. }
  97385. this._tickCallback = this._tick.bind(this);
  97386. }
  97387. /**
  97388. * Returns the data related to the updraft event (cylinder).
  97389. * @returns A physics updraft event
  97390. */
  97391. PhysicsUpdraftEvent.prototype.getData = function () {
  97392. this._dataFetched = true;
  97393. return {
  97394. cylinder: this._cylinder,
  97395. };
  97396. };
  97397. /**
  97398. * Enables the updraft.
  97399. */
  97400. PhysicsUpdraftEvent.prototype.enable = function () {
  97401. this._tickCallback.call(this);
  97402. this._scene.registerBeforeRender(this._tickCallback);
  97403. };
  97404. /**
  97405. * Disables the cortex.
  97406. */
  97407. PhysicsUpdraftEvent.prototype.disable = function () {
  97408. this._scene.unregisterBeforeRender(this._tickCallback);
  97409. };
  97410. /**
  97411. * Disposes the sphere.
  97412. * @param force Specifies if the updraft should be disposed by force
  97413. */
  97414. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  97415. var _this = this;
  97416. if (force === void 0) { force = true; }
  97417. if (force) {
  97418. this._cylinder.dispose();
  97419. }
  97420. else {
  97421. setTimeout(function () {
  97422. if (!_this._dataFetched) {
  97423. _this._cylinder.dispose();
  97424. }
  97425. }, 0);
  97426. }
  97427. };
  97428. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97429. if (impostor.mass === 0) {
  97430. return null;
  97431. }
  97432. if (!this._intersectsWithCylinder(impostor)) {
  97433. return null;
  97434. }
  97435. var impostorObjectCenter = impostor.getObjectCenter();
  97436. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97437. var direction = this._originDirection;
  97438. }
  97439. else {
  97440. var direction = impostorObjectCenter.subtract(this._originTop);
  97441. }
  97442. var multiplier = this._strength * -1;
  97443. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97444. return { force: force, contactPoint: impostorObjectCenter };
  97445. };
  97446. PhysicsUpdraftEvent.prototype._tick = function () {
  97447. var _this = this;
  97448. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97449. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97450. if (!impostorForceAndContactPoint) {
  97451. return;
  97452. }
  97453. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97454. });
  97455. };
  97456. /*** Helpers ***/
  97457. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  97458. if (!this._cylinder) {
  97459. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  97460. height: this._height,
  97461. diameter: this._radius * 2,
  97462. }, this._scene);
  97463. this._cylinder.isVisible = false;
  97464. }
  97465. };
  97466. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  97467. var impostorObject = impostor.object;
  97468. this._prepareCylinder();
  97469. this._cylinder.position = this._cylinderPosition;
  97470. return this._cylinder.intersectsMesh(impostorObject, true);
  97471. };
  97472. return PhysicsUpdraftEvent;
  97473. }());
  97474. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  97475. /**
  97476. * Represents a physics vortex event
  97477. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97478. */
  97479. var PhysicsVortexEvent = /** @class */ (function () {
  97480. /**
  97481. * Initializes the physics vortex event
  97482. * @param _scene The BabylonJS scene
  97483. * @param _origin The origin position of the vortex
  97484. * @param _radius The radius of the vortex
  97485. * @param _strength The strength of the vortex
  97486. * @param _height The height of the vortex
  97487. */
  97488. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  97489. this._scene = _scene;
  97490. this._origin = _origin;
  97491. this._radius = _radius;
  97492. this._strength = _strength;
  97493. this._height = _height;
  97494. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97495. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  97496. this._updraftMultiplier = 0.02;
  97497. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97498. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97499. this._physicsEngine = this._scene.getPhysicsEngine();
  97500. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97501. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97502. this._tickCallback = this._tick.bind(this);
  97503. }
  97504. /**
  97505. * Returns the data related to the vortex event (cylinder).
  97506. * @returns The physics vortex event data
  97507. */
  97508. PhysicsVortexEvent.prototype.getData = function () {
  97509. this._dataFetched = true;
  97510. return {
  97511. cylinder: this._cylinder,
  97512. };
  97513. };
  97514. /**
  97515. * Enables the vortex.
  97516. */
  97517. PhysicsVortexEvent.prototype.enable = function () {
  97518. this._tickCallback.call(this);
  97519. this._scene.registerBeforeRender(this._tickCallback);
  97520. };
  97521. /**
  97522. * Disables the cortex.
  97523. */
  97524. PhysicsVortexEvent.prototype.disable = function () {
  97525. this._scene.unregisterBeforeRender(this._tickCallback);
  97526. };
  97527. /**
  97528. * Disposes the sphere.
  97529. * @param force
  97530. */
  97531. PhysicsVortexEvent.prototype.dispose = function (force) {
  97532. var _this = this;
  97533. if (force === void 0) { force = true; }
  97534. if (force) {
  97535. this._cylinder.dispose();
  97536. }
  97537. else {
  97538. setTimeout(function () {
  97539. if (!_this._dataFetched) {
  97540. _this._cylinder.dispose();
  97541. }
  97542. }, 0);
  97543. }
  97544. };
  97545. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97546. if (impostor.mass === 0) {
  97547. return null;
  97548. }
  97549. if (!this._intersectsWithCylinder(impostor)) {
  97550. return null;
  97551. }
  97552. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97553. return null;
  97554. }
  97555. var impostorObjectCenter = impostor.getObjectCenter();
  97556. 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)
  97557. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  97558. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  97559. var hit = ray.intersectsMesh(impostor.object);
  97560. var contactPoint = hit.pickedPoint;
  97561. if (!contactPoint) {
  97562. return null;
  97563. }
  97564. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  97565. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  97566. var directionToOrigin = contactPoint.normalize();
  97567. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97568. directionToOrigin = directionToOrigin.negate();
  97569. }
  97570. // TODO: find a more physically based solution
  97571. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97572. var forceX = directionToOrigin.x * this._strength / 8;
  97573. var forceY = directionToOrigin.y * this._updraftMultiplier;
  97574. var forceZ = directionToOrigin.z * this._strength / 8;
  97575. }
  97576. else {
  97577. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  97578. var forceY = this._originTop.y * this._updraftMultiplier;
  97579. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  97580. }
  97581. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  97582. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  97583. return { force: force, contactPoint: impostorObjectCenter };
  97584. };
  97585. PhysicsVortexEvent.prototype._tick = function () {
  97586. var _this = this;
  97587. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97588. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97589. if (!impostorForceAndContactPoint) {
  97590. return;
  97591. }
  97592. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97593. });
  97594. };
  97595. /*** Helpers ***/
  97596. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  97597. if (!this._cylinder) {
  97598. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  97599. height: this._height,
  97600. diameter: this._radius * 2,
  97601. }, this._scene);
  97602. this._cylinder.isVisible = false;
  97603. }
  97604. };
  97605. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  97606. var impostorObject = impostor.object;
  97607. this._prepareCylinder();
  97608. this._cylinder.position = this._cylinderPosition;
  97609. return this._cylinder.intersectsMesh(impostorObject, true);
  97610. };
  97611. return PhysicsVortexEvent;
  97612. }());
  97613. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  97614. /**
  97615. * The strenght of the force in correspondence to the distance of the affected object
  97616. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97617. */
  97618. var PhysicsRadialImpulseFalloff;
  97619. (function (PhysicsRadialImpulseFalloff) {
  97620. /** Defines that impulse is constant in strength across it's whole radius */
  97621. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  97622. /** DEfines that impulse gets weaker if it's further from the origin */
  97623. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  97624. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  97625. /**
  97626. * The strength of the force in correspondence to the distance of the affected object
  97627. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97628. */
  97629. var PhysicsUpdraftMode;
  97630. (function (PhysicsUpdraftMode) {
  97631. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  97632. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  97633. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  97634. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  97635. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  97636. })(BABYLON || (BABYLON = {}));
  97637. //# sourceMappingURL=babylon.physicsHelper.js.map
  97638. var BABYLON;
  97639. (function (BABYLON) {
  97640. /** @hidden */
  97641. var CannonJSPlugin = /** @class */ (function () {
  97642. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  97643. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  97644. if (iterations === void 0) { iterations = 10; }
  97645. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  97646. this.name = "CannonJSPlugin";
  97647. this._physicsMaterials = new Array();
  97648. this._fixedTimeStep = 1 / 60;
  97649. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  97650. this.BJSCANNON = CANNON;
  97651. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  97652. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  97653. this._tmpPosition = BABYLON.Vector3.Zero();
  97654. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  97655. this._tmpUnityRotation = new BABYLON.Quaternion();
  97656. if (!this.isSupported()) {
  97657. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  97658. return;
  97659. }
  97660. this._extendNamespace();
  97661. this.world = new this.BJSCANNON.World();
  97662. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  97663. this.world.solver.iterations = iterations;
  97664. }
  97665. CannonJSPlugin.prototype.setGravity = function (gravity) {
  97666. this.world.gravity.copy(gravity);
  97667. };
  97668. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  97669. this._fixedTimeStep = timeStep;
  97670. };
  97671. CannonJSPlugin.prototype.getTimeStep = function () {
  97672. return this._fixedTimeStep;
  97673. };
  97674. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  97675. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  97676. };
  97677. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  97678. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97679. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97680. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  97681. };
  97682. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  97683. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97684. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97685. impostor.physicsBody.applyForce(impulse, worldPoint);
  97686. };
  97687. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  97688. //parent-child relationship. Does this impostor has a parent impostor?
  97689. if (impostor.parent) {
  97690. if (impostor.physicsBody) {
  97691. this.removePhysicsBody(impostor);
  97692. //TODO is that needed?
  97693. impostor.forceUpdate();
  97694. }
  97695. return;
  97696. }
  97697. //should a new body be created for this impostor?
  97698. if (impostor.isBodyInitRequired()) {
  97699. var shape = this._createShape(impostor);
  97700. //unregister events, if body is being changed
  97701. var oldBody = impostor.physicsBody;
  97702. if (oldBody) {
  97703. this.removePhysicsBody(impostor);
  97704. }
  97705. //create the body and material
  97706. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  97707. var bodyCreationObject = {
  97708. mass: impostor.getParam("mass"),
  97709. material: material
  97710. };
  97711. // A simple extend, in case native options were used.
  97712. var nativeOptions = impostor.getParam("nativeOptions");
  97713. for (var key in nativeOptions) {
  97714. if (nativeOptions.hasOwnProperty(key)) {
  97715. bodyCreationObject[key] = nativeOptions[key];
  97716. }
  97717. }
  97718. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  97719. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  97720. this.world.addEventListener("preStep", impostor.beforeStep);
  97721. this.world.addEventListener("postStep", impostor.afterStep);
  97722. impostor.physicsBody.addShape(shape);
  97723. this.world.add(impostor.physicsBody);
  97724. //try to keep the body moving in the right direction by taking old properties.
  97725. //Should be tested!
  97726. if (oldBody) {
  97727. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  97728. impostor.physicsBody[param].copy(oldBody[param]);
  97729. });
  97730. }
  97731. this._processChildMeshes(impostor);
  97732. }
  97733. //now update the body's transformation
  97734. this._updatePhysicsBodyTransformation(impostor);
  97735. };
  97736. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  97737. var _this = this;
  97738. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  97739. var currentRotation = mainImpostor.object.rotationQuaternion;
  97740. if (meshChildren.length) {
  97741. var processMesh = function (localPosition, mesh) {
  97742. if (!currentRotation || !mesh.rotationQuaternion) {
  97743. return;
  97744. }
  97745. var childImpostor = mesh.getPhysicsImpostor();
  97746. if (childImpostor) {
  97747. var parent = childImpostor.parent;
  97748. if (parent !== mainImpostor) {
  97749. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  97750. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  97751. if (childImpostor.physicsBody) {
  97752. _this.removePhysicsBody(childImpostor);
  97753. childImpostor.physicsBody = null;
  97754. }
  97755. childImpostor.parent = mainImpostor;
  97756. childImpostor.resetUpdateFlags();
  97757. 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));
  97758. //Add the mass of the children.
  97759. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  97760. }
  97761. }
  97762. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  97763. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  97764. };
  97765. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  97766. }
  97767. };
  97768. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97769. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  97770. this.world.removeEventListener("preStep", impostor.beforeStep);
  97771. this.world.removeEventListener("postStep", impostor.afterStep);
  97772. this.world.remove(impostor.physicsBody);
  97773. };
  97774. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97775. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97776. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97777. if (!mainBody || !connectedBody) {
  97778. return;
  97779. }
  97780. var constraint;
  97781. var jointData = impostorJoint.joint.jointData;
  97782. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  97783. var constraintData = {
  97784. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  97785. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  97786. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  97787. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  97788. maxForce: jointData.nativeParams.maxForce,
  97789. collideConnected: !!jointData.collision
  97790. };
  97791. switch (impostorJoint.joint.type) {
  97792. case BABYLON.PhysicsJoint.HingeJoint:
  97793. case BABYLON.PhysicsJoint.Hinge2Joint:
  97794. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  97795. break;
  97796. case BABYLON.PhysicsJoint.DistanceJoint:
  97797. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  97798. break;
  97799. case BABYLON.PhysicsJoint.SpringJoint:
  97800. var springData = jointData;
  97801. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  97802. restLength: springData.length,
  97803. stiffness: springData.stiffness,
  97804. damping: springData.damping,
  97805. localAnchorA: constraintData.pivotA,
  97806. localAnchorB: constraintData.pivotB
  97807. });
  97808. break;
  97809. case BABYLON.PhysicsJoint.LockJoint:
  97810. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  97811. break;
  97812. case BABYLON.PhysicsJoint.PointToPointJoint:
  97813. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97814. default:
  97815. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  97816. break;
  97817. }
  97818. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  97819. constraint.collideConnected = !!jointData.collision;
  97820. impostorJoint.joint.physicsJoint = constraint;
  97821. //don't add spring as constraint, as it is not one.
  97822. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97823. this.world.addConstraint(constraint);
  97824. }
  97825. else {
  97826. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  97827. constraint.applyForce();
  97828. };
  97829. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97830. }
  97831. };
  97832. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97833. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97834. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  97835. }
  97836. else {
  97837. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97838. }
  97839. };
  97840. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  97841. var index;
  97842. var mat;
  97843. for (index = 0; index < this._physicsMaterials.length; index++) {
  97844. mat = this._physicsMaterials[index];
  97845. if (mat.friction === friction && mat.restitution === restitution) {
  97846. return mat;
  97847. }
  97848. }
  97849. var currentMat = new this.BJSCANNON.Material(name);
  97850. currentMat.friction = friction;
  97851. currentMat.restitution = restitution;
  97852. this._physicsMaterials.push(currentMat);
  97853. return currentMat;
  97854. };
  97855. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  97856. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  97857. };
  97858. CannonJSPlugin.prototype._createShape = function (impostor) {
  97859. var object = impostor.object;
  97860. var returnValue;
  97861. var extendSize = impostor.getObjectExtendSize();
  97862. switch (impostor.type) {
  97863. case BABYLON.PhysicsImpostor.SphereImpostor:
  97864. var radiusX = extendSize.x;
  97865. var radiusY = extendSize.y;
  97866. var radiusZ = extendSize.z;
  97867. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  97868. break;
  97869. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  97870. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97871. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  97872. break;
  97873. case BABYLON.PhysicsImpostor.BoxImpostor:
  97874. var box = extendSize.scale(0.5);
  97875. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  97876. break;
  97877. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97878. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  97879. returnValue = new this.BJSCANNON.Plane();
  97880. break;
  97881. case BABYLON.PhysicsImpostor.MeshImpostor:
  97882. // should transform the vertex data to world coordinates!!
  97883. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  97884. var rawFaces = object.getIndices ? object.getIndices() : [];
  97885. if (!rawVerts) {
  97886. return;
  97887. }
  97888. // get only scale! so the object could transform correctly.
  97889. var oldPosition = object.position.clone();
  97890. var oldRotation = object.rotation && object.rotation.clone();
  97891. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  97892. object.position.copyFromFloats(0, 0, 0);
  97893. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97894. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97895. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97896. var transform = object.computeWorldMatrix(true);
  97897. // convert rawVerts to object space
  97898. var temp = new Array();
  97899. var index;
  97900. for (index = 0; index < rawVerts.length; index += 3) {
  97901. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  97902. }
  97903. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  97904. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  97905. //now set back the transformation!
  97906. object.position.copyFrom(oldPosition);
  97907. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  97908. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  97909. break;
  97910. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  97911. var oldPosition2 = object.position.clone();
  97912. var oldRotation2 = object.rotation && object.rotation.clone();
  97913. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  97914. object.position.copyFromFloats(0, 0, 0);
  97915. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  97916. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  97917. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  97918. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  97919. returnValue = this._createHeightmap(object);
  97920. object.position.copyFrom(oldPosition2);
  97921. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  97922. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  97923. object.computeWorldMatrix(true);
  97924. break;
  97925. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97926. returnValue = new this.BJSCANNON.Particle();
  97927. break;
  97928. }
  97929. return returnValue;
  97930. };
  97931. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  97932. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97933. var transform = object.computeWorldMatrix(true);
  97934. // convert rawVerts to object space
  97935. var temp = new Array();
  97936. var index;
  97937. for (index = 0; index < pos.length; index += 3) {
  97938. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  97939. }
  97940. pos = temp;
  97941. var matrix = new Array();
  97942. //For now pointDepth will not be used and will be automatically calculated.
  97943. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  97944. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  97945. var boundingInfo = object.getBoundingInfo();
  97946. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  97947. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  97948. var elementSize = dim * 2 / arraySize;
  97949. for (var i = 0; i < pos.length; i = i + 3) {
  97950. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  97951. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  97952. var y = -pos[i + 2] + minY;
  97953. if (!matrix[x]) {
  97954. matrix[x] = [];
  97955. }
  97956. if (!matrix[x][z]) {
  97957. matrix[x][z] = y;
  97958. }
  97959. matrix[x][z] = Math.max(y, matrix[x][z]);
  97960. }
  97961. for (var x = 0; x <= arraySize; ++x) {
  97962. if (!matrix[x]) {
  97963. var loc = 1;
  97964. while (!matrix[(x + loc) % arraySize]) {
  97965. loc++;
  97966. }
  97967. matrix[x] = matrix[(x + loc) % arraySize].slice();
  97968. //console.log("missing x", x);
  97969. }
  97970. for (var z = 0; z <= arraySize; ++z) {
  97971. if (!matrix[x][z]) {
  97972. var loc = 1;
  97973. var newValue;
  97974. while (newValue === undefined) {
  97975. newValue = matrix[x][(z + loc++) % arraySize];
  97976. }
  97977. matrix[x][z] = newValue;
  97978. }
  97979. }
  97980. }
  97981. var shape = new this.BJSCANNON.Heightfield(matrix, {
  97982. elementSize: elementSize
  97983. });
  97984. //For future reference, needed for body transformation
  97985. shape.minY = minY;
  97986. return shape;
  97987. };
  97988. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  97989. var object = impostor.object;
  97990. //make sure it is updated...
  97991. object.computeWorldMatrix && object.computeWorldMatrix(true);
  97992. // The delta between the mesh position and the mesh bounding box center
  97993. var bInfo = object.getBoundingInfo();
  97994. if (!bInfo) {
  97995. return;
  97996. }
  97997. var center = impostor.getObjectCenter();
  97998. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  97999. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  98000. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  98001. this._tmpPosition.copyFrom(center);
  98002. var quaternion = object.rotationQuaternion;
  98003. if (!quaternion) {
  98004. return;
  98005. }
  98006. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  98007. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  98008. //-90 DEG in X, precalculated
  98009. quaternion = quaternion.multiply(this._minus90X);
  98010. //Invert! (Precalculated, 90 deg in X)
  98011. //No need to clone. this will never change.
  98012. impostor.setDeltaRotation(this._plus90X);
  98013. }
  98014. //If it is a heightfield, if should be centered.
  98015. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  98016. var mesh = object;
  98017. var boundingInfo = mesh.getBoundingInfo();
  98018. //calculate the correct body position:
  98019. var rotationQuaternion = mesh.rotationQuaternion;
  98020. mesh.rotationQuaternion = this._tmpUnityRotation;
  98021. mesh.computeWorldMatrix(true);
  98022. //get original center with no rotation
  98023. var c = center.clone();
  98024. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  98025. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  98026. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  98027. mesh.setPreTransformMatrix(p);
  98028. mesh.computeWorldMatrix(true);
  98029. //calculate the translation
  98030. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  98031. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  98032. //add it inverted to the delta
  98033. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  98034. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  98035. //rotation is back
  98036. mesh.rotationQuaternion = rotationQuaternion;
  98037. mesh.setPreTransformMatrix(oldPivot);
  98038. mesh.computeWorldMatrix(true);
  98039. }
  98040. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  98041. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  98042. //this._tmpPosition.copyFrom(object.position);
  98043. }
  98044. impostor.setDeltaPosition(this._tmpDeltaPosition);
  98045. //Now update the impostor object
  98046. impostor.physicsBody.position.copy(this._tmpPosition);
  98047. impostor.physicsBody.quaternion.copy(quaternion);
  98048. };
  98049. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98050. impostor.object.position.copyFrom(impostor.physicsBody.position);
  98051. if (impostor.object.rotationQuaternion) {
  98052. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  98053. }
  98054. };
  98055. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98056. impostor.physicsBody.position.copy(newPosition);
  98057. impostor.physicsBody.quaternion.copy(newRotation);
  98058. };
  98059. CannonJSPlugin.prototype.isSupported = function () {
  98060. return this.BJSCANNON !== undefined;
  98061. };
  98062. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98063. impostor.physicsBody.velocity.copy(velocity);
  98064. };
  98065. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98066. impostor.physicsBody.angularVelocity.copy(velocity);
  98067. };
  98068. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98069. var v = impostor.physicsBody.velocity;
  98070. if (!v) {
  98071. return null;
  98072. }
  98073. return new BABYLON.Vector3(v.x, v.y, v.z);
  98074. };
  98075. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98076. var v = impostor.physicsBody.angularVelocity;
  98077. if (!v) {
  98078. return null;
  98079. }
  98080. return new BABYLON.Vector3(v.x, v.y, v.z);
  98081. };
  98082. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98083. impostor.physicsBody.mass = mass;
  98084. impostor.physicsBody.updateMassProperties();
  98085. };
  98086. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  98087. return impostor.physicsBody.mass;
  98088. };
  98089. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  98090. return impostor.physicsBody.material.friction;
  98091. };
  98092. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98093. impostor.physicsBody.material.friction = friction;
  98094. };
  98095. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98096. return impostor.physicsBody.material.restitution;
  98097. };
  98098. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98099. impostor.physicsBody.material.restitution = restitution;
  98100. };
  98101. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  98102. impostor.physicsBody.sleep();
  98103. };
  98104. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  98105. impostor.physicsBody.wakeUp();
  98106. };
  98107. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98108. joint.physicsJoint.distance = maxDistance;
  98109. };
  98110. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98111. // if (!motorIndex) {
  98112. // joint.physicsJoint.enableMotor();
  98113. // }
  98114. // }
  98115. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98116. // if (!motorIndex) {
  98117. // joint.physicsJoint.disableMotor();
  98118. // }
  98119. // }
  98120. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98121. if (!motorIndex) {
  98122. joint.physicsJoint.enableMotor();
  98123. joint.physicsJoint.setMotorSpeed(speed);
  98124. if (maxForce) {
  98125. this.setLimit(joint, maxForce);
  98126. }
  98127. }
  98128. };
  98129. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  98130. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  98131. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  98132. };
  98133. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98134. var body = impostor.physicsBody;
  98135. mesh.position.x = body.position.x;
  98136. mesh.position.y = body.position.y;
  98137. mesh.position.z = body.position.z;
  98138. if (mesh.rotationQuaternion) {
  98139. mesh.rotationQuaternion.x = body.quaternion.x;
  98140. mesh.rotationQuaternion.y = body.quaternion.y;
  98141. mesh.rotationQuaternion.z = body.quaternion.z;
  98142. mesh.rotationQuaternion.w = body.quaternion.w;
  98143. }
  98144. };
  98145. CannonJSPlugin.prototype.getRadius = function (impostor) {
  98146. var shape = impostor.physicsBody.shapes[0];
  98147. return shape.boundingSphereRadius;
  98148. };
  98149. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98150. var shape = impostor.physicsBody.shapes[0];
  98151. result.x = shape.halfExtents.x * 2;
  98152. result.y = shape.halfExtents.y * 2;
  98153. result.z = shape.halfExtents.z * 2;
  98154. };
  98155. CannonJSPlugin.prototype.dispose = function () {
  98156. };
  98157. CannonJSPlugin.prototype._extendNamespace = function () {
  98158. //this will force cannon to execute at least one step when using interpolation
  98159. var step_tmp1 = new this.BJSCANNON.Vec3();
  98160. var Engine = this.BJSCANNON;
  98161. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  98162. maxSubSteps = maxSubSteps || 10;
  98163. timeSinceLastCalled = timeSinceLastCalled || 0;
  98164. if (timeSinceLastCalled === 0) {
  98165. this.internalStep(dt);
  98166. this.time += dt;
  98167. }
  98168. else {
  98169. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  98170. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  98171. var t0 = performance.now();
  98172. for (var i = 0; i !== internalSteps; i++) {
  98173. this.internalStep(dt);
  98174. if (performance.now() - t0 > dt * 1000) {
  98175. break;
  98176. }
  98177. }
  98178. this.time += timeSinceLastCalled;
  98179. var h = this.time % dt;
  98180. var h_div_dt = h / dt;
  98181. var interpvelo = step_tmp1;
  98182. var bodies = this.bodies;
  98183. for (var j = 0; j !== bodies.length; j++) {
  98184. var b = bodies[j];
  98185. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  98186. b.position.vsub(b.previousPosition, interpvelo);
  98187. interpvelo.scale(h_div_dt, interpvelo);
  98188. b.position.vadd(interpvelo, b.interpolatedPosition);
  98189. }
  98190. else {
  98191. b.interpolatedPosition.copy(b.position);
  98192. b.interpolatedQuaternion.copy(b.quaternion);
  98193. }
  98194. }
  98195. }
  98196. };
  98197. };
  98198. return CannonJSPlugin;
  98199. }());
  98200. BABYLON.CannonJSPlugin = CannonJSPlugin;
  98201. })(BABYLON || (BABYLON = {}));
  98202. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  98203. var BABYLON;
  98204. (function (BABYLON) {
  98205. /** @hidden */
  98206. var OimoJSPlugin = /** @class */ (function () {
  98207. function OimoJSPlugin(iterations) {
  98208. this.name = "OimoJSPlugin";
  98209. this._tmpImpostorsArray = [];
  98210. this._tmpPositionVector = BABYLON.Vector3.Zero();
  98211. this.BJSOIMO = OIMO;
  98212. this.world = new this.BJSOIMO.World({
  98213. iterations: iterations
  98214. });
  98215. this.world.clear();
  98216. }
  98217. OimoJSPlugin.prototype.setGravity = function (gravity) {
  98218. this.world.gravity.copy(gravity);
  98219. };
  98220. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  98221. this.world.timeStep = timeStep;
  98222. };
  98223. OimoJSPlugin.prototype.getTimeStep = function () {
  98224. return this.world.timeStep;
  98225. };
  98226. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  98227. var _this = this;
  98228. impostors.forEach(function (impostor) {
  98229. impostor.beforeStep();
  98230. });
  98231. this.world.step();
  98232. impostors.forEach(function (impostor) {
  98233. impostor.afterStep();
  98234. //update the ordered impostors array
  98235. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  98236. });
  98237. //check for collisions
  98238. var contact = this.world.contacts;
  98239. while (contact !== null) {
  98240. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  98241. contact = contact.next;
  98242. continue;
  98243. }
  98244. //is this body colliding with any other? get the impostor
  98245. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  98246. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  98247. if (!mainImpostor || !collidingImpostor) {
  98248. contact = contact.next;
  98249. continue;
  98250. }
  98251. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  98252. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  98253. contact = contact.next;
  98254. }
  98255. };
  98256. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98257. var mass = impostor.physicsBody.mass;
  98258. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  98259. };
  98260. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98261. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  98262. this.applyImpulse(impostor, force, contactPoint);
  98263. };
  98264. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98265. var _this = this;
  98266. //parent-child relationship. Does this impostor has a parent impostor?
  98267. if (impostor.parent) {
  98268. if (impostor.physicsBody) {
  98269. this.removePhysicsBody(impostor);
  98270. //TODO is that needed?
  98271. impostor.forceUpdate();
  98272. }
  98273. return;
  98274. }
  98275. if (impostor.isBodyInitRequired()) {
  98276. var bodyConfig = {
  98277. name: impostor.uniqueId,
  98278. //Oimo must have mass, also for static objects.
  98279. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  98280. size: [],
  98281. type: [],
  98282. pos: [],
  98283. posShape: [],
  98284. rot: [],
  98285. rotShape: [],
  98286. move: impostor.getParam("mass") !== 0,
  98287. density: impostor.getParam("mass"),
  98288. friction: impostor.getParam("friction"),
  98289. restitution: impostor.getParam("restitution"),
  98290. //Supporting older versions of Oimo
  98291. world: this.world
  98292. };
  98293. var impostors = [impostor];
  98294. var addToArray = function (parent) {
  98295. if (!parent.getChildMeshes) {
  98296. return;
  98297. }
  98298. parent.getChildMeshes().forEach(function (m) {
  98299. if (m.physicsImpostor) {
  98300. impostors.push(m.physicsImpostor);
  98301. //m.physicsImpostor._init();
  98302. }
  98303. });
  98304. };
  98305. addToArray(impostor.object);
  98306. var checkWithEpsilon_1 = function (value) {
  98307. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  98308. };
  98309. var globalQuaternion_1 = new BABYLON.Quaternion();
  98310. impostors.forEach(function (i) {
  98311. if (!i.object.rotationQuaternion) {
  98312. return;
  98313. }
  98314. //get the correct bounding box
  98315. var oldQuaternion = i.object.rotationQuaternion;
  98316. globalQuaternion_1 = oldQuaternion.clone();
  98317. var rot = oldQuaternion.toEulerAngles();
  98318. var extendSize = i.getObjectExtendSize();
  98319. var radToDeg = 57.295779513082320876;
  98320. if (i === impostor) {
  98321. var center = impostor.getObjectCenter();
  98322. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  98323. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  98324. //Can also use Array.prototype.push.apply
  98325. bodyConfig.pos.push(center.x);
  98326. bodyConfig.pos.push(center.y);
  98327. bodyConfig.pos.push(center.z);
  98328. bodyConfig.posShape.push(0, 0, 0);
  98329. //tmp solution
  98330. bodyConfig.rot.push(0);
  98331. bodyConfig.rot.push(0);
  98332. bodyConfig.rot.push(0);
  98333. bodyConfig.rotShape.push(0, 0, 0);
  98334. }
  98335. else {
  98336. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  98337. bodyConfig.posShape.push(localPosition.x);
  98338. bodyConfig.posShape.push(localPosition.y);
  98339. bodyConfig.posShape.push(localPosition.z);
  98340. bodyConfig.pos.push(0, 0, 0);
  98341. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  98342. bodyConfig.rot.push(0);
  98343. bodyConfig.rot.push(0);
  98344. bodyConfig.rot.push(0);
  98345. bodyConfig.rotShape.push(rot.x * radToDeg);
  98346. bodyConfig.rotShape.push(rot.y * radToDeg);
  98347. bodyConfig.rotShape.push(rot.z * radToDeg);
  98348. }
  98349. // register mesh
  98350. switch (i.type) {
  98351. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98352. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  98353. case BABYLON.PhysicsImpostor.SphereImpostor:
  98354. var radiusX = extendSize.x;
  98355. var radiusY = extendSize.y;
  98356. var radiusZ = extendSize.z;
  98357. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  98358. bodyConfig.type.push('sphere');
  98359. //due to the way oimo works with compounds, add 3 times
  98360. bodyConfig.size.push(size);
  98361. bodyConfig.size.push(size);
  98362. bodyConfig.size.push(size);
  98363. break;
  98364. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98365. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  98366. var sizeY = checkWithEpsilon_1(extendSize.y);
  98367. bodyConfig.type.push('cylinder');
  98368. bodyConfig.size.push(sizeX);
  98369. bodyConfig.size.push(sizeY);
  98370. //due to the way oimo works with compounds, add one more value.
  98371. bodyConfig.size.push(sizeY);
  98372. break;
  98373. case BABYLON.PhysicsImpostor.PlaneImpostor:
  98374. case BABYLON.PhysicsImpostor.BoxImpostor:
  98375. default:
  98376. var sizeX = checkWithEpsilon_1(extendSize.x);
  98377. var sizeY = checkWithEpsilon_1(extendSize.y);
  98378. var sizeZ = checkWithEpsilon_1(extendSize.z);
  98379. bodyConfig.type.push('box');
  98380. //if (i === impostor) {
  98381. bodyConfig.size.push(sizeX);
  98382. bodyConfig.size.push(sizeY);
  98383. bodyConfig.size.push(sizeZ);
  98384. //} else {
  98385. // bodyConfig.size.push(0,0,0);
  98386. //}
  98387. break;
  98388. }
  98389. //actually not needed, but hey...
  98390. i.object.rotationQuaternion = oldQuaternion;
  98391. });
  98392. impostor.physicsBody = this.world.add(bodyConfig);
  98393. // set the quaternion, ignoring the previously defined (euler) rotation
  98394. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  98395. // update with delta 0, so the body will reveive the new rotation.
  98396. impostor.physicsBody.updatePosition(0);
  98397. }
  98398. else {
  98399. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  98400. }
  98401. impostor.setDeltaPosition(this._tmpPositionVector);
  98402. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  98403. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  98404. };
  98405. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98406. //impostor.physicsBody.dispose();
  98407. //Same as : (older oimo versions)
  98408. this.world.removeRigidBody(impostor.physicsBody);
  98409. };
  98410. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98411. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98412. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98413. if (!mainBody || !connectedBody) {
  98414. return;
  98415. }
  98416. var jointData = impostorJoint.joint.jointData;
  98417. var options = jointData.nativeParams || {};
  98418. var type;
  98419. var nativeJointData = {
  98420. body1: mainBody,
  98421. body2: connectedBody,
  98422. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  98423. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  98424. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  98425. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  98426. min: options.min,
  98427. max: options.max,
  98428. collision: options.collision || jointData.collision,
  98429. spring: options.spring,
  98430. //supporting older version of Oimo
  98431. world: this.world
  98432. };
  98433. switch (impostorJoint.joint.type) {
  98434. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98435. type = "jointBall";
  98436. break;
  98437. case BABYLON.PhysicsJoint.SpringJoint:
  98438. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  98439. var springData = jointData;
  98440. nativeJointData.min = springData.length || nativeJointData.min;
  98441. //Max should also be set, just make sure it is at least min
  98442. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  98443. case BABYLON.PhysicsJoint.DistanceJoint:
  98444. type = "jointDistance";
  98445. nativeJointData.max = jointData.maxDistance;
  98446. break;
  98447. case BABYLON.PhysicsJoint.PrismaticJoint:
  98448. type = "jointPrisme";
  98449. break;
  98450. case BABYLON.PhysicsJoint.SliderJoint:
  98451. type = "jointSlide";
  98452. break;
  98453. case BABYLON.PhysicsJoint.WheelJoint:
  98454. type = "jointWheel";
  98455. break;
  98456. case BABYLON.PhysicsJoint.HingeJoint:
  98457. default:
  98458. type = "jointHinge";
  98459. break;
  98460. }
  98461. nativeJointData.type = type;
  98462. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  98463. };
  98464. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98465. //Bug in Oimo prevents us from disposing a joint in the playground
  98466. //joint.joint.physicsJoint.dispose();
  98467. //So we will bruteforce it!
  98468. try {
  98469. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  98470. }
  98471. catch (e) {
  98472. BABYLON.Tools.Warn(e);
  98473. }
  98474. };
  98475. OimoJSPlugin.prototype.isSupported = function () {
  98476. return this.BJSOIMO !== undefined;
  98477. };
  98478. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98479. if (!impostor.physicsBody.sleeping) {
  98480. //TODO check that
  98481. /*if (impostor.physicsBody.shapes.next) {
  98482. var parentShape = this._getLastShape(impostor.physicsBody);
  98483. impostor.object.position.copyFrom(parentShape.position);
  98484. console.log(parentShape.position);
  98485. } else {*/
  98486. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  98487. //}
  98488. if (impostor.object.rotationQuaternion) {
  98489. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  98490. }
  98491. }
  98492. };
  98493. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98494. var body = impostor.physicsBody;
  98495. body.position.copy(newPosition);
  98496. body.orientation.copy(newRotation);
  98497. body.syncShapes();
  98498. body.awake();
  98499. };
  98500. /*private _getLastShape(body: any): any {
  98501. var lastShape = body.shapes;
  98502. while (lastShape.next) {
  98503. lastShape = lastShape.next;
  98504. }
  98505. return lastShape;
  98506. }*/
  98507. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98508. impostor.physicsBody.linearVelocity.copy(velocity);
  98509. };
  98510. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98511. impostor.physicsBody.angularVelocity.copy(velocity);
  98512. };
  98513. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98514. var v = impostor.physicsBody.linearVelocity;
  98515. if (!v) {
  98516. return null;
  98517. }
  98518. return new BABYLON.Vector3(v.x, v.y, v.z);
  98519. };
  98520. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98521. var v = impostor.physicsBody.angularVelocity;
  98522. if (!v) {
  98523. return null;
  98524. }
  98525. return new BABYLON.Vector3(v.x, v.y, v.z);
  98526. };
  98527. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98528. var staticBody = mass === 0;
  98529. //this will actually set the body's density and not its mass.
  98530. //But this is how oimo treats the mass variable.
  98531. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  98532. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  98533. };
  98534. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  98535. return impostor.physicsBody.shapes.density;
  98536. };
  98537. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  98538. return impostor.physicsBody.shapes.friction;
  98539. };
  98540. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98541. impostor.physicsBody.shapes.friction = friction;
  98542. };
  98543. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98544. return impostor.physicsBody.shapes.restitution;
  98545. };
  98546. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98547. impostor.physicsBody.shapes.restitution = restitution;
  98548. };
  98549. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  98550. impostor.physicsBody.sleep();
  98551. };
  98552. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  98553. impostor.physicsBody.awake();
  98554. };
  98555. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98556. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  98557. if (minDistance !== void 0) {
  98558. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  98559. }
  98560. };
  98561. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98562. //TODO separate rotational and transational motors.
  98563. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98564. if (motor) {
  98565. motor.setMotor(speed, maxForce);
  98566. }
  98567. };
  98568. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  98569. //TODO separate rotational and transational motors.
  98570. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98571. if (motor) {
  98572. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  98573. }
  98574. };
  98575. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98576. var body = impostor.physicsBody;
  98577. mesh.position.x = body.position.x;
  98578. mesh.position.y = body.position.y;
  98579. mesh.position.z = body.position.z;
  98580. if (mesh.rotationQuaternion) {
  98581. mesh.rotationQuaternion.x = body.orientation.x;
  98582. mesh.rotationQuaternion.y = body.orientation.y;
  98583. mesh.rotationQuaternion.z = body.orientation.z;
  98584. mesh.rotationQuaternion.w = body.orientation.s;
  98585. }
  98586. };
  98587. OimoJSPlugin.prototype.getRadius = function (impostor) {
  98588. return impostor.physicsBody.shapes.radius;
  98589. };
  98590. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98591. var shape = impostor.physicsBody.shapes;
  98592. result.x = shape.halfWidth * 2;
  98593. result.y = shape.halfHeight * 2;
  98594. result.z = shape.halfDepth * 2;
  98595. };
  98596. OimoJSPlugin.prototype.dispose = function () {
  98597. this.world.clear();
  98598. };
  98599. return OimoJSPlugin;
  98600. }());
  98601. BABYLON.OimoJSPlugin = OimoJSPlugin;
  98602. })(BABYLON || (BABYLON = {}));
  98603. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  98604. var BABYLON;
  98605. (function (BABYLON) {
  98606. /**
  98607. * Gets the current physics engine
  98608. * @returns a IPhysicsEngine or null if none attached
  98609. */
  98610. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  98611. return this._physicsEngine;
  98612. };
  98613. /**
  98614. * Enables physics to the current scene
  98615. * @param gravity defines the scene's gravity for the physics engine
  98616. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  98617. * @return a boolean indicating if the physics engine was initialized
  98618. */
  98619. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  98620. if (gravity === void 0) { gravity = null; }
  98621. if (this._physicsEngine) {
  98622. return true;
  98623. }
  98624. // Register the component to the scene
  98625. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  98626. if (!component) {
  98627. component = new PhysicsEngineSceneComponent(this);
  98628. this._addComponent(component);
  98629. }
  98630. try {
  98631. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  98632. return true;
  98633. }
  98634. catch (e) {
  98635. BABYLON.Tools.Error(e.message);
  98636. return false;
  98637. }
  98638. };
  98639. /**
  98640. * Disables and disposes the physics engine associated with the scene
  98641. */
  98642. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  98643. if (!this._physicsEngine) {
  98644. return;
  98645. }
  98646. this._physicsEngine.dispose();
  98647. this._physicsEngine = null;
  98648. };
  98649. /**
  98650. * Gets a boolean indicating if there is an active physics engine
  98651. * @returns a boolean indicating if there is an active physics engine
  98652. */
  98653. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  98654. return this._physicsEngine !== undefined;
  98655. };
  98656. /**
  98657. * Deletes a physics compound impostor
  98658. * @param compound defines the compound to delete
  98659. */
  98660. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  98661. var mesh = compound.parts[0].mesh;
  98662. if (mesh.physicsImpostor) {
  98663. mesh.physicsImpostor.dispose( /*true*/);
  98664. mesh.physicsImpostor = null;
  98665. }
  98666. };
  98667. /** @hidden */
  98668. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  98669. if (this._physicsEngine) {
  98670. this.onBeforePhysicsObservable.notifyObservers(this);
  98671. this._physicsEngine._step(step / 1000);
  98672. this.onAfterPhysicsObservable.notifyObservers(this);
  98673. }
  98674. };
  98675. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  98676. get: function () {
  98677. return this._physicsImpostor;
  98678. },
  98679. set: function (value) {
  98680. var _this = this;
  98681. if (this._physicsImpostor === value) {
  98682. return;
  98683. }
  98684. if (this._disposePhysicsObserver) {
  98685. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  98686. }
  98687. this._physicsImpostor = value;
  98688. if (value) {
  98689. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  98690. // Physics
  98691. if (_this.physicsImpostor) {
  98692. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  98693. _this.physicsImpostor = null;
  98694. }
  98695. });
  98696. }
  98697. },
  98698. enumerable: true,
  98699. configurable: true
  98700. });
  98701. /**
  98702. * Gets the current physics impostor
  98703. * @see http://doc.babylonjs.com/features/physics_engine
  98704. * @returns a physics impostor or null
  98705. */
  98706. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  98707. return this.physicsImpostor;
  98708. };
  98709. /**
  98710. * Apply a physic impulse to the mesh
  98711. * @param force defines the force to apply
  98712. * @param contactPoint defines where to apply the force
  98713. * @returns the current mesh
  98714. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  98715. */
  98716. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  98717. if (!this.physicsImpostor) {
  98718. return this;
  98719. }
  98720. this.physicsImpostor.applyImpulse(force, contactPoint);
  98721. return this;
  98722. };
  98723. /**
  98724. * Creates a physic joint between two meshes
  98725. * @param otherMesh defines the other mesh to use
  98726. * @param pivot1 defines the pivot to use on this mesh
  98727. * @param pivot2 defines the pivot to use on the other mesh
  98728. * @param options defines additional options (can be plugin dependent)
  98729. * @returns the current mesh
  98730. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  98731. */
  98732. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  98733. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  98734. return this;
  98735. }
  98736. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  98737. mainPivot: pivot1,
  98738. connectedPivot: pivot2,
  98739. nativeParams: options
  98740. });
  98741. return this;
  98742. };
  98743. /**
  98744. * Defines the physics engine scene component responsible to manage a physics engine
  98745. */
  98746. var PhysicsEngineSceneComponent = /** @class */ (function () {
  98747. /**
  98748. * Creates a new instance of the component for the given scene
  98749. * @param scene Defines the scene to register the component in
  98750. */
  98751. function PhysicsEngineSceneComponent(scene) {
  98752. var _this = this;
  98753. /**
  98754. * The component name helpful to identify the component in the list of scene components.
  98755. */
  98756. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  98757. this.scene = scene;
  98758. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  98759. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  98760. // Replace the function used to get the deterministic frame time
  98761. this.scene.getDeterministicFrameTime = function () {
  98762. if (_this.scene._physicsEngine) {
  98763. return _this.scene._physicsEngine.getTimeStep() * 1000;
  98764. }
  98765. return 1000.0 / 60.0;
  98766. };
  98767. }
  98768. /**
  98769. * Registers the component in a given scene
  98770. */
  98771. PhysicsEngineSceneComponent.prototype.register = function () {
  98772. };
  98773. /**
  98774. * Rebuilds the elements related to this component in case of
  98775. * context lost for instance.
  98776. */
  98777. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  98778. // Nothing to do for this component
  98779. };
  98780. /**
  98781. * Disposes the component and the associated ressources
  98782. */
  98783. PhysicsEngineSceneComponent.prototype.dispose = function () {
  98784. this.scene.onBeforePhysicsObservable.clear();
  98785. this.scene.onAfterPhysicsObservable.clear();
  98786. if (this.scene._physicsEngine) {
  98787. this.scene.disablePhysicsEngine();
  98788. }
  98789. };
  98790. return PhysicsEngineSceneComponent;
  98791. }());
  98792. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  98793. })(BABYLON || (BABYLON = {}));
  98794. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  98795. var BABYLON;
  98796. (function (BABYLON) {
  98797. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  98798. // All values and structures referenced from:
  98799. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  98800. var DDS_MAGIC = 0x20534444;
  98801. var
  98802. //DDSD_CAPS = 0x1,
  98803. //DDSD_HEIGHT = 0x2,
  98804. //DDSD_WIDTH = 0x4,
  98805. //DDSD_PITCH = 0x8,
  98806. //DDSD_PIXELFORMAT = 0x1000,
  98807. DDSD_MIPMAPCOUNT = 0x20000;
  98808. //DDSD_LINEARSIZE = 0x80000,
  98809. //DDSD_DEPTH = 0x800000;
  98810. // var DDSCAPS_COMPLEX = 0x8,
  98811. // DDSCAPS_MIPMAP = 0x400000,
  98812. // DDSCAPS_TEXTURE = 0x1000;
  98813. var DDSCAPS2_CUBEMAP = 0x200;
  98814. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  98815. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  98816. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  98817. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  98818. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  98819. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  98820. // DDSCAPS2_VOLUME = 0x200000;
  98821. var
  98822. //DDPF_ALPHAPIXELS = 0x1,
  98823. //DDPF_ALPHA = 0x2,
  98824. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  98825. //DDPF_YUV = 0x200,
  98826. DDPF_LUMINANCE = 0x20000;
  98827. function FourCCToInt32(value) {
  98828. return value.charCodeAt(0) +
  98829. (value.charCodeAt(1) << 8) +
  98830. (value.charCodeAt(2) << 16) +
  98831. (value.charCodeAt(3) << 24);
  98832. }
  98833. function Int32ToFourCC(value) {
  98834. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  98835. }
  98836. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  98837. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  98838. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  98839. var FOURCC_DX10 = FourCCToInt32("DX10");
  98840. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  98841. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  98842. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  98843. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  98844. var headerLengthInt = 31; // The header length in 32 bit ints
  98845. // Offsets into the header array
  98846. var off_magic = 0;
  98847. var off_size = 1;
  98848. var off_flags = 2;
  98849. var off_height = 3;
  98850. var off_width = 4;
  98851. var off_mipmapCount = 7;
  98852. var off_pfFlags = 20;
  98853. var off_pfFourCC = 21;
  98854. var off_RGBbpp = 22;
  98855. var off_RMask = 23;
  98856. var off_GMask = 24;
  98857. var off_BMask = 25;
  98858. var off_AMask = 26;
  98859. // var off_caps1 = 27;
  98860. var off_caps2 = 28;
  98861. // var off_caps3 = 29;
  98862. // var off_caps4 = 30;
  98863. var off_dxgiFormat = 32;
  98864. /**
  98865. * Class used to provide DDS decompression tools
  98866. */
  98867. var DDSTools = /** @class */ (function () {
  98868. function DDSTools() {
  98869. }
  98870. /**
  98871. * Gets DDS information from an array buffer
  98872. * @param arrayBuffer defines the array buffer to read data from
  98873. * @returns the DDS information
  98874. */
  98875. DDSTools.GetDDSInfo = function (arrayBuffer) {
  98876. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  98877. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  98878. var mipmapCount = 1;
  98879. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  98880. mipmapCount = Math.max(1, header[off_mipmapCount]);
  98881. }
  98882. var fourCC = header[off_pfFourCC];
  98883. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  98884. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98885. switch (fourCC) {
  98886. case FOURCC_D3DFMT_R16G16B16A16F:
  98887. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98888. break;
  98889. case FOURCC_D3DFMT_R32G32B32A32F:
  98890. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98891. break;
  98892. case FOURCC_DX10:
  98893. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  98894. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98895. break;
  98896. }
  98897. }
  98898. return {
  98899. width: header[off_width],
  98900. height: header[off_height],
  98901. mipmapCount: mipmapCount,
  98902. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  98903. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  98904. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  98905. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  98906. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  98907. dxgiFormat: dxgiFormat,
  98908. textureType: textureType
  98909. };
  98910. };
  98911. DDSTools._ToHalfFloat = function (value) {
  98912. if (!DDSTools._FloatView) {
  98913. DDSTools._FloatView = new Float32Array(1);
  98914. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  98915. }
  98916. DDSTools._FloatView[0] = value;
  98917. var x = DDSTools._Int32View[0];
  98918. var bits = (x >> 16) & 0x8000; /* Get the sign */
  98919. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  98920. var e = (x >> 23) & 0xff; /* Using int is faster here */
  98921. /* If zero, or denormal, or exponent underflows too much for a denormal
  98922. * half, return signed zero. */
  98923. if (e < 103) {
  98924. return bits;
  98925. }
  98926. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  98927. if (e > 142) {
  98928. bits |= 0x7c00;
  98929. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  98930. * not Inf, so make sure we set one mantissa bit too. */
  98931. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  98932. return bits;
  98933. }
  98934. /* If exponent underflows but not too much, return a denormal */
  98935. if (e < 113) {
  98936. m |= 0x0800;
  98937. /* Extra rounding may overflow and set mantissa to 0 and exponent
  98938. * to 1, which is OK. */
  98939. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  98940. return bits;
  98941. }
  98942. bits |= ((e - 112) << 10) | (m >> 1);
  98943. bits += m & 1;
  98944. return bits;
  98945. };
  98946. DDSTools._FromHalfFloat = function (value) {
  98947. var s = (value & 0x8000) >> 15;
  98948. var e = (value & 0x7C00) >> 10;
  98949. var f = value & 0x03FF;
  98950. if (e === 0) {
  98951. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  98952. }
  98953. else if (e == 0x1F) {
  98954. return f ? NaN : ((s ? -1 : 1) * Infinity);
  98955. }
  98956. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  98957. };
  98958. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98959. var destArray = new Float32Array(dataLength);
  98960. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98961. var index = 0;
  98962. for (var y = 0; y < height; y++) {
  98963. for (var x = 0; x < width; x++) {
  98964. var srcPos = (x + y * width) * 4;
  98965. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  98966. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  98967. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  98968. if (DDSTools.StoreLODInAlphaChannel) {
  98969. destArray[index + 3] = lod;
  98970. }
  98971. else {
  98972. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  98973. }
  98974. index += 4;
  98975. }
  98976. }
  98977. return destArray;
  98978. };
  98979. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98980. if (DDSTools.StoreLODInAlphaChannel) {
  98981. var destArray = new Uint16Array(dataLength);
  98982. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  98983. var index = 0;
  98984. for (var y = 0; y < height; y++) {
  98985. for (var x = 0; x < width; x++) {
  98986. var srcPos = (x + y * width) * 4;
  98987. destArray[index] = srcData[srcPos];
  98988. destArray[index + 1] = srcData[srcPos + 1];
  98989. destArray[index + 2] = srcData[srcPos + 2];
  98990. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  98991. index += 4;
  98992. }
  98993. }
  98994. return destArray;
  98995. }
  98996. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  98997. };
  98998. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  98999. if (DDSTools.StoreLODInAlphaChannel) {
  99000. var destArray = new Float32Array(dataLength);
  99001. var srcData = new Float32Array(arrayBuffer, dataOffset);
  99002. var index = 0;
  99003. for (var y = 0; y < height; y++) {
  99004. for (var x = 0; x < width; x++) {
  99005. var srcPos = (x + y * width) * 4;
  99006. destArray[index] = srcData[srcPos];
  99007. destArray[index + 1] = srcData[srcPos + 1];
  99008. destArray[index + 2] = srcData[srcPos + 2];
  99009. destArray[index + 3] = lod;
  99010. index += 4;
  99011. }
  99012. }
  99013. return destArray;
  99014. }
  99015. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  99016. };
  99017. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99018. var destArray = new Uint8Array(dataLength);
  99019. var srcData = new Float32Array(arrayBuffer, dataOffset);
  99020. var index = 0;
  99021. for (var y = 0; y < height; y++) {
  99022. for (var x = 0; x < width; x++) {
  99023. var srcPos = (x + y * width) * 4;
  99024. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  99025. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  99026. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  99027. if (DDSTools.StoreLODInAlphaChannel) {
  99028. destArray[index + 3] = lod;
  99029. }
  99030. else {
  99031. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  99032. }
  99033. index += 4;
  99034. }
  99035. }
  99036. return destArray;
  99037. };
  99038. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99039. var destArray = new Uint8Array(dataLength);
  99040. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99041. var index = 0;
  99042. for (var y = 0; y < height; y++) {
  99043. for (var x = 0; x < width; x++) {
  99044. var srcPos = (x + y * width) * 4;
  99045. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  99046. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  99047. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  99048. if (DDSTools.StoreLODInAlphaChannel) {
  99049. destArray[index + 3] = lod;
  99050. }
  99051. else {
  99052. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  99053. }
  99054. index += 4;
  99055. }
  99056. }
  99057. return destArray;
  99058. };
  99059. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  99060. var byteArray = new Uint8Array(dataLength);
  99061. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99062. var index = 0;
  99063. for (var y = 0; y < height; y++) {
  99064. for (var x = 0; x < width; x++) {
  99065. var srcPos = (x + y * width) * 4;
  99066. byteArray[index] = srcData[srcPos + rOffset];
  99067. byteArray[index + 1] = srcData[srcPos + gOffset];
  99068. byteArray[index + 2] = srcData[srcPos + bOffset];
  99069. byteArray[index + 3] = srcData[srcPos + aOffset];
  99070. index += 4;
  99071. }
  99072. }
  99073. return byteArray;
  99074. };
  99075. DDSTools._ExtractLongWordOrder = function (value) {
  99076. if (value === 0 || value === 255 || value === -16777216) {
  99077. return 0;
  99078. }
  99079. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  99080. };
  99081. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  99082. var byteArray = new Uint8Array(dataLength);
  99083. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99084. var index = 0;
  99085. for (var y = 0; y < height; y++) {
  99086. for (var x = 0; x < width; x++) {
  99087. var srcPos = (x + y * width) * 3;
  99088. byteArray[index] = srcData[srcPos + rOffset];
  99089. byteArray[index + 1] = srcData[srcPos + gOffset];
  99090. byteArray[index + 2] = srcData[srcPos + bOffset];
  99091. index += 3;
  99092. }
  99093. }
  99094. return byteArray;
  99095. };
  99096. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  99097. var byteArray = new Uint8Array(dataLength);
  99098. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99099. var index = 0;
  99100. for (var y = 0; y < height; y++) {
  99101. for (var x = 0; x < width; x++) {
  99102. var srcPos = (x + y * width);
  99103. byteArray[index] = srcData[srcPos];
  99104. index++;
  99105. }
  99106. }
  99107. return byteArray;
  99108. };
  99109. /**
  99110. * Uploads DDS Levels to a Babylon Texture
  99111. * @hidden
  99112. */
  99113. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  99114. if (lodIndex === void 0) { lodIndex = -1; }
  99115. var sphericalPolynomialFaces = null;
  99116. if (info.sphericalPolynomial) {
  99117. sphericalPolynomialFaces = new Array();
  99118. }
  99119. var ext = engine.getCaps().s3tc;
  99120. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  99121. var fourCC, width, height, dataLength = 0, dataOffset;
  99122. var byteArray, mipmapCount, mip;
  99123. var internalCompressedFormat = 0;
  99124. var blockBytes = 1;
  99125. if (header[off_magic] !== DDS_MAGIC) {
  99126. BABYLON.Tools.Error("Invalid magic number in DDS header");
  99127. return;
  99128. }
  99129. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  99130. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  99131. return;
  99132. }
  99133. if (info.isCompressed && !ext) {
  99134. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  99135. return;
  99136. }
  99137. var bpp = header[off_RGBbpp];
  99138. dataOffset = header[off_size] + 4;
  99139. var computeFormats = false;
  99140. if (info.isFourCC) {
  99141. fourCC = header[off_pfFourCC];
  99142. switch (fourCC) {
  99143. case FOURCC_DXT1:
  99144. blockBytes = 8;
  99145. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  99146. break;
  99147. case FOURCC_DXT3:
  99148. blockBytes = 16;
  99149. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  99150. break;
  99151. case FOURCC_DXT5:
  99152. blockBytes = 16;
  99153. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  99154. break;
  99155. case FOURCC_D3DFMT_R16G16B16A16F:
  99156. computeFormats = true;
  99157. break;
  99158. case FOURCC_D3DFMT_R32G32B32A32F:
  99159. computeFormats = true;
  99160. break;
  99161. case FOURCC_DX10:
  99162. // There is an additionnal header so dataOffset need to be changed
  99163. dataOffset += 5 * 4; // 5 uints
  99164. var supported = false;
  99165. switch (info.dxgiFormat) {
  99166. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  99167. computeFormats = true;
  99168. supported = true;
  99169. break;
  99170. case DXGI_FORMAT_B8G8R8X8_UNORM:
  99171. info.isRGB = true;
  99172. info.isFourCC = false;
  99173. bpp = 32;
  99174. supported = true;
  99175. break;
  99176. }
  99177. if (supported) {
  99178. break;
  99179. }
  99180. default:
  99181. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  99182. return;
  99183. }
  99184. }
  99185. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  99186. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  99187. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  99188. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  99189. if (computeFormats) {
  99190. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  99191. }
  99192. mipmapCount = 1;
  99193. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  99194. mipmapCount = Math.max(1, header[off_mipmapCount]);
  99195. }
  99196. for (var face = 0; face < faces; face++) {
  99197. width = header[off_width];
  99198. height = header[off_height];
  99199. for (mip = 0; mip < mipmapCount; ++mip) {
  99200. if (lodIndex === -1 || lodIndex === mip) {
  99201. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  99202. var i = (lodIndex === -1) ? mip : 0;
  99203. if (!info.isCompressed && info.isFourCC) {
  99204. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99205. dataLength = width * height * 4;
  99206. var floatArray = null;
  99207. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  99208. if (bpp === 128) {
  99209. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99210. if (sphericalPolynomialFaces && i == 0) {
  99211. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99212. }
  99213. }
  99214. else if (bpp === 64) {
  99215. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99216. if (sphericalPolynomialFaces && i == 0) {
  99217. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99218. }
  99219. }
  99220. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99221. }
  99222. else {
  99223. if (bpp === 128) {
  99224. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99225. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99226. if (sphericalPolynomialFaces && i == 0) {
  99227. sphericalPolynomialFaces.push(floatArray);
  99228. }
  99229. }
  99230. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  99231. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99232. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99233. if (sphericalPolynomialFaces && i == 0) {
  99234. sphericalPolynomialFaces.push(floatArray);
  99235. }
  99236. }
  99237. else { // 64
  99238. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99239. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99240. if (sphericalPolynomialFaces && i == 0) {
  99241. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99242. }
  99243. }
  99244. }
  99245. if (floatArray) {
  99246. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  99247. }
  99248. }
  99249. else if (info.isRGB) {
  99250. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99251. if (bpp === 24) {
  99252. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  99253. dataLength = width * height * 3;
  99254. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  99255. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99256. }
  99257. else { // 32
  99258. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99259. dataLength = width * height * 4;
  99260. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  99261. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99262. }
  99263. }
  99264. else if (info.isLuminance) {
  99265. var unpackAlignment = engine._getUnpackAlignement();
  99266. var unpaddedRowSize = width;
  99267. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  99268. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  99269. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  99270. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  99271. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99272. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99273. }
  99274. else {
  99275. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  99276. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  99277. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99278. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  99279. }
  99280. }
  99281. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  99282. width *= 0.5;
  99283. height *= 0.5;
  99284. width = Math.max(1.0, width);
  99285. height = Math.max(1.0, height);
  99286. }
  99287. if (currentFace !== undefined) {
  99288. // Loading a single face
  99289. break;
  99290. }
  99291. }
  99292. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  99293. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  99294. size: header[off_width],
  99295. right: sphericalPolynomialFaces[0],
  99296. left: sphericalPolynomialFaces[1],
  99297. up: sphericalPolynomialFaces[2],
  99298. down: sphericalPolynomialFaces[3],
  99299. front: sphericalPolynomialFaces[4],
  99300. back: sphericalPolynomialFaces[5],
  99301. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  99302. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  99303. gammaSpace: false,
  99304. });
  99305. }
  99306. else {
  99307. info.sphericalPolynomial = undefined;
  99308. }
  99309. };
  99310. /**
  99311. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  99312. */
  99313. DDSTools.StoreLODInAlphaChannel = false;
  99314. return DDSTools;
  99315. }());
  99316. BABYLON.DDSTools = DDSTools;
  99317. })(BABYLON || (BABYLON = {}));
  99318. //# sourceMappingURL=babylon.dds.js.map
  99319. var BABYLON;
  99320. (function (BABYLON) {
  99321. /**
  99322. * Implementation of the DDS Texture Loader.
  99323. */
  99324. var DDSTextureLoader = /** @class */ (function () {
  99325. function DDSTextureLoader() {
  99326. /**
  99327. * Defines wether the loader supports cascade loading the different faces.
  99328. */
  99329. this.supportCascades = true;
  99330. }
  99331. /**
  99332. * This returns if the loader support the current file information.
  99333. * @param extension defines the file extension of the file being loaded
  99334. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99335. * @param fallback defines the fallback internal texture if any
  99336. * @param isBase64 defines whether the texture is encoded as a base64
  99337. * @param isBuffer defines whether the texture data are stored as a buffer
  99338. * @returns true if the loader can load the specified file
  99339. */
  99340. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99341. return extension.indexOf(".dds") === 0;
  99342. };
  99343. /**
  99344. * Transform the url before loading if required.
  99345. * @param rootUrl the url of the texture
  99346. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99347. * @returns the transformed texture
  99348. */
  99349. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99350. return rootUrl;
  99351. };
  99352. /**
  99353. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99354. * @param rootUrl the url of the texture
  99355. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99356. * @returns the fallback texture
  99357. */
  99358. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99359. return null;
  99360. };
  99361. /**
  99362. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99363. * @param data contains the texture data
  99364. * @param texture defines the BabylonJS internal texture
  99365. * @param createPolynomials will be true if polynomials have been requested
  99366. * @param onLoad defines the callback to trigger once the texture is ready
  99367. * @param onError defines the callback to trigger in case of error
  99368. */
  99369. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  99370. var engine = texture.getEngine();
  99371. var info;
  99372. var loadMipmap = false;
  99373. if (Array.isArray(imgs)) {
  99374. for (var index = 0; index < imgs.length; index++) {
  99375. var data_1 = imgs[index];
  99376. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  99377. texture.width = info.width;
  99378. texture.height = info.height;
  99379. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99380. engine._unpackFlipY(info.isCompressed);
  99381. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  99382. if (!info.isFourCC && info.mipmapCount === 1) {
  99383. engine.generateMipMapsForCubemap(texture);
  99384. }
  99385. }
  99386. }
  99387. else {
  99388. var data = imgs;
  99389. info = BABYLON.DDSTools.GetDDSInfo(data);
  99390. texture.width = info.width;
  99391. texture.height = info.height;
  99392. if (createPolynomials) {
  99393. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  99394. }
  99395. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99396. engine._unpackFlipY(info.isCompressed);
  99397. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  99398. if (!info.isFourCC && info.mipmapCount === 1) {
  99399. engine.generateMipMapsForCubemap(texture);
  99400. }
  99401. }
  99402. engine._setCubeMapTextureParams(loadMipmap);
  99403. texture.isReady = true;
  99404. if (onLoad) {
  99405. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  99406. }
  99407. };
  99408. /**
  99409. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99410. * @param data contains the texture data
  99411. * @param texture defines the BabylonJS internal texture
  99412. * @param callback defines the method to call once ready to upload
  99413. */
  99414. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  99415. var info = BABYLON.DDSTools.GetDDSInfo(data);
  99416. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  99417. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  99418. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  99419. });
  99420. };
  99421. return DDSTextureLoader;
  99422. }());
  99423. // Register the loader.
  99424. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  99425. })(BABYLON || (BABYLON = {}));
  99426. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  99427. var BABYLON;
  99428. (function (BABYLON) {
  99429. /**
  99430. * Based on jsTGALoader - Javascript loader for TGA file
  99431. * By Vincent Thibault
  99432. * @see http://blog.robrowser.com/javascript-tga-loader.html
  99433. */
  99434. var TGATools = /** @class */ (function () {
  99435. function TGATools() {
  99436. }
  99437. /**
  99438. * Gets the header of a TGA file
  99439. * @param data defines the TGA data
  99440. * @returns the header
  99441. */
  99442. TGATools.GetTGAHeader = function (data) {
  99443. var offset = 0;
  99444. var header = {
  99445. id_length: data[offset++],
  99446. colormap_type: data[offset++],
  99447. image_type: data[offset++],
  99448. colormap_index: data[offset++] | data[offset++] << 8,
  99449. colormap_length: data[offset++] | data[offset++] << 8,
  99450. colormap_size: data[offset++],
  99451. origin: [
  99452. data[offset++] | data[offset++] << 8,
  99453. data[offset++] | data[offset++] << 8
  99454. ],
  99455. width: data[offset++] | data[offset++] << 8,
  99456. height: data[offset++] | data[offset++] << 8,
  99457. pixel_size: data[offset++],
  99458. flags: data[offset++]
  99459. };
  99460. return header;
  99461. };
  99462. /**
  99463. * Uploads TGA content to a Babylon Texture
  99464. * @hidden
  99465. */
  99466. TGATools.UploadContent = function (texture, data) {
  99467. // Not enough data to contain header ?
  99468. if (data.length < 19) {
  99469. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  99470. return;
  99471. }
  99472. // Read Header
  99473. var offset = 18;
  99474. var header = TGATools.GetTGAHeader(data);
  99475. // Assume it's a valid Targa file.
  99476. if (header.id_length + offset > data.length) {
  99477. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  99478. return;
  99479. }
  99480. // Skip not needed data
  99481. offset += header.id_length;
  99482. var use_rle = false;
  99483. var use_pal = false;
  99484. var use_grey = false;
  99485. // Get some informations.
  99486. switch (header.image_type) {
  99487. case TGATools._TYPE_RLE_INDEXED:
  99488. use_rle = true;
  99489. case TGATools._TYPE_INDEXED:
  99490. use_pal = true;
  99491. break;
  99492. case TGATools._TYPE_RLE_RGB:
  99493. use_rle = true;
  99494. case TGATools._TYPE_RGB:
  99495. // use_rgb = true;
  99496. break;
  99497. case TGATools._TYPE_RLE_GREY:
  99498. use_rle = true;
  99499. case TGATools._TYPE_GREY:
  99500. use_grey = true;
  99501. break;
  99502. }
  99503. var pixel_data;
  99504. // var numAlphaBits = header.flags & 0xf;
  99505. var pixel_size = header.pixel_size >> 3;
  99506. var pixel_total = header.width * header.height * pixel_size;
  99507. // Read palettes
  99508. var palettes;
  99509. if (use_pal) {
  99510. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  99511. }
  99512. // Read LRE
  99513. if (use_rle) {
  99514. pixel_data = new Uint8Array(pixel_total);
  99515. var c, count, i;
  99516. var localOffset = 0;
  99517. var pixels = new Uint8Array(pixel_size);
  99518. while (offset < pixel_total && localOffset < pixel_total) {
  99519. c = data[offset++];
  99520. count = (c & 0x7f) + 1;
  99521. // RLE pixels
  99522. if (c & 0x80) {
  99523. // Bind pixel tmp array
  99524. for (i = 0; i < pixel_size; ++i) {
  99525. pixels[i] = data[offset++];
  99526. }
  99527. // Copy pixel array
  99528. for (i = 0; i < count; ++i) {
  99529. pixel_data.set(pixels, localOffset + i * pixel_size);
  99530. }
  99531. localOffset += pixel_size * count;
  99532. }
  99533. // Raw pixels
  99534. else {
  99535. count *= pixel_size;
  99536. for (i = 0; i < count; ++i) {
  99537. pixel_data[localOffset + i] = data[offset++];
  99538. }
  99539. localOffset += count;
  99540. }
  99541. }
  99542. }
  99543. // RAW Pixels
  99544. else {
  99545. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  99546. }
  99547. // Load to texture
  99548. var x_start, y_start, x_step, y_step, y_end, x_end;
  99549. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  99550. default:
  99551. case TGATools._ORIGIN_UL:
  99552. x_start = 0;
  99553. x_step = 1;
  99554. x_end = header.width;
  99555. y_start = 0;
  99556. y_step = 1;
  99557. y_end = header.height;
  99558. break;
  99559. case TGATools._ORIGIN_BL:
  99560. x_start = 0;
  99561. x_step = 1;
  99562. x_end = header.width;
  99563. y_start = header.height - 1;
  99564. y_step = -1;
  99565. y_end = -1;
  99566. break;
  99567. case TGATools._ORIGIN_UR:
  99568. x_start = header.width - 1;
  99569. x_step = -1;
  99570. x_end = -1;
  99571. y_start = 0;
  99572. y_step = 1;
  99573. y_end = header.height;
  99574. break;
  99575. case TGATools._ORIGIN_BR:
  99576. x_start = header.width - 1;
  99577. x_step = -1;
  99578. x_end = -1;
  99579. y_start = header.height - 1;
  99580. y_step = -1;
  99581. y_end = -1;
  99582. break;
  99583. }
  99584. // Load the specify method
  99585. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  99586. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  99587. var engine = texture.getEngine();
  99588. engine._uploadDataToTextureDirectly(texture, imageData);
  99589. };
  99590. /** @hidden */
  99591. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99592. var image = pixel_data, colormap = palettes;
  99593. var width = header.width, height = header.height;
  99594. var color, i = 0, x, y;
  99595. var imageData = new Uint8Array(width * height * 4);
  99596. for (y = y_start; y !== y_end; y += y_step) {
  99597. for (x = x_start; x !== x_end; x += x_step, i++) {
  99598. color = image[i];
  99599. imageData[(x + width * y) * 4 + 3] = 255;
  99600. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  99601. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  99602. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  99603. }
  99604. }
  99605. return imageData;
  99606. };
  99607. /** @hidden */
  99608. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99609. var image = pixel_data;
  99610. var width = header.width, height = header.height;
  99611. var color, i = 0, x, y;
  99612. var imageData = new Uint8Array(width * height * 4);
  99613. for (y = y_start; y !== y_end; y += y_step) {
  99614. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99615. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  99616. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  99617. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  99618. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  99619. imageData[(x + width * y) * 4 + 0] = r;
  99620. imageData[(x + width * y) * 4 + 1] = g;
  99621. imageData[(x + width * y) * 4 + 2] = b;
  99622. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  99623. }
  99624. }
  99625. return imageData;
  99626. };
  99627. /** @hidden */
  99628. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99629. var image = pixel_data;
  99630. var width = header.width, height = header.height;
  99631. var i = 0, x, y;
  99632. var imageData = new Uint8Array(width * height * 4);
  99633. for (y = y_start; y !== y_end; y += y_step) {
  99634. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  99635. imageData[(x + width * y) * 4 + 3] = 255;
  99636. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99637. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99638. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99639. }
  99640. }
  99641. return imageData;
  99642. };
  99643. /** @hidden */
  99644. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99645. var image = pixel_data;
  99646. var width = header.width, height = header.height;
  99647. var i = 0, x, y;
  99648. var imageData = new Uint8Array(width * height * 4);
  99649. for (y = y_start; y !== y_end; y += y_step) {
  99650. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  99651. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99652. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99653. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99654. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  99655. }
  99656. }
  99657. return imageData;
  99658. };
  99659. /** @hidden */
  99660. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99661. var image = pixel_data;
  99662. var width = header.width, height = header.height;
  99663. var color, i = 0, x, y;
  99664. var imageData = new Uint8Array(width * height * 4);
  99665. for (y = y_start; y !== y_end; y += y_step) {
  99666. for (x = x_start; x !== x_end; x += x_step, i++) {
  99667. color = image[i];
  99668. imageData[(x + width * y) * 4 + 0] = color;
  99669. imageData[(x + width * y) * 4 + 1] = color;
  99670. imageData[(x + width * y) * 4 + 2] = color;
  99671. imageData[(x + width * y) * 4 + 3] = 255;
  99672. }
  99673. }
  99674. return imageData;
  99675. };
  99676. /** @hidden */
  99677. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99678. var image = pixel_data;
  99679. var width = header.width, height = header.height;
  99680. var i = 0, x, y;
  99681. var imageData = new Uint8Array(width * height * 4);
  99682. for (y = y_start; y !== y_end; y += y_step) {
  99683. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99684. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  99685. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  99686. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99687. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  99688. }
  99689. }
  99690. return imageData;
  99691. };
  99692. //private static _TYPE_NO_DATA = 0;
  99693. TGATools._TYPE_INDEXED = 1;
  99694. TGATools._TYPE_RGB = 2;
  99695. TGATools._TYPE_GREY = 3;
  99696. TGATools._TYPE_RLE_INDEXED = 9;
  99697. TGATools._TYPE_RLE_RGB = 10;
  99698. TGATools._TYPE_RLE_GREY = 11;
  99699. TGATools._ORIGIN_MASK = 0x30;
  99700. TGATools._ORIGIN_SHIFT = 0x04;
  99701. TGATools._ORIGIN_BL = 0x00;
  99702. TGATools._ORIGIN_BR = 0x01;
  99703. TGATools._ORIGIN_UL = 0x02;
  99704. TGATools._ORIGIN_UR = 0x03;
  99705. return TGATools;
  99706. }());
  99707. BABYLON.TGATools = TGATools;
  99708. })(BABYLON || (BABYLON = {}));
  99709. //# sourceMappingURL=babylon.tga.js.map
  99710. var BABYLON;
  99711. (function (BABYLON) {
  99712. /**
  99713. * Implementation of the TGA Texture Loader.
  99714. */
  99715. var TGATextureLoader = /** @class */ (function () {
  99716. function TGATextureLoader() {
  99717. /**
  99718. * Defines wether the loader supports cascade loading the different faces.
  99719. */
  99720. this.supportCascades = false;
  99721. }
  99722. /**
  99723. * This returns if the loader support the current file information.
  99724. * @param extension defines the file extension of the file being loaded
  99725. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99726. * @param fallback defines the fallback internal texture if any
  99727. * @param isBase64 defines whether the texture is encoded as a base64
  99728. * @param isBuffer defines whether the texture data are stored as a buffer
  99729. * @returns true if the loader can load the specified file
  99730. */
  99731. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99732. return extension.indexOf(".tga") === 0;
  99733. };
  99734. /**
  99735. * Transform the url before loading if required.
  99736. * @param rootUrl the url of the texture
  99737. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99738. * @returns the transformed texture
  99739. */
  99740. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99741. return rootUrl;
  99742. };
  99743. /**
  99744. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99745. * @param rootUrl the url of the texture
  99746. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99747. * @returns the fallback texture
  99748. */
  99749. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99750. return null;
  99751. };
  99752. /**
  99753. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99754. * @param data contains the texture data
  99755. * @param texture defines the BabylonJS internal texture
  99756. * @param createPolynomials will be true if polynomials have been requested
  99757. * @param onLoad defines the callback to trigger once the texture is ready
  99758. * @param onError defines the callback to trigger in case of error
  99759. */
  99760. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99761. throw ".env not supported in Cube.";
  99762. };
  99763. /**
  99764. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99765. * @param data contains the texture data
  99766. * @param texture defines the BabylonJS internal texture
  99767. * @param callback defines the method to call once ready to upload
  99768. */
  99769. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  99770. var uintData = new Uint8Array(data);
  99771. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  99772. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  99773. BABYLON.TGATools.UploadContent(texture, uintData);
  99774. });
  99775. };
  99776. return TGATextureLoader;
  99777. }());
  99778. // Register the loader.
  99779. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  99780. })(BABYLON || (BABYLON = {}));
  99781. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  99782. var BABYLON;
  99783. (function (BABYLON) {
  99784. /**
  99785. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  99786. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  99787. */
  99788. var KhronosTextureContainer = /** @class */ (function () {
  99789. /**
  99790. * Creates a new KhronosTextureContainer
  99791. * @param arrayBuffer contents of the KTX container file
  99792. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  99793. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  99794. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  99795. */
  99796. function KhronosTextureContainer(
  99797. /** contents of the KTX container file */
  99798. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  99799. this.arrayBuffer = arrayBuffer;
  99800. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  99801. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  99802. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  99803. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  99804. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  99805. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  99806. BABYLON.Tools.Error("texture missing KTX identifier");
  99807. return;
  99808. }
  99809. // load the reset of the header in native 32 bit int
  99810. var header = new Int32Array(this.arrayBuffer, 12, 13);
  99811. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  99812. var oppositeEndianess = header[0] === 0x01020304;
  99813. // read all the header elements in order they exist in the file, without modification (sans endainness)
  99814. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  99815. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  99816. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  99817. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  99818. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  99819. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  99820. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  99821. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  99822. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  99823. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  99824. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  99825. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  99826. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  99827. if (this.glType !== 0) {
  99828. BABYLON.Tools.Error("only compressed formats currently supported");
  99829. return;
  99830. }
  99831. else {
  99832. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  99833. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  99834. }
  99835. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  99836. BABYLON.Tools.Error("only 2D textures currently supported");
  99837. return;
  99838. }
  99839. if (this.numberOfArrayElements !== 0) {
  99840. BABYLON.Tools.Error("texture arrays not currently supported");
  99841. return;
  99842. }
  99843. if (this.numberOfFaces !== facesExpected) {
  99844. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  99845. return;
  99846. }
  99847. // we now have a completely validated file, so could use existence of loadType as success
  99848. // would need to make this more elaborate & adjust checks above to support more than one load type
  99849. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  99850. }
  99851. //
  99852. /**
  99853. * Revert the endianness of a value.
  99854. * Not as fast hardware based, but will probably never need to use
  99855. * @param val defines the value to convert
  99856. * @returns the new value
  99857. */
  99858. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  99859. return ((val & 0xFF) << 24)
  99860. | ((val & 0xFF00) << 8)
  99861. | ((val >> 8) & 0xFF00)
  99862. | ((val >> 24) & 0xFF);
  99863. };
  99864. /**
  99865. * Uploads KTX content to a Babylon Texture.
  99866. * It is assumed that the texture has already been created & is currently bound
  99867. * @hidden
  99868. */
  99869. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  99870. switch (this.loadType) {
  99871. case KhronosTextureContainer.COMPRESSED_2D:
  99872. this._upload2DCompressedLevels(texture, loadMipmaps);
  99873. break;
  99874. case KhronosTextureContainer.TEX_2D:
  99875. case KhronosTextureContainer.COMPRESSED_3D:
  99876. case KhronosTextureContainer.TEX_3D:
  99877. }
  99878. };
  99879. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  99880. // initialize width & height for level 1
  99881. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  99882. var width = this.pixelWidth;
  99883. var height = this.pixelHeight;
  99884. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  99885. for (var level = 0; level < mipmapCount; level++) {
  99886. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  99887. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  99888. for (var face = 0; face < this.numberOfFaces; face++) {
  99889. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  99890. var engine = texture.getEngine();
  99891. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  99892. dataOffset += imageSize; // add size of the image for the next face/mipmap
  99893. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  99894. }
  99895. width = Math.max(1.0, width * 0.5);
  99896. height = Math.max(1.0, height * 0.5);
  99897. }
  99898. };
  99899. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  99900. // load types
  99901. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  99902. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  99903. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  99904. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  99905. return KhronosTextureContainer;
  99906. }());
  99907. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  99908. })(BABYLON || (BABYLON = {}));
  99909. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  99910. var BABYLON;
  99911. (function (BABYLON) {
  99912. /**
  99913. * Implementation of the KTX Texture Loader.
  99914. */
  99915. var KTXTextureLoader = /** @class */ (function () {
  99916. function KTXTextureLoader() {
  99917. /**
  99918. * Defines wether the loader supports cascade loading the different faces.
  99919. */
  99920. this.supportCascades = false;
  99921. }
  99922. /**
  99923. * This returns if the loader support the current file information.
  99924. * @param extension defines the file extension of the file being loaded
  99925. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99926. * @param fallback defines the fallback internal texture if any
  99927. * @param isBase64 defines whether the texture is encoded as a base64
  99928. * @param isBuffer defines whether the texture data are stored as a buffer
  99929. * @returns true if the loader can load the specified file
  99930. */
  99931. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99932. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  99933. return true;
  99934. }
  99935. return false;
  99936. };
  99937. /**
  99938. * Transform the url before loading if required.
  99939. * @param rootUrl the url of the texture
  99940. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99941. * @returns the transformed texture
  99942. */
  99943. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99944. var lastDot = rootUrl.lastIndexOf('.');
  99945. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  99946. };
  99947. /**
  99948. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99949. * @param rootUrl the url of the texture
  99950. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99951. * @returns the fallback texture
  99952. */
  99953. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99954. // remove the format appended to the rootUrl in the original createCubeTexture call.
  99955. var exp = new RegExp("" + textureFormatInUse + "$");
  99956. return rootUrl.replace(exp, "");
  99957. };
  99958. /**
  99959. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99960. * @param data contains the texture data
  99961. * @param texture defines the BabylonJS internal texture
  99962. * @param createPolynomials will be true if polynomials have been requested
  99963. * @param onLoad defines the callback to trigger once the texture is ready
  99964. * @param onError defines the callback to trigger in case of error
  99965. */
  99966. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99967. if (Array.isArray(data)) {
  99968. return;
  99969. }
  99970. var engine = texture.getEngine();
  99971. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  99972. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  99973. engine._unpackFlipY(true);
  99974. ktx.uploadLevels(texture, texture.generateMipMaps);
  99975. texture.width = ktx.pixelWidth;
  99976. texture.height = ktx.pixelHeight;
  99977. engine._setCubeMapTextureParams(loadMipmap);
  99978. texture.isReady = true;
  99979. };
  99980. /**
  99981. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99982. * @param data contains the texture data
  99983. * @param texture defines the BabylonJS internal texture
  99984. * @param callback defines the method to call once ready to upload
  99985. */
  99986. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  99987. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  99988. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  99989. ktx.uploadLevels(texture, texture.generateMipMaps);
  99990. });
  99991. };
  99992. return KTXTextureLoader;
  99993. }());
  99994. // Register the loader.
  99995. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  99996. })(BABYLON || (BABYLON = {}));
  99997. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  99998. var BABYLON;
  99999. (function (BABYLON) {
  100000. /**
  100001. * Sets of helpers addressing the serialization and deserialization of environment texture
  100002. * stored in a BabylonJS env file.
  100003. * Those files are usually stored as .env files.
  100004. */
  100005. var EnvironmentTextureTools = /** @class */ (function () {
  100006. function EnvironmentTextureTools() {
  100007. }
  100008. /**
  100009. * Gets the environment info from an env file.
  100010. * @param data The array buffer containing the .env bytes.
  100011. * @returns the environment file info (the json header) if successfully parsed.
  100012. */
  100013. EnvironmentTextureTools.GetEnvInfo = function (data) {
  100014. var dataView = new DataView(data);
  100015. var pos = 0;
  100016. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100017. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  100018. BABYLON.Tools.Error('Not a babylon environment map');
  100019. return null;
  100020. }
  100021. }
  100022. // Read json manifest - collect characters up to null terminator
  100023. var manifestString = '';
  100024. var charCode = 0x00;
  100025. while ((charCode = dataView.getUint8(pos++))) {
  100026. manifestString += String.fromCharCode(charCode);
  100027. }
  100028. var manifest = JSON.parse(manifestString);
  100029. if (manifest.specular) {
  100030. // Extend the header with the position of the payload.
  100031. manifest.specular.specularDataPosition = pos;
  100032. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  100033. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  100034. }
  100035. return manifest;
  100036. };
  100037. /**
  100038. * Creates an environment texture from a loaded cube texture.
  100039. * @param texture defines the cube texture to convert in env file
  100040. * @return a promise containing the environment data if succesfull.
  100041. */
  100042. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  100043. var _this = this;
  100044. var internalTexture = texture.getInternalTexture();
  100045. if (!internalTexture) {
  100046. return Promise.reject("The cube texture is invalid.");
  100047. }
  100048. if (!texture._prefiltered) {
  100049. return Promise.reject("The cube texture is invalid (not prefiltered).");
  100050. }
  100051. var engine = internalTexture.getEngine();
  100052. if (engine && engine.premultipliedAlpha) {
  100053. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  100054. }
  100055. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  100056. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  100057. }
  100058. var canvas = engine.getRenderingCanvas();
  100059. if (!canvas) {
  100060. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  100061. }
  100062. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100063. if (!engine.getCaps().textureFloatRender) {
  100064. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100065. if (!engine.getCaps().textureHalfFloatRender) {
  100066. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  100067. }
  100068. }
  100069. var cubeWidth = internalTexture.width;
  100070. var hostingScene = new BABYLON.Scene(engine);
  100071. var specularTextures = {};
  100072. var promises = [];
  100073. // Read and collect all mipmaps data from the cube.
  100074. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  100075. mipmapsCount = Math.round(mipmapsCount);
  100076. var _loop_1 = function (i) {
  100077. var faceWidth = Math.pow(2, mipmapsCount - i);
  100078. var _loop_2 = function (face) {
  100079. var data = texture.readPixels(face, i);
  100080. // Creates a temp texture with the face data.
  100081. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  100082. // And rgbdEncode them.
  100083. var promise = new Promise(function (resolve, reject) {
  100084. 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);
  100085. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100086. rgbdPostProcess.onApply = function (effect) {
  100087. effect._bindTexture("textureSampler", tempTexture);
  100088. };
  100089. // As the process needs to happen on the main canvas, keep track of the current size
  100090. var currentW = engine.getRenderWidth();
  100091. var currentH = engine.getRenderHeight();
  100092. // Set the desired size for the texture
  100093. engine.setSize(faceWidth, faceWidth);
  100094. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  100095. // Reading datas from WebGL
  100096. BABYLON.Tools.ToBlob(canvas, function (blob) {
  100097. var fileReader = new FileReader();
  100098. fileReader.onload = function (event) {
  100099. var arrayBuffer = event.target.result;
  100100. specularTextures[i * 6 + face] = arrayBuffer;
  100101. resolve();
  100102. };
  100103. fileReader.readAsArrayBuffer(blob);
  100104. });
  100105. // Reapply the previous canvas size
  100106. engine.setSize(currentW, currentH);
  100107. });
  100108. });
  100109. promises.push(promise);
  100110. };
  100111. // All faces of the cube.
  100112. for (var face = 0; face < 6; face++) {
  100113. _loop_2(face);
  100114. }
  100115. };
  100116. for (var i = 0; i <= mipmapsCount; i++) {
  100117. _loop_1(i);
  100118. }
  100119. // Once all the textures haves been collected as RGBD stored in PNGs
  100120. return Promise.all(promises).then(function () {
  100121. // We can delete the hosting scene keeping track of all the creation objects
  100122. hostingScene.dispose();
  100123. // Creates the json header for the env texture
  100124. var info = {
  100125. version: 1,
  100126. width: cubeWidth,
  100127. irradiance: _this._CreateEnvTextureIrradiance(texture),
  100128. specular: {
  100129. mipmaps: [],
  100130. lodGenerationScale: texture.lodGenerationScale
  100131. }
  100132. };
  100133. // Sets the specular image data information
  100134. var position = 0;
  100135. for (var i = 0; i <= mipmapsCount; i++) {
  100136. for (var face = 0; face < 6; face++) {
  100137. var byteLength = specularTextures[i * 6 + face].byteLength;
  100138. info.specular.mipmaps.push({
  100139. length: byteLength,
  100140. position: position
  100141. });
  100142. position += byteLength;
  100143. }
  100144. }
  100145. // Encode the JSON as an array buffer
  100146. var infoString = JSON.stringify(info);
  100147. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  100148. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  100149. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  100150. infoView[i] = infoString.charCodeAt(i);
  100151. }
  100152. // Ends up with a null terminator for easier parsing
  100153. infoView[infoString.length] = 0x00;
  100154. // Computes the final required size and creates the storage
  100155. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  100156. var finalBuffer = new ArrayBuffer(totalSize);
  100157. var finalBufferView = new Uint8Array(finalBuffer);
  100158. var dataView = new DataView(finalBuffer);
  100159. // Copy the magic bytes identifying the file in
  100160. var pos = 0;
  100161. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100162. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  100163. }
  100164. // Add the json info
  100165. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  100166. pos += infoBuffer.byteLength;
  100167. // Finally inserts the texture data
  100168. for (var i = 0; i <= mipmapsCount; i++) {
  100169. for (var face = 0; face < 6; face++) {
  100170. var dataBuffer = specularTextures[i * 6 + face];
  100171. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  100172. pos += dataBuffer.byteLength;
  100173. }
  100174. }
  100175. // Voila
  100176. return finalBuffer;
  100177. });
  100178. };
  100179. /**
  100180. * Creates a JSON representation of the spherical data.
  100181. * @param texture defines the texture containing the polynomials
  100182. * @return the JSON representation of the spherical info
  100183. */
  100184. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  100185. var polynmials = texture.sphericalPolynomial;
  100186. if (polynmials == null) {
  100187. return null;
  100188. }
  100189. return {
  100190. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  100191. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  100192. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  100193. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  100194. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  100195. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  100196. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  100197. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  100198. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  100199. };
  100200. };
  100201. /**
  100202. * Uploads the texture info contained in the env file to the GPU.
  100203. * @param texture defines the internal texture to upload to
  100204. * @param arrayBuffer defines the buffer cotaining the data to load
  100205. * @param info defines the texture info retrieved through the GetEnvInfo method
  100206. * @returns a promise
  100207. */
  100208. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  100209. if (info.version !== 1) {
  100210. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  100211. }
  100212. var specularInfo = info.specular;
  100213. if (!specularInfo) {
  100214. // Nothing else parsed so far
  100215. return Promise.resolve();
  100216. }
  100217. // Double checks the enclosed info
  100218. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  100219. mipmapsCount = Math.round(mipmapsCount) + 1;
  100220. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  100221. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  100222. }
  100223. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  100224. var imageData = new Array(mipmapsCount);
  100225. for (var i = 0; i < mipmapsCount; i++) {
  100226. imageData[i] = new Array(6);
  100227. for (var face = 0; face < 6; face++) {
  100228. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  100229. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  100230. }
  100231. }
  100232. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  100233. };
  100234. /**
  100235. * Uploads the levels of image data to the GPU.
  100236. * @param texture defines the internal texture to upload to
  100237. * @param imageData defines the array buffer views of image data [mipmap][face]
  100238. * @returns a promise
  100239. */
  100240. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  100241. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  100242. throw new Error("Texture size must be a power of two");
  100243. }
  100244. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  100245. // Gets everything ready.
  100246. var engine = texture.getEngine();
  100247. var expandTexture = false;
  100248. var generateNonLODTextures = false;
  100249. var rgbdPostProcess = null;
  100250. var cubeRtt = null;
  100251. var lodTextures = null;
  100252. var caps = engine.getCaps();
  100253. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  100254. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100255. texture.generateMipMaps = true;
  100256. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  100257. // Add extra process if texture lod is not supported
  100258. if (!caps.textureLOD) {
  100259. expandTexture = false;
  100260. generateNonLODTextures = true;
  100261. lodTextures = {};
  100262. }
  100263. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  100264. else if (engine.webGLVersion < 2) {
  100265. expandTexture = false;
  100266. }
  100267. // If half float available we can uncompress the texture
  100268. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  100269. expandTexture = true;
  100270. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100271. }
  100272. // If full float available we can uncompress the texture
  100273. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  100274. expandTexture = true;
  100275. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100276. }
  100277. // Expand the texture if possible
  100278. if (expandTexture) {
  100279. // Simply run through the decode PP
  100280. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  100281. texture._isRGBD = false;
  100282. texture.invertY = false;
  100283. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  100284. generateDepthBuffer: false,
  100285. generateMipMaps: true,
  100286. generateStencilBuffer: false,
  100287. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  100288. type: texture.type,
  100289. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  100290. });
  100291. }
  100292. else {
  100293. texture._isRGBD = true;
  100294. texture.invertY = true;
  100295. // In case of missing support, applies the same patch than DDS files.
  100296. if (generateNonLODTextures) {
  100297. var mipSlices = 3;
  100298. var scale = texture._lodGenerationScale;
  100299. var offset = texture._lodGenerationOffset;
  100300. for (var i = 0; i < mipSlices; i++) {
  100301. //compute LOD from even spacing in smoothness (matching shader calculation)
  100302. var smoothness = i / (mipSlices - 1);
  100303. var roughness = 1 - smoothness;
  100304. var minLODIndex = offset; // roughness = 0
  100305. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  100306. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  100307. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  100308. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  100309. glTextureFromLod.isCube = true;
  100310. glTextureFromLod.invertY = true;
  100311. glTextureFromLod.generateMipMaps = false;
  100312. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  100313. // Wrap in a base texture for easy binding.
  100314. var lodTexture = new BABYLON.BaseTexture(null);
  100315. lodTexture.isCube = true;
  100316. lodTexture._texture = glTextureFromLod;
  100317. lodTextures[mipmapIndex] = lodTexture;
  100318. switch (i) {
  100319. case 0:
  100320. texture._lodTextureLow = lodTexture;
  100321. break;
  100322. case 1:
  100323. texture._lodTextureMid = lodTexture;
  100324. break;
  100325. case 2:
  100326. texture._lodTextureHigh = lodTexture;
  100327. break;
  100328. }
  100329. }
  100330. }
  100331. }
  100332. var promises = [];
  100333. var _loop_3 = function (i) {
  100334. var _loop_4 = function (face) {
  100335. // Constructs an image element from image data
  100336. var bytes = imageData[i][face];
  100337. var blob = new Blob([bytes], { type: 'image/png' });
  100338. var url = URL.createObjectURL(blob);
  100339. var image = new Image();
  100340. image.src = url;
  100341. // Enqueue promise to upload to the texture.
  100342. var promise = new Promise(function (resolve, reject) {
  100343. image.onload = function () {
  100344. if (expandTexture) {
  100345. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  100346. reject(message);
  100347. }, image);
  100348. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100349. // Uncompress the data to a RTT
  100350. rgbdPostProcess.onApply = function (effect) {
  100351. effect._bindTexture("textureSampler", tempTexture_1);
  100352. effect.setFloat2("scale", 1, 1);
  100353. };
  100354. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  100355. // Cleanup
  100356. engine.restoreDefaultFramebuffer();
  100357. tempTexture_1.dispose();
  100358. window.URL.revokeObjectURL(url);
  100359. resolve();
  100360. });
  100361. }
  100362. else {
  100363. engine._uploadImageToTexture(texture, image, face, i);
  100364. // Upload the face to the non lod texture support
  100365. if (generateNonLODTextures) {
  100366. var lodTexture = lodTextures[i];
  100367. if (lodTexture) {
  100368. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  100369. }
  100370. }
  100371. resolve();
  100372. }
  100373. };
  100374. image.onerror = function (error) {
  100375. reject(error);
  100376. };
  100377. });
  100378. promises.push(promise);
  100379. };
  100380. // All faces
  100381. for (var face = 0; face < 6; face++) {
  100382. _loop_4(face);
  100383. }
  100384. };
  100385. // All mipmaps up to provided number of images
  100386. for (var i = 0; i < imageData.length; i++) {
  100387. _loop_3(i);
  100388. }
  100389. // Fill remaining mipmaps with black textures.
  100390. if (imageData.length < mipmapsCount) {
  100391. var data = void 0;
  100392. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  100393. var dataLength = size * size * 4;
  100394. switch (texture.type) {
  100395. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  100396. data = new Uint8Array(dataLength);
  100397. break;
  100398. }
  100399. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  100400. data = new Uint16Array(dataLength);
  100401. break;
  100402. }
  100403. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  100404. data = new Float32Array(dataLength);
  100405. break;
  100406. }
  100407. }
  100408. for (var i = imageData.length; i < mipmapsCount; i++) {
  100409. for (var face = 0; face < 6; face++) {
  100410. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  100411. }
  100412. }
  100413. }
  100414. // Once all done, finishes the cleanup and return
  100415. return Promise.all(promises).then(function () {
  100416. // Release temp RTT.
  100417. if (cubeRtt) {
  100418. engine._releaseFramebufferObjects(cubeRtt);
  100419. cubeRtt._swapAndDie(texture);
  100420. }
  100421. // Release temp Post Process.
  100422. if (rgbdPostProcess) {
  100423. rgbdPostProcess.dispose();
  100424. }
  100425. // Flag internal texture as ready in case they are in use.
  100426. if (generateNonLODTextures) {
  100427. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  100428. texture._lodTextureHigh._texture.isReady = true;
  100429. }
  100430. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  100431. texture._lodTextureMid._texture.isReady = true;
  100432. }
  100433. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  100434. texture._lodTextureLow._texture.isReady = true;
  100435. }
  100436. }
  100437. });
  100438. };
  100439. /**
  100440. * Uploads spherical polynomials information to the texture.
  100441. * @param texture defines the texture we are trying to upload the information to
  100442. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  100443. */
  100444. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  100445. if (info.version !== 1) {
  100446. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  100447. }
  100448. var irradianceInfo = info.irradiance;
  100449. if (!irradianceInfo) {
  100450. return;
  100451. }
  100452. var sp = new BABYLON.SphericalPolynomial();
  100453. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  100454. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  100455. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  100456. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  100457. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  100458. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  100459. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  100460. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  100461. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  100462. texture._sphericalPolynomial = sp;
  100463. };
  100464. /**
  100465. * Magic number identifying the env file.
  100466. */
  100467. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  100468. return EnvironmentTextureTools;
  100469. }());
  100470. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  100471. })(BABYLON || (BABYLON = {}));
  100472. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  100473. var BABYLON;
  100474. (function (BABYLON) {
  100475. /**
  100476. * Implementation of the ENV Texture Loader.
  100477. */
  100478. var ENVTextureLoader = /** @class */ (function () {
  100479. function ENVTextureLoader() {
  100480. /**
  100481. * Defines wether the loader supports cascade loading the different faces.
  100482. */
  100483. this.supportCascades = false;
  100484. }
  100485. /**
  100486. * This returns if the loader support the current file information.
  100487. * @param extension defines the file extension of the file being loaded
  100488. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100489. * @param fallback defines the fallback internal texture if any
  100490. * @param isBase64 defines whether the texture is encoded as a base64
  100491. * @param isBuffer defines whether the texture data are stored as a buffer
  100492. * @returns true if the loader can load the specified file
  100493. */
  100494. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100495. return extension.indexOf(".env") === 0;
  100496. };
  100497. /**
  100498. * Transform the url before loading if required.
  100499. * @param rootUrl the url of the texture
  100500. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100501. * @returns the transformed texture
  100502. */
  100503. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100504. return rootUrl;
  100505. };
  100506. /**
  100507. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100508. * @param rootUrl the url of the texture
  100509. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100510. * @returns the fallback texture
  100511. */
  100512. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100513. return null;
  100514. };
  100515. /**
  100516. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100517. * @param data contains the texture data
  100518. * @param texture defines the BabylonJS internal texture
  100519. * @param createPolynomials will be true if polynomials have been requested
  100520. * @param onLoad defines the callback to trigger once the texture is ready
  100521. * @param onError defines the callback to trigger in case of error
  100522. */
  100523. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100524. if (Array.isArray(data)) {
  100525. return;
  100526. }
  100527. data = data;
  100528. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  100529. if (info) {
  100530. texture.width = info.width;
  100531. texture.height = info.width;
  100532. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  100533. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  100534. texture.isReady = true;
  100535. if (onLoad) {
  100536. onLoad();
  100537. }
  100538. });
  100539. }
  100540. else if (onError) {
  100541. onError("Can not parse the environment file", null);
  100542. }
  100543. };
  100544. /**
  100545. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100546. * @param data contains the texture data
  100547. * @param texture defines the BabylonJS internal texture
  100548. * @param callback defines the method to call once ready to upload
  100549. */
  100550. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  100551. throw ".env not supported in 2d.";
  100552. };
  100553. return ENVTextureLoader;
  100554. }());
  100555. // Register the loader.
  100556. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  100557. })(BABYLON || (BABYLON = {}));
  100558. //# sourceMappingURL=babylon.envTextureLoader.js.map
  100559. var BABYLON;
  100560. (function (BABYLON) {
  100561. /**
  100562. * Renders a layer on top of an existing scene
  100563. */
  100564. var UtilityLayerRenderer = /** @class */ (function () {
  100565. /**
  100566. * Instantiates a UtilityLayerRenderer
  100567. * @param originalScene the original scene that will be rendered on top of
  100568. */
  100569. function UtilityLayerRenderer(
  100570. /** the original scene that will be rendered on top of */
  100571. originalScene) {
  100572. var _this = this;
  100573. this.originalScene = originalScene;
  100574. this._pointerCaptures = {};
  100575. this._lastPointerEvents = {};
  100576. /**
  100577. * If the utility layer should automatically be rendered on top of existing scene
  100578. */
  100579. this.shouldRender = true;
  100580. /**
  100581. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  100582. */
  100583. this.onlyCheckPointerDownEvents = true;
  100584. /**
  100585. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  100586. */
  100587. this.processAllEvents = false;
  100588. /**
  100589. * Observable raised when the pointer move from the utility layer scene to the main scene
  100590. */
  100591. this.onPointerOutObservable = new BABYLON.Observable();
  100592. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  100593. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  100594. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  100595. this.utilityLayerScene._allowPostProcessClearColor = false;
  100596. originalScene.getEngine().scenes.pop();
  100597. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  100598. this.utilityLayerScene.detachControl();
  100599. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  100600. if (!_this.processAllEvents) {
  100601. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  100602. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  100603. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  100604. return;
  100605. }
  100606. }
  100607. var pointerEvent = (prePointerInfo.event);
  100608. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  100609. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100610. return;
  100611. }
  100612. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  100613. if (!prePointerInfo.ray && utilityScenePick) {
  100614. prePointerInfo.ray = utilityScenePick.ray;
  100615. }
  100616. // always fire the prepointer oversvable
  100617. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  100618. // allow every non pointer down event to flow to the utility layer
  100619. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  100620. if (!prePointerInfo.skipOnPointerObservable) {
  100621. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100622. }
  100623. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  100624. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100625. }
  100626. return;
  100627. }
  100628. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  100629. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  100630. if (utilityScenePick && utilityScenePick.hit) {
  100631. if (!prePointerInfo.skipOnPointerObservable) {
  100632. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100633. }
  100634. prePointerInfo.skipOnPointerObservable = true;
  100635. }
  100636. }
  100637. else {
  100638. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  100639. var pointerEvent_1 = (prePointerInfo.event);
  100640. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  100641. if (originalScenePick && utilityScenePick) {
  100642. // No pick in utility scene
  100643. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  100644. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100645. // We touched an utility mesh present in the main scene
  100646. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100647. prePointerInfo.skipOnPointerObservable = true;
  100648. }
  100649. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100650. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  100651. }
  100652. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100653. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100654. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100655. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100656. }
  100657. }
  100658. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  100659. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  100660. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  100661. // If a previous utility layer set this, do not unset this
  100662. if (!prePointerInfo.skipOnPointerObservable) {
  100663. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  100664. }
  100665. }
  100666. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  100667. // We have a pick in both scenes but main is closer than utility
  100668. // We touched an utility mesh present in the main scene
  100669. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100670. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100671. prePointerInfo.skipOnPointerObservable = true;
  100672. }
  100673. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100674. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100675. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100676. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100677. }
  100678. }
  100679. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  100680. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  100681. }
  100682. }
  100683. }
  100684. });
  100685. // Render directly on top of existing scene without clearing
  100686. this.utilityLayerScene.autoClear = false;
  100687. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  100688. if (_this.shouldRender) {
  100689. _this.render();
  100690. }
  100691. });
  100692. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  100693. _this.dispose();
  100694. });
  100695. this._updateCamera();
  100696. }
  100697. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  100698. /**
  100699. * 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)
  100700. */
  100701. get: function () {
  100702. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  100703. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100704. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100705. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100706. });
  100707. }
  100708. return UtilityLayerRenderer._DefaultUtilityLayer;
  100709. },
  100710. enumerable: true,
  100711. configurable: true
  100712. });
  100713. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  100714. /**
  100715. * 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)
  100716. */
  100717. get: function () {
  100718. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  100719. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100720. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  100721. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100722. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100723. });
  100724. }
  100725. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  100726. },
  100727. enumerable: true,
  100728. configurable: true
  100729. });
  100730. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  100731. if (!prePointerInfo.skipOnPointerObservable) {
  100732. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  100733. this._lastPointerEvents[pointerEvent.pointerId] = true;
  100734. }
  100735. };
  100736. /**
  100737. * Renders the utility layers scene on top of the original scene
  100738. */
  100739. UtilityLayerRenderer.prototype.render = function () {
  100740. this._updateCamera();
  100741. if (this.utilityLayerScene.activeCamera) {
  100742. // Set the camera's scene to utility layers scene
  100743. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  100744. var camera = this.utilityLayerScene.activeCamera;
  100745. camera._scene = this.utilityLayerScene;
  100746. if (camera.leftCamera) {
  100747. camera.leftCamera._scene = this.utilityLayerScene;
  100748. }
  100749. if (camera.rightCamera) {
  100750. camera.rightCamera._scene = this.utilityLayerScene;
  100751. }
  100752. this.utilityLayerScene.render(false);
  100753. // Reset camera's scene back to original
  100754. camera._scene = oldScene;
  100755. if (camera.leftCamera) {
  100756. camera.leftCamera._scene = oldScene;
  100757. }
  100758. if (camera.rightCamera) {
  100759. camera.rightCamera._scene = oldScene;
  100760. }
  100761. }
  100762. };
  100763. /**
  100764. * Disposes of the renderer
  100765. */
  100766. UtilityLayerRenderer.prototype.dispose = function () {
  100767. this.onPointerOutObservable.clear();
  100768. if (this._afterRenderObserver) {
  100769. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  100770. }
  100771. if (this._sceneDisposeObserver) {
  100772. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100773. }
  100774. if (this._originalPointerObserver) {
  100775. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  100776. }
  100777. this.utilityLayerScene.dispose();
  100778. };
  100779. UtilityLayerRenderer.prototype._updateCamera = function () {
  100780. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  100781. };
  100782. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100783. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100784. return UtilityLayerRenderer;
  100785. }());
  100786. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  100787. })(BABYLON || (BABYLON = {}));
  100788. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  100789. //# sourceMappingURL=babylon.behavior.js.map
  100790. var BABYLON;
  100791. (function (BABYLON) {
  100792. /**
  100793. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  100794. */
  100795. var PointerDragBehavior = /** @class */ (function () {
  100796. /**
  100797. * Creates a pointer drag behavior that can be attached to a mesh
  100798. * @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)
  100799. */
  100800. function PointerDragBehavior(options) {
  100801. /**
  100802. * 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)
  100803. */
  100804. this.maxDragAngle = 0;
  100805. /**
  100806. * @hidden
  100807. */
  100808. this._useAlternatePickedPointAboveMaxDragAngle = false;
  100809. /**
  100810. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  100811. */
  100812. this.currentDraggingPointerID = -1;
  100813. /**
  100814. * If the behavior is currently in a dragging state
  100815. */
  100816. this.dragging = false;
  100817. /**
  100818. * 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)
  100819. */
  100820. this.dragDeltaRatio = 0.2;
  100821. /**
  100822. * If the drag plane orientation should be updated during the dragging (Default: true)
  100823. */
  100824. this.updateDragPlane = true;
  100825. // Debug mode will display drag planes to help visualize behavior
  100826. this._debugMode = false;
  100827. this._moving = false;
  100828. /**
  100829. * Fires each time the attached mesh is dragged with the pointer
  100830. * * delta between last drag position and current drag position in world space
  100831. * * dragDistance along the drag axis
  100832. * * dragPlaneNormal normal of the current drag plane used during the drag
  100833. * * dragPlanePoint in world space where the drag intersects the drag plane
  100834. */
  100835. this.onDragObservable = new BABYLON.Observable();
  100836. /**
  100837. * Fires each time a drag begins (eg. mouse down on mesh)
  100838. */
  100839. this.onDragStartObservable = new BABYLON.Observable();
  100840. /**
  100841. * Fires each time a drag ends (eg. mouse release after drag)
  100842. */
  100843. this.onDragEndObservable = new BABYLON.Observable();
  100844. /**
  100845. * If the attached mesh should be moved when dragged
  100846. */
  100847. this.moveAttached = true;
  100848. /**
  100849. * If the drag behavior will react to drag events (Default: true)
  100850. */
  100851. this.enabled = true;
  100852. /**
  100853. * If camera controls should be detached during the drag
  100854. */
  100855. this.detachCameraControls = true;
  100856. /**
  100857. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  100858. */
  100859. this.useObjectOrienationForDragging = true;
  100860. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  100861. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  100862. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  100863. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  100864. this._attachedElement = null;
  100865. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100866. this._lastPointerRay = {};
  100867. this._dragDelta = new BABYLON.Vector3();
  100868. // Variables to avoid instantiation in the below method
  100869. this._pointA = new BABYLON.Vector3(0, 0, 0);
  100870. this._pointB = new BABYLON.Vector3(0, 0, 0);
  100871. this._pointC = new BABYLON.Vector3(0, 0, 0);
  100872. this._lineA = new BABYLON.Vector3(0, 0, 0);
  100873. this._lineB = new BABYLON.Vector3(0, 0, 0);
  100874. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  100875. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  100876. this._options = options ? options : {};
  100877. var optionCount = 0;
  100878. if (this._options.dragAxis) {
  100879. optionCount++;
  100880. }
  100881. if (this._options.dragPlaneNormal) {
  100882. optionCount++;
  100883. }
  100884. if (optionCount > 1) {
  100885. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  100886. }
  100887. }
  100888. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  100889. /**
  100890. * The name of the behavior
  100891. */
  100892. get: function () {
  100893. return "PointerDrag";
  100894. },
  100895. enumerable: true,
  100896. configurable: true
  100897. });
  100898. /**
  100899. * Initializes the behavior
  100900. */
  100901. PointerDragBehavior.prototype.init = function () { };
  100902. /**
  100903. * Attaches the drag behavior the passed in mesh
  100904. * @param ownerNode The mesh that will be dragged around once attached
  100905. */
  100906. PointerDragBehavior.prototype.attach = function (ownerNode) {
  100907. var _this = this;
  100908. this._scene = ownerNode.getScene();
  100909. this._attachedNode = ownerNode;
  100910. // Initialize drag plane to not interfere with existing scene
  100911. if (!PointerDragBehavior._planeScene) {
  100912. if (this._debugMode) {
  100913. PointerDragBehavior._planeScene = this._scene;
  100914. }
  100915. else {
  100916. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  100917. PointerDragBehavior._planeScene.detachControl();
  100918. this._scene.getEngine().scenes.pop();
  100919. this._scene.onDisposeObservable.addOnce(function () {
  100920. PointerDragBehavior._planeScene.dispose();
  100921. PointerDragBehavior._planeScene = null;
  100922. });
  100923. }
  100924. }
  100925. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  100926. // State of the drag
  100927. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  100928. var pickPredicate = function (m) {
  100929. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  100930. };
  100931. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100932. if (!_this.enabled) {
  100933. return;
  100934. }
  100935. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100936. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100937. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  100938. }
  100939. }
  100940. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100941. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100942. _this.releaseDrag();
  100943. }
  100944. }
  100945. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100946. var pointerId = pointerInfo.event.pointerId;
  100947. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  100948. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  100949. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  100950. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  100951. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  100952. }
  100953. _this.currentDraggingPointerID = pointerId;
  100954. }
  100955. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  100956. if (!_this._lastPointerRay[pointerId]) {
  100957. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100958. }
  100959. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  100960. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  100961. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  100962. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  100963. _this._moveDrag(pointerInfo.pickInfo.ray);
  100964. }
  100965. }
  100966. }
  100967. });
  100968. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100969. if (_this._moving && _this.moveAttached) {
  100970. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  100971. // Slowly move mesh to avoid jitter
  100972. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  100973. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  100974. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  100975. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  100976. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  100977. }
  100978. });
  100979. };
  100980. /**
  100981. * Force relase the drag action by code.
  100982. */
  100983. PointerDragBehavior.prototype.releaseDrag = function () {
  100984. this.dragging = false;
  100985. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  100986. this.currentDraggingPointerID = -1;
  100987. this._moving = false;
  100988. // Reattach camera controls
  100989. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  100990. this._scene.activeCamera.attachControl(this._attachedElement, true);
  100991. }
  100992. };
  100993. /**
  100994. * Simulates the start of a pointer drag event on the behavior
  100995. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  100996. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  100997. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  100998. */
  100999. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  101000. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  101001. this._startDrag(pointerId, fromRay, startPickedPoint);
  101002. var lastRay = this._lastPointerRay[pointerId];
  101003. if (pointerId === PointerDragBehavior._AnyMouseID) {
  101004. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  101005. }
  101006. if (lastRay) {
  101007. // if there was a last pointer ray drag the object there
  101008. this._moveDrag(lastRay);
  101009. }
  101010. };
  101011. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  101012. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  101013. return;
  101014. }
  101015. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  101016. // Create start ray from the camera to the object
  101017. if (fromRay) {
  101018. this._startDragRay.direction.copyFrom(fromRay.direction);
  101019. this._startDragRay.origin.copyFrom(fromRay.origin);
  101020. }
  101021. else {
  101022. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  101023. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  101024. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  101025. }
  101026. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  101027. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  101028. if (pickedPoint) {
  101029. this.dragging = true;
  101030. this.currentDraggingPointerID = pointerId;
  101031. this.lastDragPosition.copyFrom(pickedPoint);
  101032. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  101033. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  101034. // Detatch camera controls
  101035. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  101036. if (this._scene.activeCamera.inputs.attachedElement) {
  101037. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  101038. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  101039. }
  101040. else {
  101041. this._attachedElement = null;
  101042. }
  101043. }
  101044. }
  101045. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  101046. };
  101047. PointerDragBehavior.prototype._moveDrag = function (ray) {
  101048. this._moving = true;
  101049. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  101050. if (pickedPoint) {
  101051. if (this.updateDragPlane) {
  101052. this._updateDragPlanePosition(ray, pickedPoint);
  101053. }
  101054. var dragLength = 0;
  101055. // depending on the drag mode option drag accordingly
  101056. if (this._options.dragAxis) {
  101057. // Convert local drag axis to world
  101058. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  101059. // Project delta drag from the drag plane onto the drag axis
  101060. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  101061. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  101062. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  101063. }
  101064. else {
  101065. dragLength = this._dragDelta.length();
  101066. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  101067. }
  101068. this._targetPosition.addInPlace(this._dragDelta);
  101069. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  101070. this.lastDragPosition.copyFrom(pickedPoint);
  101071. }
  101072. };
  101073. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  101074. var _this = this;
  101075. if (!ray) {
  101076. return null;
  101077. }
  101078. // Calculate angle between plane normal and ray
  101079. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  101080. // Correct if ray is casted from oposite side
  101081. if (angle > Math.PI / 2) {
  101082. angle = Math.PI - angle;
  101083. }
  101084. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  101085. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  101086. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  101087. // Invert ray direction along the towards object axis
  101088. this._tmpVector.copyFrom(ray.direction);
  101089. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  101090. this._alternatePickedPoint.normalize();
  101091. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  101092. this._tmpVector.addInPlace(this._alternatePickedPoint);
  101093. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  101094. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  101095. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  101096. this._alternatePickedPoint.addInPlace(this._tmpVector);
  101097. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  101098. return this._alternatePickedPoint;
  101099. }
  101100. else {
  101101. return null;
  101102. }
  101103. }
  101104. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  101105. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  101106. return pickResult.pickedPoint;
  101107. }
  101108. else {
  101109. return null;
  101110. }
  101111. };
  101112. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  101113. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  101114. this._pointA.copyFrom(dragPlanePosition);
  101115. if (this._options.dragAxis) {
  101116. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  101117. // Calculate plane normal in direction of camera but perpendicular to drag axis
  101118. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  101119. ray.origin.subtractToRef(this._pointA, this._pointC);
  101120. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  101121. // Get perpendicular line from direction to camera and drag axis
  101122. this._pointB.subtractToRef(this._pointA, this._lineA);
  101123. this._pointC.subtractToRef(this._pointA, this._lineB);
  101124. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  101125. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  101126. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  101127. this._lookAt.normalize();
  101128. this._dragPlane.position.copyFrom(this._pointA);
  101129. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  101130. this._dragPlane.lookAt(this._lookAt);
  101131. }
  101132. else if (this._options.dragPlaneNormal) {
  101133. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  101134. this._dragPlane.position.copyFrom(this._pointA);
  101135. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  101136. this._dragPlane.lookAt(this._lookAt);
  101137. }
  101138. else {
  101139. this._dragPlane.position.copyFrom(this._pointA);
  101140. this._dragPlane.lookAt(ray.origin);
  101141. }
  101142. this._dragPlane.computeWorldMatrix(true);
  101143. };
  101144. /**
  101145. * Detaches the behavior from the mesh
  101146. */
  101147. PointerDragBehavior.prototype.detach = function () {
  101148. if (this._pointerObserver) {
  101149. this._scene.onPointerObservable.remove(this._pointerObserver);
  101150. }
  101151. if (this._beforeRenderObserver) {
  101152. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101153. }
  101154. };
  101155. PointerDragBehavior._AnyMouseID = -2;
  101156. return PointerDragBehavior;
  101157. }());
  101158. BABYLON.PointerDragBehavior = PointerDragBehavior;
  101159. })(BABYLON || (BABYLON = {}));
  101160. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  101161. var BABYLON;
  101162. (function (BABYLON) {
  101163. /**
  101164. * A behavior that when attached to a mesh will allow the mesh to be scaled
  101165. */
  101166. var MultiPointerScaleBehavior = /** @class */ (function () {
  101167. /**
  101168. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  101169. */
  101170. function MultiPointerScaleBehavior() {
  101171. this._startDistance = 0;
  101172. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  101173. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  101174. this._sceneRenderObserver = null;
  101175. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  101176. this._dragBehaviorA.moveAttached = false;
  101177. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  101178. this._dragBehaviorB.moveAttached = false;
  101179. }
  101180. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  101181. /**
  101182. * The name of the behavior
  101183. */
  101184. get: function () {
  101185. return "MultiPointerScale";
  101186. },
  101187. enumerable: true,
  101188. configurable: true
  101189. });
  101190. /**
  101191. * Initializes the behavior
  101192. */
  101193. MultiPointerScaleBehavior.prototype.init = function () { };
  101194. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  101195. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  101196. };
  101197. /**
  101198. * Attaches the scale behavior the passed in mesh
  101199. * @param ownerNode The mesh that will be scaled around once attached
  101200. */
  101201. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  101202. var _this = this;
  101203. this._ownerNode = ownerNode;
  101204. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  101205. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  101206. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101207. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101208. _this._dragBehaviorA.releaseDrag();
  101209. }
  101210. else {
  101211. _this._initialScale.copyFrom(ownerNode.scaling);
  101212. _this._startDistance = _this._getCurrentDistance();
  101213. }
  101214. }
  101215. });
  101216. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  101217. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101218. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101219. _this._dragBehaviorB.releaseDrag();
  101220. }
  101221. else {
  101222. _this._initialScale.copyFrom(ownerNode.scaling);
  101223. _this._startDistance = _this._getCurrentDistance();
  101224. }
  101225. }
  101226. });
  101227. // Once both drag behaviors are active scale based on the distance between the two pointers
  101228. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101229. behavior.onDragObservable.add(function () {
  101230. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101231. var ratio = _this._getCurrentDistance() / _this._startDistance;
  101232. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  101233. }
  101234. });
  101235. });
  101236. ownerNode.addBehavior(this._dragBehaviorA);
  101237. ownerNode.addBehavior(this._dragBehaviorB);
  101238. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101239. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101240. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101241. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  101242. if (change.length() > 0.01) {
  101243. ownerNode.scaling.addInPlace(change);
  101244. }
  101245. }
  101246. });
  101247. };
  101248. /**
  101249. * Detaches the behavior from the mesh
  101250. */
  101251. MultiPointerScaleBehavior.prototype.detach = function () {
  101252. var _this = this;
  101253. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101254. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101255. behavior.onDragStartObservable.clear();
  101256. behavior.onDragObservable.clear();
  101257. _this._ownerNode.removeBehavior(behavior);
  101258. });
  101259. };
  101260. return MultiPointerScaleBehavior;
  101261. }());
  101262. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  101263. })(BABYLON || (BABYLON = {}));
  101264. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  101265. var BABYLON;
  101266. (function (BABYLON) {
  101267. /**
  101268. * 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
  101269. */
  101270. var SixDofDragBehavior = /** @class */ (function () {
  101271. /**
  101272. * Instantiates 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
  101273. */
  101274. function SixDofDragBehavior() {
  101275. this._sceneRenderObserver = null;
  101276. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  101277. this._moving = false;
  101278. this._startingOrientation = new BABYLON.Quaternion();
  101279. /**
  101280. * 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)
  101281. */
  101282. this.zDragFactor = 3;
  101283. /**
  101284. * If the behavior is currently in a dragging state
  101285. */
  101286. this.dragging = false;
  101287. /**
  101288. * 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)
  101289. */
  101290. this.dragDeltaRatio = 0.2;
  101291. /**
  101292. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  101293. */
  101294. this.currentDraggingPointerID = -1;
  101295. /**
  101296. * If camera controls should be detached during the drag
  101297. */
  101298. this.detachCameraControls = true;
  101299. /**
  101300. * Fires each time a drag starts
  101301. */
  101302. this.onDragStartObservable = new BABYLON.Observable();
  101303. /**
  101304. * Fires each time a drag ends (eg. mouse release after drag)
  101305. */
  101306. this.onDragEndObservable = new BABYLON.Observable();
  101307. }
  101308. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  101309. /**
  101310. * The name of the behavior
  101311. */
  101312. get: function () {
  101313. return "SixDofDrag";
  101314. },
  101315. enumerable: true,
  101316. configurable: true
  101317. });
  101318. /**
  101319. * Initializes the behavior
  101320. */
  101321. SixDofDragBehavior.prototype.init = function () { };
  101322. /**
  101323. * Attaches the scale behavior the passed in mesh
  101324. * @param ownerNode The mesh that will be scaled around once attached
  101325. */
  101326. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  101327. var _this = this;
  101328. this._ownerNode = ownerNode;
  101329. this._scene = this._ownerNode.getScene();
  101330. if (!SixDofDragBehavior._virtualScene) {
  101331. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  101332. SixDofDragBehavior._virtualScene.detachControl();
  101333. this._scene.getEngine().scenes.pop();
  101334. }
  101335. var pickedMesh = null;
  101336. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  101337. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  101338. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101339. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  101340. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101341. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  101342. var pickPredicate = function (m) {
  101343. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  101344. };
  101345. var attachedElement = null;
  101346. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101347. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101348. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101349. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101350. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101351. }
  101352. pickedMesh = _this._ownerNode;
  101353. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101354. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101355. // Set position and orientation of the controller
  101356. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101357. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101358. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  101359. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101360. pickedMesh.computeWorldMatrix();
  101361. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  101362. if (!pickedMesh.rotationQuaternion) {
  101363. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  101364. }
  101365. var oldParent = pickedMesh.parent;
  101366. pickedMesh.setParent(null);
  101367. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  101368. pickedMesh.setParent(oldParent);
  101369. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101370. // Update state
  101371. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101372. _this.dragging = true;
  101373. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  101374. // Detatch camera controls
  101375. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101376. if (_this._scene.activeCamera.inputs.attachedElement) {
  101377. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  101378. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  101379. }
  101380. else {
  101381. attachedElement = null;
  101382. }
  101383. }
  101384. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101385. _this.onDragStartObservable.notifyObservers({});
  101386. }
  101387. }
  101388. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101389. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101390. _this.dragging = false;
  101391. _this._moving = false;
  101392. _this.currentDraggingPointerID = -1;
  101393. pickedMesh = null;
  101394. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101395. // Reattach camera controls
  101396. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101397. _this._scene.activeCamera.attachControl(attachedElement, true);
  101398. }
  101399. _this.onDragEndObservable.notifyObservers({});
  101400. }
  101401. }
  101402. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101403. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  101404. var zDragFactor = _this.zDragFactor;
  101405. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101406. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101407. zDragFactor = 0;
  101408. }
  101409. // Calculate controller drag distance in controller space
  101410. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  101411. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101412. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  101413. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101414. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  101415. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  101416. if (_this._virtualDragMesh.position.z < 0) {
  101417. _this._virtualDragMesh.position.z = 0;
  101418. }
  101419. // Update the controller position
  101420. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101421. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101422. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101423. // Move the virtualObjectsPosition into the picked mesh's space if needed
  101424. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101425. if (pickedMesh.parent) {
  101426. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  101427. }
  101428. if (!_this._moving) {
  101429. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  101430. }
  101431. _this._moving = true;
  101432. }
  101433. }
  101434. });
  101435. var tmpQuaternion = new BABYLON.Quaternion();
  101436. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101437. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101438. if (_this.dragging && _this._moving && pickedMesh) {
  101439. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101440. // Slowly move mesh to avoid jitter
  101441. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  101442. // Get change in rotation
  101443. tmpQuaternion.copyFrom(_this._startingOrientation);
  101444. tmpQuaternion.x = -tmpQuaternion.x;
  101445. tmpQuaternion.y = -tmpQuaternion.y;
  101446. tmpQuaternion.z = -tmpQuaternion.z;
  101447. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  101448. // Convert change in rotation to only y axis rotation
  101449. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  101450. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  101451. // Slowly move mesh to avoid jitter
  101452. var oldParent = pickedMesh.parent;
  101453. pickedMesh.setParent(null);
  101454. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  101455. pickedMesh.setParent(oldParent);
  101456. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101457. }
  101458. });
  101459. };
  101460. /**
  101461. * Detaches the behavior from the mesh
  101462. */
  101463. SixDofDragBehavior.prototype.detach = function () {
  101464. if (this._scene) {
  101465. this._scene.onPointerObservable.remove(this._pointerObserver);
  101466. }
  101467. if (this._ownerNode) {
  101468. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101469. }
  101470. if (this._virtualOriginMesh) {
  101471. this._virtualOriginMesh.dispose();
  101472. }
  101473. if (this._virtualDragMesh) {
  101474. this._virtualDragMesh.dispose();
  101475. }
  101476. this.onDragEndObservable.clear();
  101477. this.onDragStartObservable.clear();
  101478. };
  101479. return SixDofDragBehavior;
  101480. }());
  101481. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  101482. })(BABYLON || (BABYLON = {}));
  101483. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  101484. var BABYLON;
  101485. (function (BABYLON) {
  101486. /**
  101487. * @hidden
  101488. */
  101489. var FaceDirectionInfo = /** @class */ (function () {
  101490. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  101491. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  101492. if (diff === void 0) { diff = 0; }
  101493. if (ignore === void 0) { ignore = false; }
  101494. this.direction = direction;
  101495. this.rotatedDirection = rotatedDirection;
  101496. this.diff = diff;
  101497. this.ignore = ignore;
  101498. }
  101499. return FaceDirectionInfo;
  101500. }());
  101501. /**
  101502. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  101503. */
  101504. var AttachToBoxBehavior = /** @class */ (function () {
  101505. /**
  101506. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  101507. * @param ui The transform node that should be attched to the mesh
  101508. */
  101509. function AttachToBoxBehavior(ui) {
  101510. this.ui = ui;
  101511. /**
  101512. * The name of the behavior
  101513. */
  101514. this.name = "AttachToBoxBehavior";
  101515. /**
  101516. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  101517. */
  101518. this.distanceAwayFromFace = 0.15;
  101519. /**
  101520. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  101521. */
  101522. this.distanceAwayFromBottomOfFace = 0.15;
  101523. 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))];
  101524. this._tmpMatrix = new BABYLON.Matrix();
  101525. this._tmpVector = new BABYLON.Vector3();
  101526. this._zeroVector = BABYLON.Vector3.Zero();
  101527. this._lookAtTmpMatrix = new BABYLON.Matrix();
  101528. /* Does nothing */
  101529. }
  101530. /**
  101531. * Initializes the behavior
  101532. */
  101533. AttachToBoxBehavior.prototype.init = function () {
  101534. /* Does nothing */
  101535. };
  101536. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  101537. var _this = this;
  101538. // Go over each face and calculate the angle between the face's normal and targetDirection
  101539. this._faceVectors.forEach(function (v) {
  101540. if (!_this._target.rotationQuaternion) {
  101541. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  101542. }
  101543. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  101544. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  101545. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  101546. });
  101547. // Return the face information of the one with the normal closeset to target direction
  101548. return this._faceVectors.reduce(function (min, p) {
  101549. if (min.ignore) {
  101550. return p;
  101551. }
  101552. else if (p.ignore) {
  101553. return min;
  101554. }
  101555. else {
  101556. return min.diff < p.diff ? min : p;
  101557. }
  101558. }, this._faceVectors[0]);
  101559. };
  101560. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  101561. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  101562. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  101563. this._lookAtTmpMatrix.invert();
  101564. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  101565. };
  101566. /**
  101567. * Attaches the AttachToBoxBehavior to the passed in mesh
  101568. * @param target The mesh that the specified node will be attached to
  101569. */
  101570. AttachToBoxBehavior.prototype.attach = function (target) {
  101571. var _this = this;
  101572. this._target = target;
  101573. this._scene = this._target.getScene();
  101574. // Every frame, update the app bars position
  101575. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  101576. if (!_this._scene.activeCamera) {
  101577. return;
  101578. }
  101579. // Find the face closest to the cameras position
  101580. var cameraPos = _this._scene.activeCamera.position;
  101581. if (_this._scene.activeCamera.devicePosition) {
  101582. cameraPos = _this._scene.activeCamera.devicePosition;
  101583. }
  101584. var facing = _this._closestFace(cameraPos.subtract(target.position));
  101585. if (_this._scene.activeCamera.leftCamera) {
  101586. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101587. }
  101588. else {
  101589. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101590. }
  101591. // Get camera up direction
  101592. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  101593. // Ignore faces to not select a parrelel face for the up vector of the UI
  101594. _this._faceVectors.forEach(function (v) {
  101595. if (facing.direction.x && v.direction.x) {
  101596. v.ignore = true;
  101597. }
  101598. if (facing.direction.y && v.direction.y) {
  101599. v.ignore = true;
  101600. }
  101601. if (facing.direction.z && v.direction.z) {
  101602. v.ignore = true;
  101603. }
  101604. });
  101605. var facingUp = _this._closestFace(_this._tmpVector);
  101606. // Unignore faces
  101607. _this._faceVectors.forEach(function (v) {
  101608. v.ignore = false;
  101609. });
  101610. // Position the app bar on that face
  101611. _this.ui.position.copyFrom(target.position);
  101612. if (facing.direction.x) {
  101613. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101614. _this.ui.position.addInPlace(_this._tmpVector);
  101615. }
  101616. if (facing.direction.y) {
  101617. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101618. _this.ui.position.addInPlace(_this._tmpVector);
  101619. }
  101620. if (facing.direction.z) {
  101621. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101622. _this.ui.position.addInPlace(_this._tmpVector);
  101623. }
  101624. // Rotate to be oriented properly to the camera
  101625. if (!_this.ui.rotationQuaternion) {
  101626. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  101627. }
  101628. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  101629. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  101630. // Place ui the correct distance from the bottom of the mesh
  101631. if (facingUp.direction.x) {
  101632. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  101633. }
  101634. if (facingUp.direction.y) {
  101635. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  101636. }
  101637. if (facingUp.direction.z) {
  101638. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  101639. }
  101640. _this.ui.position.addInPlace(_this._tmpVector);
  101641. });
  101642. };
  101643. /**
  101644. * Detaches the behavior from the mesh
  101645. */
  101646. AttachToBoxBehavior.prototype.detach = function () {
  101647. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  101648. };
  101649. return AttachToBoxBehavior;
  101650. }());
  101651. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  101652. })(BABYLON || (BABYLON = {}));
  101653. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  101654. var BABYLON;
  101655. (function (BABYLON) {
  101656. /**
  101657. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  101658. */
  101659. var FadeInOutBehavior = /** @class */ (function () {
  101660. /**
  101661. * Instatiates the FadeInOutBehavior
  101662. */
  101663. function FadeInOutBehavior() {
  101664. var _this = this;
  101665. /**
  101666. * Time in milliseconds to delay before fading in (Default: 0)
  101667. */
  101668. this.delay = 0;
  101669. /**
  101670. * Time in milliseconds for the mesh to fade in (Default: 300)
  101671. */
  101672. this.fadeInTime = 300;
  101673. this._millisecondsPerFrame = 1000 / 60;
  101674. this._hovered = false;
  101675. this._hoverValue = 0;
  101676. this._ownerNode = null;
  101677. this._update = function () {
  101678. if (_this._ownerNode) {
  101679. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  101680. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  101681. if (_this._ownerNode.visibility > 1) {
  101682. _this._setAllVisibility(_this._ownerNode, 1);
  101683. _this._hoverValue = _this.fadeInTime + _this.delay;
  101684. return;
  101685. }
  101686. else if (_this._ownerNode.visibility < 0) {
  101687. _this._setAllVisibility(_this._ownerNode, 0);
  101688. if (_this._hoverValue < 0) {
  101689. _this._hoverValue = 0;
  101690. return;
  101691. }
  101692. }
  101693. setTimeout(_this._update, _this._millisecondsPerFrame);
  101694. }
  101695. };
  101696. }
  101697. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  101698. /**
  101699. * The name of the behavior
  101700. */
  101701. get: function () {
  101702. return "FadeInOut";
  101703. },
  101704. enumerable: true,
  101705. configurable: true
  101706. });
  101707. /**
  101708. * Initializes the behavior
  101709. */
  101710. FadeInOutBehavior.prototype.init = function () {
  101711. };
  101712. /**
  101713. * Attaches the fade behavior on the passed in mesh
  101714. * @param ownerNode The mesh that will be faded in/out once attached
  101715. */
  101716. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  101717. this._ownerNode = ownerNode;
  101718. this._setAllVisibility(this._ownerNode, 0);
  101719. };
  101720. /**
  101721. * Detaches the behavior from the mesh
  101722. */
  101723. FadeInOutBehavior.prototype.detach = function () {
  101724. this._ownerNode = null;
  101725. };
  101726. /**
  101727. * Triggers the mesh to begin fading in or out
  101728. * @param value if the object should fade in or out (true to fade in)
  101729. */
  101730. FadeInOutBehavior.prototype.fadeIn = function (value) {
  101731. this._hovered = value;
  101732. this._update();
  101733. };
  101734. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  101735. var _this = this;
  101736. mesh.visibility = value;
  101737. mesh.getChildMeshes().forEach(function (c) {
  101738. _this._setAllVisibility(c, value);
  101739. });
  101740. };
  101741. return FadeInOutBehavior;
  101742. }());
  101743. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  101744. })(BABYLON || (BABYLON = {}));
  101745. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  101746. var BABYLON;
  101747. (function (BABYLON) {
  101748. /**
  101749. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  101750. */
  101751. var Gizmo = /** @class */ (function () {
  101752. /**
  101753. * Creates a gizmo
  101754. * @param gizmoLayer The utility layer the gizmo will be added to
  101755. */
  101756. function Gizmo(
  101757. /** The utility layer the gizmo will be added to */
  101758. gizmoLayer) {
  101759. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101760. var _this = this;
  101761. this.gizmoLayer = gizmoLayer;
  101762. /**
  101763. * Ratio for the scale of the gizmo (Default: 1)
  101764. */
  101765. this.scaleRatio = 1;
  101766. this._tmpMatrix = new BABYLON.Matrix();
  101767. /**
  101768. * If a custom mesh has been set (Default: false)
  101769. */
  101770. this._customMeshSet = false;
  101771. /**
  101772. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  101773. */
  101774. this.updateGizmoRotationToMatchAttachedMesh = true;
  101775. /**
  101776. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  101777. */
  101778. this.updateGizmoPositionToMatchAttachedMesh = true;
  101779. /**
  101780. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  101781. */
  101782. this._updateScale = true;
  101783. this._interactionsEnabled = true;
  101784. this._tempVector = new BABYLON.Vector3();
  101785. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  101786. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  101787. _this._update();
  101788. });
  101789. this.attachedMesh = null;
  101790. }
  101791. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  101792. /**
  101793. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  101794. * * When set, interactions will be enabled
  101795. */
  101796. get: function () {
  101797. return this._attachedMesh;
  101798. },
  101799. set: function (value) {
  101800. this._attachedMesh = value;
  101801. this._rootMesh.setEnabled(value ? true : false);
  101802. this._attachedMeshChanged(value);
  101803. },
  101804. enumerable: true,
  101805. configurable: true
  101806. });
  101807. /**
  101808. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  101809. * @param mesh The mesh to replace the default mesh of the gizmo
  101810. */
  101811. Gizmo.prototype.setCustomMesh = function (mesh) {
  101812. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  101813. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  101814. }
  101815. this._rootMesh.getChildMeshes().forEach(function (c) {
  101816. c.dispose();
  101817. });
  101818. mesh.parent = this._rootMesh;
  101819. this._customMeshSet = true;
  101820. };
  101821. Gizmo.prototype._attachedMeshChanged = function (value) {
  101822. };
  101823. /**
  101824. * @hidden
  101825. * Updates the gizmo to match the attached mesh's position/rotation
  101826. */
  101827. Gizmo.prototype._update = function () {
  101828. if (this.attachedMesh) {
  101829. if (this.updateGizmoRotationToMatchAttachedMesh) {
  101830. if (!this._rootMesh.rotationQuaternion) {
  101831. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  101832. }
  101833. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  101834. this._tempVector.copyFrom(this.attachedMesh.scaling);
  101835. if (this.attachedMesh.scaling.x < 0) {
  101836. this.attachedMesh.scaling.x *= -1;
  101837. }
  101838. if (this.attachedMesh.scaling.y < 0) {
  101839. this.attachedMesh.scaling.y *= -1;
  101840. }
  101841. if (this.attachedMesh.scaling.z < 0) {
  101842. this.attachedMesh.scaling.z *= -1;
  101843. }
  101844. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  101845. this.attachedMesh.scaling.copyFrom(this._tempVector);
  101846. this.attachedMesh.computeWorldMatrix();
  101847. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  101848. }
  101849. else if (this._rootMesh.rotationQuaternion) {
  101850. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  101851. }
  101852. if (this.updateGizmoPositionToMatchAttachedMesh) {
  101853. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  101854. }
  101855. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  101856. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  101857. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  101858. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  101859. }
  101860. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  101861. var dist = this._tempVector.length() * this.scaleRatio;
  101862. this._rootMesh.scaling.set(dist, dist, dist);
  101863. }
  101864. }
  101865. };
  101866. /**
  101867. * Disposes of the gizmo
  101868. */
  101869. Gizmo.prototype.dispose = function () {
  101870. this._rootMesh.dispose();
  101871. if (this._beforeRenderObserver) {
  101872. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101873. }
  101874. };
  101875. return Gizmo;
  101876. }());
  101877. BABYLON.Gizmo = Gizmo;
  101878. })(BABYLON || (BABYLON = {}));
  101879. //# sourceMappingURL=babylon.gizmo.js.map
  101880. var BABYLON;
  101881. (function (BABYLON) {
  101882. /**
  101883. * Single axis drag gizmo
  101884. */
  101885. var AxisDragGizmo = /** @class */ (function (_super) {
  101886. __extends(AxisDragGizmo, _super);
  101887. /**
  101888. * Creates an AxisDragGizmo
  101889. * @param gizmoLayer The utility layer the gizmo will be added to
  101890. * @param dragAxis The axis which the gizmo will be able to drag on
  101891. * @param color The color of the gizmo
  101892. */
  101893. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  101894. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101895. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101896. var _this = _super.call(this, gizmoLayer) || this;
  101897. _this._pointerObserver = null;
  101898. /**
  101899. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101900. */
  101901. _this.snapDistance = 0;
  101902. /**
  101903. * Event that fires each time the gizmo snaps to a new location.
  101904. * * snapDistance is the the change in distance
  101905. */
  101906. _this.onSnapObservable = new BABYLON.Observable();
  101907. // Create Material
  101908. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101909. coloredMaterial.disableLighting = true;
  101910. coloredMaterial.emissiveColor = color;
  101911. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101912. hoverMaterial.disableLighting = true;
  101913. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101914. // Build mesh on root node
  101915. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101916. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  101917. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  101918. arrowTail.color = coloredMaterial.emissiveColor;
  101919. arrow.addChild(arrowMesh);
  101920. arrow.addChild(arrowTail);
  101921. // Position arrow pointing in its drag axis
  101922. arrowMesh.scaling.scaleInPlace(0.05);
  101923. arrowMesh.material = coloredMaterial;
  101924. arrowMesh.rotation.x = Math.PI / 2;
  101925. arrowMesh.position.z += 0.3;
  101926. arrowTail.scaling.scaleInPlace(0.26);
  101927. arrowTail.rotation.x = Math.PI / 2;
  101928. arrowTail.material = coloredMaterial;
  101929. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  101930. arrow.scaling.scaleInPlace(1 / 3);
  101931. _this._rootMesh.addChild(arrow);
  101932. var currentSnapDragDistance = 0;
  101933. var tmpVector = new BABYLON.Vector3();
  101934. var tmpSnapEvent = { snapDistance: 0 };
  101935. // Add drag behavior to handle events when the gizmo is dragged
  101936. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101937. _this.dragBehavior.moveAttached = false;
  101938. _this._rootMesh.addBehavior(_this.dragBehavior);
  101939. var localDelta = new BABYLON.Vector3();
  101940. var tmpMatrix = new BABYLON.Matrix();
  101941. _this.dragBehavior.onDragObservable.add(function (event) {
  101942. if (_this.attachedMesh) {
  101943. // Convert delta to local translation if it has a parent
  101944. if (_this.attachedMesh.parent) {
  101945. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  101946. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  101947. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  101948. }
  101949. else {
  101950. localDelta.copyFrom(event.delta);
  101951. }
  101952. // Snapping logic
  101953. if (_this.snapDistance == 0) {
  101954. _this.attachedMesh.position.addInPlace(localDelta);
  101955. }
  101956. else {
  101957. currentSnapDragDistance += event.dragDistance;
  101958. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  101959. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  101960. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  101961. localDelta.normalizeToRef(tmpVector);
  101962. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  101963. _this.attachedMesh.position.addInPlace(tmpVector);
  101964. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  101965. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  101966. }
  101967. }
  101968. }
  101969. });
  101970. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101971. if (_this._customMeshSet) {
  101972. return;
  101973. }
  101974. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  101975. var material = isHovered ? hoverMaterial : coloredMaterial;
  101976. _this._rootMesh.getChildMeshes().forEach(function (m) {
  101977. m.material = material;
  101978. if (m.color) {
  101979. m.color = material.emissiveColor;
  101980. }
  101981. });
  101982. });
  101983. return _this;
  101984. }
  101985. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  101986. if (this.dragBehavior) {
  101987. this.dragBehavior.enabled = value ? true : false;
  101988. }
  101989. };
  101990. /**
  101991. * Disposes of the gizmo
  101992. */
  101993. AxisDragGizmo.prototype.dispose = function () {
  101994. this.onSnapObservable.clear();
  101995. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101996. this.dragBehavior.detach();
  101997. _super.prototype.dispose.call(this);
  101998. };
  101999. return AxisDragGizmo;
  102000. }(BABYLON.Gizmo));
  102001. BABYLON.AxisDragGizmo = AxisDragGizmo;
  102002. })(BABYLON || (BABYLON = {}));
  102003. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  102004. var BABYLON;
  102005. (function (BABYLON) {
  102006. /**
  102007. * Single axis scale gizmo
  102008. */
  102009. var AxisScaleGizmo = /** @class */ (function (_super) {
  102010. __extends(AxisScaleGizmo, _super);
  102011. /**
  102012. * Creates an AxisScaleGizmo
  102013. * @param gizmoLayer The utility layer the gizmo will be added to
  102014. * @param dragAxis The axis which the gizmo will be able to scale on
  102015. * @param color The color of the gizmo
  102016. */
  102017. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  102018. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102019. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102020. var _this = _super.call(this, gizmoLayer) || this;
  102021. _this._pointerObserver = null;
  102022. /**
  102023. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102024. */
  102025. _this.snapDistance = 0;
  102026. /**
  102027. * Event that fires each time the gizmo snaps to a new location.
  102028. * * snapDistance is the the change in distance
  102029. */
  102030. _this.onSnapObservable = new BABYLON.Observable();
  102031. /**
  102032. * If the scaling operation should be done on all axis (default: false)
  102033. */
  102034. _this.uniformScaling = false;
  102035. // Create Material
  102036. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102037. _this._coloredMaterial.disableLighting = true;
  102038. _this._coloredMaterial.emissiveColor = color;
  102039. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102040. hoverMaterial.disableLighting = true;
  102041. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102042. // Build mesh on root node
  102043. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102044. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  102045. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  102046. arrowTail.color = _this._coloredMaterial.emissiveColor;
  102047. arrow.addChild(arrowMesh);
  102048. arrow.addChild(arrowTail);
  102049. // Position arrow pointing in its drag axis
  102050. arrowMesh.scaling.scaleInPlace(0.1);
  102051. arrowMesh.material = _this._coloredMaterial;
  102052. arrowMesh.rotation.x = Math.PI / 2;
  102053. arrowMesh.position.z += 0.3;
  102054. arrowTail.scaling.scaleInPlace(0.26);
  102055. arrowTail.rotation.x = Math.PI / 2;
  102056. arrowTail.material = _this._coloredMaterial;
  102057. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  102058. _this._rootMesh.addChild(arrow);
  102059. arrow.scaling.scaleInPlace(1 / 3);
  102060. // Add drag behavior to handle events when the gizmo is dragged
  102061. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102062. _this.dragBehavior.moveAttached = false;
  102063. _this._rootMesh.addBehavior(_this.dragBehavior);
  102064. var currentSnapDragDistance = 0;
  102065. var tmpVector = new BABYLON.Vector3();
  102066. var tmpSnapEvent = { snapDistance: 0 };
  102067. _this.dragBehavior.onDragObservable.add(function (event) {
  102068. if (_this.attachedMesh) {
  102069. // Snapping logic
  102070. var snapped = false;
  102071. var dragSteps = 0;
  102072. if (_this.uniformScaling) {
  102073. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  102074. if (tmpVector.y < 0) {
  102075. tmpVector.scaleInPlace(-1);
  102076. }
  102077. }
  102078. else {
  102079. tmpVector.copyFrom(dragAxis);
  102080. }
  102081. if (_this.snapDistance == 0) {
  102082. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  102083. }
  102084. else {
  102085. currentSnapDragDistance += event.dragDistance;
  102086. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102087. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102088. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102089. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  102090. snapped = true;
  102091. }
  102092. else {
  102093. tmpVector.scaleInPlace(0);
  102094. }
  102095. }
  102096. _this.attachedMesh.scaling.addInPlace(tmpVector);
  102097. if (snapped) {
  102098. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102099. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102100. }
  102101. }
  102102. });
  102103. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102104. if (_this._customMeshSet) {
  102105. return;
  102106. }
  102107. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102108. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  102109. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102110. m.material = material;
  102111. if (m.color) {
  102112. m.color = material.emissiveColor;
  102113. }
  102114. });
  102115. });
  102116. return _this;
  102117. }
  102118. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  102119. if (this.dragBehavior) {
  102120. this.dragBehavior.enabled = value ? true : false;
  102121. }
  102122. };
  102123. /**
  102124. * Disposes of the gizmo
  102125. */
  102126. AxisScaleGizmo.prototype.dispose = function () {
  102127. this.onSnapObservable.clear();
  102128. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102129. this.dragBehavior.detach();
  102130. _super.prototype.dispose.call(this);
  102131. };
  102132. /**
  102133. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  102134. * @param mesh The mesh to replace the default mesh of the gizmo
  102135. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  102136. */
  102137. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  102138. var _this = this;
  102139. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  102140. _super.prototype.setCustomMesh.call(this, mesh);
  102141. if (useGizmoMaterial) {
  102142. this._rootMesh.getChildMeshes().forEach(function (m) {
  102143. m.material = _this._coloredMaterial;
  102144. if (m.color) {
  102145. m.color = _this._coloredMaterial.emissiveColor;
  102146. }
  102147. });
  102148. this._customMeshSet = false;
  102149. }
  102150. };
  102151. return AxisScaleGizmo;
  102152. }(BABYLON.Gizmo));
  102153. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  102154. })(BABYLON || (BABYLON = {}));
  102155. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  102156. var BABYLON;
  102157. (function (BABYLON) {
  102158. /**
  102159. * Single plane rotation gizmo
  102160. */
  102161. var PlaneRotationGizmo = /** @class */ (function (_super) {
  102162. __extends(PlaneRotationGizmo, _super);
  102163. /**
  102164. * Creates a PlaneRotationGizmo
  102165. * @param gizmoLayer The utility layer the gizmo will be added to
  102166. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  102167. * @param color The color of the gizmo
  102168. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102169. */
  102170. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  102171. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102172. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102173. if (tessellation === void 0) { tessellation = 32; }
  102174. var _this = _super.call(this, gizmoLayer) || this;
  102175. _this._pointerObserver = null;
  102176. /**
  102177. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  102178. */
  102179. _this.snapDistance = 0;
  102180. /**
  102181. * Event that fires each time the gizmo snaps to a new location.
  102182. * * snapDistance is the the change in distance
  102183. */
  102184. _this.onSnapObservable = new BABYLON.Observable();
  102185. // Create Material
  102186. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102187. coloredMaterial.disableLighting = true;
  102188. coloredMaterial.emissiveColor = color;
  102189. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102190. hoverMaterial.disableLighting = true;
  102191. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102192. // Build mesh on root node
  102193. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102194. // Create circle out of lines
  102195. var radius = 0.8;
  102196. var points = new Array();
  102197. for (var i = 0; i < tessellation; i++) {
  102198. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  102199. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  102200. }
  102201. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  102202. rotationMesh.color = coloredMaterial.emissiveColor;
  102203. // Position arrow pointing in its drag axis
  102204. rotationMesh.scaling.scaleInPlace(0.26);
  102205. rotationMesh.material = coloredMaterial;
  102206. rotationMesh.rotation.x = Math.PI / 2;
  102207. parentMesh.addChild(rotationMesh);
  102208. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  102209. _this._rootMesh.addChild(parentMesh);
  102210. parentMesh.scaling.scaleInPlace(1 / 3);
  102211. // Add drag behavior to handle events when the gizmo is dragged
  102212. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  102213. _this.dragBehavior.moveAttached = false;
  102214. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  102215. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  102216. _this._rootMesh.addBehavior(_this.dragBehavior);
  102217. var lastDragPosition = new BABYLON.Vector3();
  102218. _this.dragBehavior.onDragStartObservable.add(function (e) {
  102219. if (_this.attachedMesh) {
  102220. lastDragPosition.copyFrom(e.dragPlanePoint);
  102221. }
  102222. });
  102223. var rotationMatrix = new BABYLON.Matrix();
  102224. var planeNormalTowardsCamera = new BABYLON.Vector3();
  102225. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  102226. var tmpSnapEvent = { snapDistance: 0 };
  102227. var currentSnapDragDistance = 0;
  102228. var tmpMatrix = new BABYLON.Matrix();
  102229. var tmpVector = new BABYLON.Vector3();
  102230. var amountToRotate = new BABYLON.Quaternion();
  102231. _this.dragBehavior.onDragObservable.add(function (event) {
  102232. if (_this.attachedMesh) {
  102233. if (!_this.attachedMesh.rotationQuaternion) {
  102234. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102235. }
  102236. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  102237. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  102238. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  102239. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  102240. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  102241. var angle = Math.atan2(cross.length(), dot);
  102242. planeNormalTowardsCamera.copyFrom(planeNormal);
  102243. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  102244. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102245. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  102246. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  102247. }
  102248. // Flip up vector depending on which side the camera is on
  102249. if (gizmoLayer.utilityLayerScene.activeCamera) {
  102250. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  102251. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  102252. planeNormalTowardsCamera.scaleInPlace(-1);
  102253. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  102254. }
  102255. }
  102256. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  102257. if (halfCircleSide) {
  102258. angle = -angle;
  102259. }
  102260. // Snapping logic
  102261. var snapped = false;
  102262. if (_this.snapDistance != 0) {
  102263. currentSnapDragDistance += angle;
  102264. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102265. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102266. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102267. angle = _this.snapDistance * dragSteps;
  102268. snapped = true;
  102269. }
  102270. else {
  102271. angle = 0;
  102272. }
  102273. }
  102274. // If the mesh has a parent, convert needed world rotation to local rotation
  102275. tmpMatrix.reset();
  102276. if (_this.attachedMesh.parent) {
  102277. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102278. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  102279. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  102280. }
  102281. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  102282. var quaternionCoefficient = Math.sin(angle / 2);
  102283. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  102284. // 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
  102285. if (tmpMatrix.determinant() > 0) {
  102286. amountToRotate.toEulerAnglesToRef(tmpVector);
  102287. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  102288. }
  102289. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102290. // Rotate selected mesh quaternion over fixed axis
  102291. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  102292. }
  102293. else {
  102294. // Rotate selected mesh quaternion over rotated axis
  102295. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  102296. }
  102297. lastDragPosition.copyFrom(event.dragPlanePoint);
  102298. if (snapped) {
  102299. tmpSnapEvent.snapDistance = angle;
  102300. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102301. }
  102302. }
  102303. });
  102304. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102305. if (_this._customMeshSet) {
  102306. return;
  102307. }
  102308. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102309. var material = isHovered ? hoverMaterial : coloredMaterial;
  102310. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102311. m.material = material;
  102312. if (m.color) {
  102313. m.color = material.emissiveColor;
  102314. }
  102315. });
  102316. });
  102317. return _this;
  102318. }
  102319. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  102320. if (this.dragBehavior) {
  102321. this.dragBehavior.enabled = value ? true : false;
  102322. }
  102323. };
  102324. /**
  102325. * Disposes of the gizmo
  102326. */
  102327. PlaneRotationGizmo.prototype.dispose = function () {
  102328. this.onSnapObservable.clear();
  102329. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102330. this.dragBehavior.detach();
  102331. _super.prototype.dispose.call(this);
  102332. };
  102333. return PlaneRotationGizmo;
  102334. }(BABYLON.Gizmo));
  102335. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  102336. })(BABYLON || (BABYLON = {}));
  102337. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  102338. var BABYLON;
  102339. (function (BABYLON) {
  102340. /**
  102341. * Gizmo that enables dragging a mesh along 3 axis
  102342. */
  102343. var PositionGizmo = /** @class */ (function (_super) {
  102344. __extends(PositionGizmo, _super);
  102345. /**
  102346. * Creates a PositionGizmo
  102347. * @param gizmoLayer The utility layer the gizmo will be added to
  102348. */
  102349. function PositionGizmo(gizmoLayer) {
  102350. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102351. var _this = _super.call(this, gizmoLayer) || this;
  102352. /** Fires an event when any of it's sub gizmos are dragged */
  102353. _this.onDragStartObservable = new BABYLON.Observable();
  102354. /** Fires an event when any of it's sub gizmos are released from dragging */
  102355. _this.onDragEndObservable = new BABYLON.Observable();
  102356. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102357. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102358. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102359. // Relay drag events
  102360. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102361. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102362. _this.onDragStartObservable.notifyObservers({});
  102363. });
  102364. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102365. _this.onDragEndObservable.notifyObservers({});
  102366. });
  102367. });
  102368. _this.attachedMesh = null;
  102369. return _this;
  102370. }
  102371. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  102372. set: function (mesh) {
  102373. if (this.xGizmo) {
  102374. this.xGizmo.attachedMesh = mesh;
  102375. this.yGizmo.attachedMesh = mesh;
  102376. this.zGizmo.attachedMesh = mesh;
  102377. }
  102378. },
  102379. enumerable: true,
  102380. configurable: true
  102381. });
  102382. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102383. get: function () {
  102384. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102385. },
  102386. set: function (value) {
  102387. if (this.xGizmo) {
  102388. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102389. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102390. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102391. }
  102392. },
  102393. enumerable: true,
  102394. configurable: true
  102395. });
  102396. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  102397. get: function () {
  102398. return this.xGizmo.snapDistance;
  102399. },
  102400. /**
  102401. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102402. */
  102403. set: function (value) {
  102404. if (this.xGizmo) {
  102405. this.xGizmo.snapDistance = value;
  102406. this.yGizmo.snapDistance = value;
  102407. this.zGizmo.snapDistance = value;
  102408. }
  102409. },
  102410. enumerable: true,
  102411. configurable: true
  102412. });
  102413. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  102414. get: function () {
  102415. return this.xGizmo.scaleRatio;
  102416. },
  102417. /**
  102418. * Ratio for the scale of the gizmo (Default: 1)
  102419. */
  102420. set: function (value) {
  102421. if (this.xGizmo) {
  102422. this.xGizmo.scaleRatio = value;
  102423. this.yGizmo.scaleRatio = value;
  102424. this.zGizmo.scaleRatio = value;
  102425. }
  102426. },
  102427. enumerable: true,
  102428. configurable: true
  102429. });
  102430. /**
  102431. * Disposes of the gizmo
  102432. */
  102433. PositionGizmo.prototype.dispose = function () {
  102434. this.xGizmo.dispose();
  102435. this.yGizmo.dispose();
  102436. this.zGizmo.dispose();
  102437. this.onDragStartObservable.clear();
  102438. this.onDragEndObservable.clear();
  102439. };
  102440. /**
  102441. * CustomMeshes are not supported by this gizmo
  102442. * @param mesh The mesh to replace the default mesh of the gizmo
  102443. */
  102444. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  102445. 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)");
  102446. };
  102447. return PositionGizmo;
  102448. }(BABYLON.Gizmo));
  102449. BABYLON.PositionGizmo = PositionGizmo;
  102450. })(BABYLON || (BABYLON = {}));
  102451. //# sourceMappingURL=babylon.positionGizmo.js.map
  102452. var BABYLON;
  102453. (function (BABYLON) {
  102454. /**
  102455. * Gizmo that enables rotating a mesh along 3 axis
  102456. */
  102457. var RotationGizmo = /** @class */ (function (_super) {
  102458. __extends(RotationGizmo, _super);
  102459. /**
  102460. * Creates a RotationGizmo
  102461. * @param gizmoLayer The utility layer the gizmo will be added to
  102462. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102463. */
  102464. function RotationGizmo(gizmoLayer, tessellation) {
  102465. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102466. if (tessellation === void 0) { tessellation = 32; }
  102467. var _this = _super.call(this, gizmoLayer) || this;
  102468. /** Fires an event when any of it's sub gizmos are dragged */
  102469. _this.onDragStartObservable = new BABYLON.Observable();
  102470. /** Fires an event when any of it's sub gizmos are released from dragging */
  102471. _this.onDragEndObservable = new BABYLON.Observable();
  102472. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  102473. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  102474. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  102475. // Relay drag events
  102476. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102477. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102478. _this.onDragStartObservable.notifyObservers({});
  102479. });
  102480. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102481. _this.onDragEndObservable.notifyObservers({});
  102482. });
  102483. });
  102484. _this.attachedMesh = null;
  102485. return _this;
  102486. }
  102487. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  102488. set: function (mesh) {
  102489. if (this.xGizmo) {
  102490. this.xGizmo.attachedMesh = mesh;
  102491. this.yGizmo.attachedMesh = mesh;
  102492. this.zGizmo.attachedMesh = mesh;
  102493. }
  102494. },
  102495. enumerable: true,
  102496. configurable: true
  102497. });
  102498. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102499. get: function () {
  102500. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102501. },
  102502. set: function (value) {
  102503. if (this.xGizmo) {
  102504. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102505. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102506. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102507. }
  102508. },
  102509. enumerable: true,
  102510. configurable: true
  102511. });
  102512. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  102513. get: function () {
  102514. return this.xGizmo.snapDistance;
  102515. },
  102516. /**
  102517. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102518. */
  102519. set: function (value) {
  102520. if (this.xGizmo) {
  102521. this.xGizmo.snapDistance = value;
  102522. this.yGizmo.snapDistance = value;
  102523. this.zGizmo.snapDistance = value;
  102524. }
  102525. },
  102526. enumerable: true,
  102527. configurable: true
  102528. });
  102529. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  102530. get: function () {
  102531. return this.xGizmo.scaleRatio;
  102532. },
  102533. /**
  102534. * Ratio for the scale of the gizmo (Default: 1)
  102535. */
  102536. set: function (value) {
  102537. if (this.xGizmo) {
  102538. this.xGizmo.scaleRatio = value;
  102539. this.yGizmo.scaleRatio = value;
  102540. this.zGizmo.scaleRatio = value;
  102541. }
  102542. },
  102543. enumerable: true,
  102544. configurable: true
  102545. });
  102546. /**
  102547. * Disposes of the gizmo
  102548. */
  102549. RotationGizmo.prototype.dispose = function () {
  102550. this.xGizmo.dispose();
  102551. this.yGizmo.dispose();
  102552. this.zGizmo.dispose();
  102553. this.onDragStartObservable.clear();
  102554. this.onDragEndObservable.clear();
  102555. };
  102556. /**
  102557. * CustomMeshes are not supported by this gizmo
  102558. * @param mesh The mesh to replace the default mesh of the gizmo
  102559. */
  102560. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  102561. 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)");
  102562. };
  102563. return RotationGizmo;
  102564. }(BABYLON.Gizmo));
  102565. BABYLON.RotationGizmo = RotationGizmo;
  102566. })(BABYLON || (BABYLON = {}));
  102567. //# sourceMappingURL=babylon.rotationGizmo.js.map
  102568. var BABYLON;
  102569. (function (BABYLON) {
  102570. /**
  102571. * Gizmo that enables scaling a mesh along 3 axis
  102572. */
  102573. var ScaleGizmo = /** @class */ (function (_super) {
  102574. __extends(ScaleGizmo, _super);
  102575. /**
  102576. * Creates a ScaleGizmo
  102577. * @param gizmoLayer The utility layer the gizmo will be added to
  102578. */
  102579. function ScaleGizmo(gizmoLayer) {
  102580. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102581. var _this = _super.call(this, gizmoLayer) || this;
  102582. /** Fires an event when any of it's sub gizmos are dragged */
  102583. _this.onDragStartObservable = new BABYLON.Observable();
  102584. /** Fires an event when any of it's sub gizmos are released from dragging */
  102585. _this.onDragEndObservable = new BABYLON.Observable();
  102586. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102587. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102588. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102589. // Create uniform scale gizmo
  102590. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  102591. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  102592. _this.uniformScaleGizmo.uniformScaling = true;
  102593. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102594. uniformScalingMesh.scaling.scaleInPlace(0.02);
  102595. uniformScalingMesh.visibility = 0;
  102596. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102597. octahedron.scaling.scaleInPlace(0.007);
  102598. uniformScalingMesh.addChild(octahedron);
  102599. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  102600. // Relay drag events
  102601. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  102602. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102603. _this.onDragStartObservable.notifyObservers({});
  102604. });
  102605. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102606. _this.onDragEndObservable.notifyObservers({});
  102607. });
  102608. });
  102609. _this.attachedMesh = null;
  102610. return _this;
  102611. }
  102612. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  102613. set: function (mesh) {
  102614. if (this.xGizmo) {
  102615. this.xGizmo.attachedMesh = mesh;
  102616. this.yGizmo.attachedMesh = mesh;
  102617. this.zGizmo.attachedMesh = mesh;
  102618. this.uniformScaleGizmo.attachedMesh = mesh;
  102619. }
  102620. },
  102621. enumerable: true,
  102622. configurable: true
  102623. });
  102624. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102625. get: function () {
  102626. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102627. },
  102628. set: function (value) {
  102629. if (!value) {
  102630. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  102631. }
  102632. if (this.xGizmo) {
  102633. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102634. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102635. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102636. }
  102637. },
  102638. enumerable: true,
  102639. configurable: true
  102640. });
  102641. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  102642. get: function () {
  102643. return this.xGizmo.snapDistance;
  102644. },
  102645. /**
  102646. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102647. */
  102648. set: function (value) {
  102649. if (this.xGizmo) {
  102650. this.xGizmo.snapDistance = value;
  102651. this.yGizmo.snapDistance = value;
  102652. this.zGizmo.snapDistance = value;
  102653. this.uniformScaleGizmo.snapDistance = value;
  102654. }
  102655. },
  102656. enumerable: true,
  102657. configurable: true
  102658. });
  102659. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  102660. get: function () {
  102661. return this.xGizmo.scaleRatio;
  102662. },
  102663. /**
  102664. * Ratio for the scale of the gizmo (Default: 1)
  102665. */
  102666. set: function (value) {
  102667. if (this.xGizmo) {
  102668. this.xGizmo.scaleRatio = value;
  102669. this.yGizmo.scaleRatio = value;
  102670. this.zGizmo.scaleRatio = value;
  102671. this.uniformScaleGizmo.scaleRatio = value;
  102672. }
  102673. },
  102674. enumerable: true,
  102675. configurable: true
  102676. });
  102677. /**
  102678. * Disposes of the gizmo
  102679. */
  102680. ScaleGizmo.prototype.dispose = function () {
  102681. this.xGizmo.dispose();
  102682. this.yGizmo.dispose();
  102683. this.zGizmo.dispose();
  102684. this.uniformScaleGizmo.dispose();
  102685. this.onDragStartObservable.clear();
  102686. this.onDragEndObservable.clear();
  102687. };
  102688. return ScaleGizmo;
  102689. }(BABYLON.Gizmo));
  102690. BABYLON.ScaleGizmo = ScaleGizmo;
  102691. })(BABYLON || (BABYLON = {}));
  102692. //# sourceMappingURL=babylon.scaleGizmo.js.map
  102693. var BABYLON;
  102694. (function (BABYLON) {
  102695. /**
  102696. * Bounding box gizmo
  102697. */
  102698. var BoundingBoxGizmo = /** @class */ (function (_super) {
  102699. __extends(BoundingBoxGizmo, _super);
  102700. /**
  102701. * Creates an BoundingBoxGizmo
  102702. * @param gizmoLayer The utility layer the gizmo will be added to
  102703. * @param color The color of the gizmo
  102704. */
  102705. function BoundingBoxGizmo(color, gizmoLayer) {
  102706. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102707. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  102708. var _this = _super.call(this, gizmoLayer) || this;
  102709. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  102710. _this._renderObserver = null;
  102711. _this._pointerObserver = null;
  102712. _this._scaleDragSpeed = 0.2;
  102713. _this._tmpQuaternion = new BABYLON.Quaternion();
  102714. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  102715. _this._tmpRotationMatrix = new BABYLON.Matrix();
  102716. /**
  102717. * 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)
  102718. */
  102719. _this.ignoreChildren = false;
  102720. /**
  102721. * 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)
  102722. */
  102723. _this.includeChildPredicate = null;
  102724. /**
  102725. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  102726. */
  102727. _this.rotationSphereSize = 0.1;
  102728. /**
  102729. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  102730. */
  102731. _this.scaleBoxSize = 0.1;
  102732. /**
  102733. * 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)
  102734. */
  102735. _this.fixedDragMeshScreenSize = false;
  102736. /**
  102737. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  102738. */
  102739. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  102740. /**
  102741. * Fired when a rotation sphere or scale box is dragged
  102742. */
  102743. _this.onDragStartObservable = new BABYLON.Observable();
  102744. /**
  102745. * Fired when a scale box is dragged
  102746. */
  102747. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  102748. /**
  102749. * Fired when a scale box drag is ended
  102750. */
  102751. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  102752. /**
  102753. * Fired when a rotation sphere is dragged
  102754. */
  102755. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  102756. /**
  102757. * Fired when a rotation sphere drag is ended
  102758. */
  102759. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  102760. /**
  102761. * 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)
  102762. */
  102763. _this.scalePivot = null;
  102764. _this._existingMeshScale = new BABYLON.Vector3();
  102765. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  102766. _this._updateScale = false;
  102767. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  102768. // Create Materials
  102769. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102770. coloredMaterial.disableLighting = true;
  102771. coloredMaterial.emissiveColor = color;
  102772. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102773. hoverColoredMaterial.disableLighting = true;
  102774. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102775. // Build bounding box out of lines
  102776. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102777. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  102778. var lines = [];
  102779. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  102780. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  102781. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  102782. 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));
  102783. 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));
  102784. 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));
  102785. 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));
  102786. 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));
  102787. 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));
  102788. 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));
  102789. 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));
  102790. 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));
  102791. lines.forEach(function (l) {
  102792. l.color = color;
  102793. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  102794. l.isPickable = false;
  102795. _this._lineBoundingBox.addChild(l);
  102796. });
  102797. _this._rootMesh.addChild(_this._lineBoundingBox);
  102798. // Create rotation spheres
  102799. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102800. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  102801. var _loop_1 = function (i_1) {
  102802. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  102803. sphere.rotationQuaternion = new BABYLON.Quaternion();
  102804. sphere.material = coloredMaterial;
  102805. // Drag behavior
  102806. _dragBehavior = new BABYLON.PointerDragBehavior({});
  102807. _dragBehavior.moveAttached = false;
  102808. _dragBehavior.updateDragPlane = false;
  102809. sphere.addBehavior(_dragBehavior);
  102810. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  102811. var totalTurnAmountOfDrag = 0;
  102812. _dragBehavior.onDragStartObservable.add(function (event) {
  102813. startingTurnDirection.copyFrom(sphere.forward);
  102814. totalTurnAmountOfDrag = 0;
  102815. });
  102816. _dragBehavior.onDragObservable.add(function (event) {
  102817. _this.onRotationSphereDragObservable.notifyObservers({});
  102818. if (_this.attachedMesh) {
  102819. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102820. var worldDragDirection = startingTurnDirection;
  102821. // Project the world right on to the drag plane
  102822. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  102823. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  102824. // project drag delta on to the resulting drag axis and rotate based on that
  102825. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  102826. // Make rotation relative to size of mesh.
  102827. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102828. // Rotate based on axis
  102829. if (!_this.attachedMesh.rotationQuaternion) {
  102830. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102831. }
  102832. if (!_this._anchorMesh.rotationQuaternion) {
  102833. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  102834. }
  102835. // Do not allow the object to turn more than a full circle
  102836. totalTurnAmountOfDrag += projectDist;
  102837. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  102838. if (i_1 >= 8) {
  102839. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  102840. }
  102841. else if (i_1 >= 4) {
  102842. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  102843. }
  102844. else {
  102845. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  102846. }
  102847. // Rotate around center of bounding box
  102848. _this._anchorMesh.addChild(_this.attachedMesh);
  102849. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  102850. _this._anchorMesh.removeChild(_this.attachedMesh);
  102851. }
  102852. _this.updateBoundingBox();
  102853. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102854. }
  102855. });
  102856. // Selection/deselection
  102857. _dragBehavior.onDragStartObservable.add(function () {
  102858. _this.onDragStartObservable.notifyObservers({});
  102859. _this._selectNode(sphere);
  102860. });
  102861. _dragBehavior.onDragEndObservable.add(function () {
  102862. _this.onRotationSphereDragEndObservable.notifyObservers({});
  102863. _this._selectNode(null);
  102864. });
  102865. this_1._rotateSpheresParent.addChild(sphere);
  102866. };
  102867. var this_1 = this, _dragBehavior;
  102868. for (var i_1 = 0; i_1 < 12; i_1++) {
  102869. _loop_1(i_1);
  102870. }
  102871. _this._rootMesh.addChild(_this._rotateSpheresParent);
  102872. // Create scale cubes
  102873. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102874. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  102875. for (var i = 0; i < 2; i++) {
  102876. for (var j = 0; j < 2; j++) {
  102877. var _loop_2 = function () {
  102878. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  102879. box.material = coloredMaterial;
  102880. // Dragging logic
  102881. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  102882. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102883. _dragBehavior.moveAttached = false;
  102884. box.addBehavior(_dragBehavior);
  102885. _dragBehavior.onDragObservable.add(function (event) {
  102886. _this.onScaleBoxDragObservable.notifyObservers({});
  102887. if (_this.attachedMesh) {
  102888. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102889. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102890. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  102891. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  102892. _this.updateBoundingBox();
  102893. if (_this.scalePivot) {
  102894. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  102895. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  102896. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  102897. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102898. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102899. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  102900. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  102901. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  102902. }
  102903. else {
  102904. // Scale from the position of the opposite corner
  102905. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  102906. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  102907. }
  102908. _this._anchorMesh.addChild(_this.attachedMesh);
  102909. _this._anchorMesh.scaling.addInPlace(deltaScale);
  102910. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  102911. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  102912. }
  102913. _this._anchorMesh.removeChild(_this.attachedMesh);
  102914. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102915. }
  102916. });
  102917. // Selection/deselection
  102918. _dragBehavior.onDragStartObservable.add(function () {
  102919. _this.onDragStartObservable.notifyObservers({});
  102920. _this._selectNode(box);
  102921. });
  102922. _dragBehavior.onDragEndObservable.add(function () {
  102923. _this.onScaleBoxDragEndObservable.notifyObservers({});
  102924. _this._selectNode(null);
  102925. });
  102926. this_2._scaleBoxesParent.addChild(box);
  102927. };
  102928. var this_2 = this, _dragBehavior;
  102929. for (var k = 0; k < 2; k++) {
  102930. _loop_2();
  102931. }
  102932. }
  102933. }
  102934. _this._rootMesh.addChild(_this._scaleBoxesParent);
  102935. // Hover color change
  102936. var pointerIds = new Array();
  102937. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102938. if (!pointerIds[pointerInfo.event.pointerId]) {
  102939. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  102940. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  102941. pointerIds[pointerInfo.event.pointerId] = mesh;
  102942. mesh.material = hoverColoredMaterial;
  102943. }
  102944. });
  102945. }
  102946. else {
  102947. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  102948. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  102949. delete pointerIds[pointerInfo.event.pointerId];
  102950. }
  102951. }
  102952. });
  102953. // Update bounding box positions
  102954. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  102955. // Only update the bouding box if scaling has changed
  102956. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  102957. _this.updateBoundingBox();
  102958. }
  102959. });
  102960. _this.updateBoundingBox();
  102961. return _this;
  102962. }
  102963. /** @hidden */
  102964. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  102965. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  102966. // Save old pivot and set pivot to 0,0,0
  102967. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  102968. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  102969. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  102970. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  102971. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102972. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102973. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102974. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  102975. }
  102976. }
  102977. BoundingBoxGizmo._PivotCached++;
  102978. };
  102979. /** @hidden */
  102980. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  102981. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  102982. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  102983. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  102984. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  102985. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  102986. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  102987. }
  102988. this._PivotCached--;
  102989. };
  102990. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  102991. if (value) {
  102992. // Reset anchor mesh to match attached mesh's scale
  102993. // This is needed to avoid invalid box/sphere position on first drag
  102994. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  102995. this._anchorMesh.addChild(value);
  102996. this._anchorMesh.removeChild(value);
  102997. BoundingBoxGizmo._RestorePivotPoint(value);
  102998. this.updateBoundingBox();
  102999. }
  103000. };
  103001. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  103002. this._rotateSpheresParent.getChildMeshes()
  103003. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  103004. m.isVisible = (!selectedMesh || m == selectedMesh);
  103005. });
  103006. };
  103007. /**
  103008. * Updates the bounding box information for the Gizmo
  103009. */
  103010. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  103011. if (this.attachedMesh) {
  103012. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  103013. this._update();
  103014. // Rotate based on axis
  103015. if (!this.attachedMesh.rotationQuaternion) {
  103016. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  103017. }
  103018. if (!this._anchorMesh.rotationQuaternion) {
  103019. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  103020. }
  103021. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103022. // Store original position and reset mesh to origin before computing the bounding box
  103023. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103024. this._tmpVector.copyFrom(this.attachedMesh.position);
  103025. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  103026. this.attachedMesh.position.set(0, 0, 0);
  103027. // Update bounding dimensions/positions
  103028. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  103029. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  103030. // Update gizmo to match bounding box scaling and rotation
  103031. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  103032. 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);
  103033. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  103034. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  103035. this._lineBoundingBox.computeWorldMatrix();
  103036. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  103037. // restore position/rotation values
  103038. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  103039. this.attachedMesh.position.copyFrom(this._tmpVector);
  103040. }
  103041. // Update rotation sphere locations
  103042. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  103043. for (var i = 0; i < 3; i++) {
  103044. for (var j = 0; j < 2; j++) {
  103045. for (var k = 0; k < 2; k++) {
  103046. var index = ((i * 4) + (j * 2)) + k;
  103047. if (i == 0) {
  103048. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103049. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103050. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103051. }
  103052. if (i == 1) {
  103053. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  103054. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103055. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103056. }
  103057. if (i == 2) {
  103058. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  103059. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103060. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103061. }
  103062. if (this.fixedDragMeshScreenSize) {
  103063. this._rootMesh.computeWorldMatrix();
  103064. this._rotateSpheresParent.computeWorldMatrix();
  103065. rotateSpheres[index].computeWorldMatrix();
  103066. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103067. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103068. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103069. }
  103070. else {
  103071. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  103072. }
  103073. }
  103074. }
  103075. }
  103076. // Update scale box locations
  103077. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  103078. for (var i = 0; i < 2; i++) {
  103079. for (var j = 0; j < 2; j++) {
  103080. for (var k = 0; k < 2; k++) {
  103081. var index = ((i * 4) + (j * 2)) + k;
  103082. if (scaleBoxes[index]) {
  103083. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103084. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103085. if (this.fixedDragMeshScreenSize) {
  103086. this._rootMesh.computeWorldMatrix();
  103087. this._scaleBoxesParent.computeWorldMatrix();
  103088. scaleBoxes[index].computeWorldMatrix();
  103089. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103090. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103091. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103092. }
  103093. else {
  103094. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  103095. }
  103096. }
  103097. }
  103098. }
  103099. }
  103100. if (this.attachedMesh) {
  103101. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  103102. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  103103. }
  103104. };
  103105. /**
  103106. * Enables rotation on the specified axis and disables rotation on the others
  103107. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  103108. */
  103109. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  103110. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  103111. if (i < 4) {
  103112. m.setEnabled(axis.indexOf("x") != -1);
  103113. }
  103114. else if (i < 8) {
  103115. m.setEnabled(axis.indexOf("y") != -1);
  103116. }
  103117. else {
  103118. m.setEnabled(axis.indexOf("z") != -1);
  103119. }
  103120. });
  103121. };
  103122. /**
  103123. * Disposes of the gizmo
  103124. */
  103125. BoundingBoxGizmo.prototype.dispose = function () {
  103126. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103127. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  103128. this._lineBoundingBox.dispose();
  103129. this._rotateSpheresParent.dispose();
  103130. this._scaleBoxesParent.dispose();
  103131. _super.prototype.dispose.call(this);
  103132. };
  103133. /**
  103134. * 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)
  103135. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  103136. * @returns the bounding box mesh with the passed in mesh as a child
  103137. */
  103138. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  103139. var makeNotPickable = function (root) {
  103140. root.isPickable = false;
  103141. root.getChildMeshes().forEach(function (c) {
  103142. makeNotPickable(c);
  103143. });
  103144. };
  103145. makeNotPickable(mesh);
  103146. // Reset position to get boudning box from origin with no rotation
  103147. if (!mesh.rotationQuaternion) {
  103148. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  103149. }
  103150. var oldPos = mesh.position.clone();
  103151. var oldRot = mesh.rotationQuaternion.clone();
  103152. mesh.rotationQuaternion.set(0, 0, 0, 1);
  103153. mesh.position.set(0, 0, 0);
  103154. // Update bounding dimensions/positions
  103155. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  103156. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  103157. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  103158. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  103159. // Restore original positions
  103160. mesh.addChild(box);
  103161. mesh.rotationQuaternion.copyFrom(oldRot);
  103162. mesh.position.copyFrom(oldPos);
  103163. // Reverse parenting
  103164. mesh.removeChild(box);
  103165. box.addChild(mesh);
  103166. box.visibility = 0;
  103167. return box;
  103168. };
  103169. /**
  103170. * CustomMeshes are not supported by this gizmo
  103171. * @param mesh The mesh to replace the default mesh of the gizmo
  103172. */
  103173. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  103174. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  103175. };
  103176. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  103177. // store/remove pivot point should only be applied during their outermost calls
  103178. BoundingBoxGizmo._PivotCached = 0;
  103179. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  103180. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  103181. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  103182. return BoundingBoxGizmo;
  103183. }(BABYLON.Gizmo));
  103184. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  103185. })(BABYLON || (BABYLON = {}));
  103186. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  103187. var BABYLON;
  103188. (function (BABYLON) {
  103189. /**
  103190. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  103191. */
  103192. var GizmoManager = /** @class */ (function () {
  103193. /**
  103194. * Instatiates a gizmo manager
  103195. * @param scene the scene to overlay the gizmos on top of
  103196. */
  103197. function GizmoManager(scene) {
  103198. var _this = this;
  103199. this.scene = scene;
  103200. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  103201. this._pointerObserver = null;
  103202. this._attachedMesh = null;
  103203. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  103204. /**
  103205. * When bounding box gizmo is enabled, this can be used to track drag/end events
  103206. */
  103207. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  103208. /**
  103209. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  103210. */
  103211. this.attachableMeshes = null;
  103212. /**
  103213. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  103214. */
  103215. this.usePointerToAttachGizmos = true;
  103216. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103217. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  103218. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103219. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  103220. // Instatiate/dispose gizmos based on pointer actions
  103221. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  103222. if (!_this.usePointerToAttachGizmos) {
  103223. return;
  103224. }
  103225. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  103226. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  103227. var node = pointerInfo.pickInfo.pickedMesh;
  103228. if (_this.attachableMeshes == null) {
  103229. // Attach to the most parent node
  103230. while (node && node.parent != null) {
  103231. node = node.parent;
  103232. }
  103233. }
  103234. else {
  103235. // Attach to the parent node that is an attachableMesh
  103236. var found = false;
  103237. _this.attachableMeshes.forEach(function (mesh) {
  103238. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  103239. node = mesh;
  103240. found = true;
  103241. }
  103242. });
  103243. if (!found) {
  103244. node = null;
  103245. }
  103246. }
  103247. if (node instanceof BABYLON.AbstractMesh) {
  103248. if (_this._attachedMesh != node) {
  103249. _this.attachToMesh(node);
  103250. }
  103251. }
  103252. else {
  103253. _this.attachToMesh(null);
  103254. }
  103255. }
  103256. else {
  103257. _this.attachToMesh(null);
  103258. }
  103259. }
  103260. });
  103261. }
  103262. /**
  103263. * Attaches a set of gizmos to the specified mesh
  103264. * @param mesh The mesh the gizmo's should be attached to
  103265. */
  103266. GizmoManager.prototype.attachToMesh = function (mesh) {
  103267. if (this._attachedMesh) {
  103268. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103269. }
  103270. this._attachedMesh = mesh;
  103271. for (var key in this.gizmos) {
  103272. var gizmo = (this.gizmos[key]);
  103273. if (gizmo && this._gizmosEnabled[key]) {
  103274. gizmo.attachedMesh = mesh;
  103275. }
  103276. }
  103277. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  103278. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103279. }
  103280. };
  103281. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  103282. get: function () {
  103283. return this._gizmosEnabled.positionGizmo;
  103284. },
  103285. /**
  103286. * If the position gizmo is enabled
  103287. */
  103288. set: function (value) {
  103289. if (value) {
  103290. if (!this.gizmos.positionGizmo) {
  103291. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  103292. }
  103293. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  103294. }
  103295. else if (this.gizmos.positionGizmo) {
  103296. this.gizmos.positionGizmo.attachedMesh = null;
  103297. }
  103298. this._gizmosEnabled.positionGizmo = value;
  103299. },
  103300. enumerable: true,
  103301. configurable: true
  103302. });
  103303. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  103304. get: function () {
  103305. return this._gizmosEnabled.rotationGizmo;
  103306. },
  103307. /**
  103308. * If the rotation gizmo is enabled
  103309. */
  103310. set: function (value) {
  103311. if (value) {
  103312. if (!this.gizmos.rotationGizmo) {
  103313. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  103314. }
  103315. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  103316. }
  103317. else if (this.gizmos.rotationGizmo) {
  103318. this.gizmos.rotationGizmo.attachedMesh = null;
  103319. }
  103320. this._gizmosEnabled.rotationGizmo = value;
  103321. },
  103322. enumerable: true,
  103323. configurable: true
  103324. });
  103325. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  103326. get: function () {
  103327. return this._gizmosEnabled.scaleGizmo;
  103328. },
  103329. /**
  103330. * If the scale gizmo is enabled
  103331. */
  103332. set: function (value) {
  103333. if (value) {
  103334. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  103335. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  103336. }
  103337. else if (this.gizmos.scaleGizmo) {
  103338. this.gizmos.scaleGizmo.attachedMesh = null;
  103339. }
  103340. this._gizmosEnabled.scaleGizmo = value;
  103341. },
  103342. enumerable: true,
  103343. configurable: true
  103344. });
  103345. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  103346. get: function () {
  103347. return this._gizmosEnabled.boundingBoxGizmo;
  103348. },
  103349. /**
  103350. * If the boundingBox gizmo is enabled
  103351. */
  103352. set: function (value) {
  103353. if (value) {
  103354. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  103355. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  103356. if (this._attachedMesh) {
  103357. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103358. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103359. }
  103360. }
  103361. else if (this.gizmos.boundingBoxGizmo) {
  103362. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  103363. }
  103364. this._gizmosEnabled.boundingBoxGizmo = value;
  103365. },
  103366. enumerable: true,
  103367. configurable: true
  103368. });
  103369. /**
  103370. * Disposes of the gizmo manager
  103371. */
  103372. GizmoManager.prototype.dispose = function () {
  103373. this.scene.onPointerObservable.remove(this._pointerObserver);
  103374. for (var key in this.gizmos) {
  103375. var gizmo = (this.gizmos[key]);
  103376. if (gizmo) {
  103377. gizmo.dispose();
  103378. }
  103379. }
  103380. this._defaultKeepDepthUtilityLayer.dispose();
  103381. this._defaultUtilityLayer.dispose();
  103382. this.boundingBoxDragBehavior.detach();
  103383. };
  103384. return GizmoManager;
  103385. }());
  103386. BABYLON.GizmoManager = GizmoManager;
  103387. })(BABYLON || (BABYLON = {}));
  103388. //# sourceMappingURL=babylon.gizmoManager.js.map
  103389. var BABYLON;
  103390. (function (BABYLON) {
  103391. /**
  103392. * Defines a target to use with MorphTargetManager
  103393. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103394. */
  103395. var MorphTarget = /** @class */ (function () {
  103396. /**
  103397. * Creates a new MorphTarget
  103398. * @param name defines the name of the target
  103399. * @param influence defines the influence to use
  103400. */
  103401. function MorphTarget(
  103402. /** defines the name of the target */
  103403. name, influence, scene) {
  103404. if (influence === void 0) { influence = 0; }
  103405. if (scene === void 0) { scene = null; }
  103406. this.name = name;
  103407. /**
  103408. * Gets or sets the list of animations
  103409. */
  103410. this.animations = new Array();
  103411. this._positions = null;
  103412. this._normals = null;
  103413. this._tangents = null;
  103414. /**
  103415. * Observable raised when the influence changes
  103416. */
  103417. this.onInfluenceChanged = new BABYLON.Observable();
  103418. /** @hidden */
  103419. this._onDataLayoutChanged = new BABYLON.Observable();
  103420. this._animationPropertiesOverride = null;
  103421. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103422. this.influence = influence;
  103423. }
  103424. Object.defineProperty(MorphTarget.prototype, "influence", {
  103425. /**
  103426. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  103427. */
  103428. get: function () {
  103429. return this._influence;
  103430. },
  103431. set: function (influence) {
  103432. if (this._influence === influence) {
  103433. return;
  103434. }
  103435. var previous = this._influence;
  103436. this._influence = influence;
  103437. if (this.onInfluenceChanged.hasObservers) {
  103438. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  103439. }
  103440. },
  103441. enumerable: true,
  103442. configurable: true
  103443. });
  103444. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  103445. /**
  103446. * Gets or sets the animation properties override
  103447. */
  103448. get: function () {
  103449. if (!this._animationPropertiesOverride && this._scene) {
  103450. return this._scene.animationPropertiesOverride;
  103451. }
  103452. return this._animationPropertiesOverride;
  103453. },
  103454. set: function (value) {
  103455. this._animationPropertiesOverride = value;
  103456. },
  103457. enumerable: true,
  103458. configurable: true
  103459. });
  103460. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  103461. /**
  103462. * Gets a boolean defining if the target contains position data
  103463. */
  103464. get: function () {
  103465. return !!this._positions;
  103466. },
  103467. enumerable: true,
  103468. configurable: true
  103469. });
  103470. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  103471. /**
  103472. * Gets a boolean defining if the target contains normal data
  103473. */
  103474. get: function () {
  103475. return !!this._normals;
  103476. },
  103477. enumerable: true,
  103478. configurable: true
  103479. });
  103480. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  103481. /**
  103482. * Gets a boolean defining if the target contains tangent data
  103483. */
  103484. get: function () {
  103485. return !!this._tangents;
  103486. },
  103487. enumerable: true,
  103488. configurable: true
  103489. });
  103490. /**
  103491. * Affects position data to this target
  103492. * @param data defines the position data to use
  103493. */
  103494. MorphTarget.prototype.setPositions = function (data) {
  103495. var hadPositions = this.hasPositions;
  103496. this._positions = data;
  103497. if (hadPositions !== this.hasPositions) {
  103498. this._onDataLayoutChanged.notifyObservers(undefined);
  103499. }
  103500. };
  103501. /**
  103502. * Gets the position data stored in this target
  103503. * @returns a FloatArray containing the position data (or null if not present)
  103504. */
  103505. MorphTarget.prototype.getPositions = function () {
  103506. return this._positions;
  103507. };
  103508. /**
  103509. * Affects normal data to this target
  103510. * @param data defines the normal data to use
  103511. */
  103512. MorphTarget.prototype.setNormals = function (data) {
  103513. var hadNormals = this.hasNormals;
  103514. this._normals = data;
  103515. if (hadNormals !== this.hasNormals) {
  103516. this._onDataLayoutChanged.notifyObservers(undefined);
  103517. }
  103518. };
  103519. /**
  103520. * Gets the normal data stored in this target
  103521. * @returns a FloatArray containing the normal data (or null if not present)
  103522. */
  103523. MorphTarget.prototype.getNormals = function () {
  103524. return this._normals;
  103525. };
  103526. /**
  103527. * Affects tangent data to this target
  103528. * @param data defines the tangent data to use
  103529. */
  103530. MorphTarget.prototype.setTangents = function (data) {
  103531. var hadTangents = this.hasTangents;
  103532. this._tangents = data;
  103533. if (hadTangents !== this.hasTangents) {
  103534. this._onDataLayoutChanged.notifyObservers(undefined);
  103535. }
  103536. };
  103537. /**
  103538. * Gets the tangent data stored in this target
  103539. * @returns a FloatArray containing the tangent data (or null if not present)
  103540. */
  103541. MorphTarget.prototype.getTangents = function () {
  103542. return this._tangents;
  103543. };
  103544. /**
  103545. * Serializes the current target into a Serialization object
  103546. * @returns the serialized object
  103547. */
  103548. MorphTarget.prototype.serialize = function () {
  103549. var serializationObject = {};
  103550. serializationObject.name = this.name;
  103551. serializationObject.influence = this.influence;
  103552. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  103553. if (this.hasNormals) {
  103554. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  103555. }
  103556. if (this.hasTangents) {
  103557. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  103558. }
  103559. // Animations
  103560. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  103561. return serializationObject;
  103562. };
  103563. // Statics
  103564. /**
  103565. * Creates a new target from serialized data
  103566. * @param serializationObject defines the serialized data to use
  103567. * @returns a new MorphTarget
  103568. */
  103569. MorphTarget.Parse = function (serializationObject) {
  103570. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  103571. result.setPositions(serializationObject.positions);
  103572. if (serializationObject.normals) {
  103573. result.setNormals(serializationObject.normals);
  103574. }
  103575. if (serializationObject.tangents) {
  103576. result.setTangents(serializationObject.tangents);
  103577. }
  103578. // Animations
  103579. if (serializationObject.animations) {
  103580. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  103581. var parsedAnimation = serializationObject.animations[animationIndex];
  103582. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  103583. }
  103584. }
  103585. return result;
  103586. };
  103587. /**
  103588. * Creates a MorphTarget from mesh data
  103589. * @param mesh defines the source mesh
  103590. * @param name defines the name to use for the new target
  103591. * @param influence defines the influence to attach to the target
  103592. * @returns a new MorphTarget
  103593. */
  103594. MorphTarget.FromMesh = function (mesh, name, influence) {
  103595. if (!name) {
  103596. name = mesh.name;
  103597. }
  103598. var result = new MorphTarget(name, influence, mesh.getScene());
  103599. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  103600. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103601. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  103602. }
  103603. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  103604. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  103605. }
  103606. return result;
  103607. };
  103608. return MorphTarget;
  103609. }());
  103610. BABYLON.MorphTarget = MorphTarget;
  103611. })(BABYLON || (BABYLON = {}));
  103612. //# sourceMappingURL=babylon.morphTarget.js.map
  103613. var BABYLON;
  103614. (function (BABYLON) {
  103615. /**
  103616. * This class is used to deform meshes using morphing between different targets
  103617. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103618. */
  103619. var MorphTargetManager = /** @class */ (function () {
  103620. /**
  103621. * Creates a new MorphTargetManager
  103622. * @param scene defines the current scene
  103623. */
  103624. function MorphTargetManager(scene) {
  103625. if (scene === void 0) { scene = null; }
  103626. this._targets = new Array();
  103627. this._targetInfluenceChangedObservers = new Array();
  103628. this._targetDataLayoutChangedObservers = new Array();
  103629. this._activeTargets = new BABYLON.SmartArray(16);
  103630. this._supportsNormals = false;
  103631. this._supportsTangents = false;
  103632. this._vertexCount = 0;
  103633. this._uniqueId = 0;
  103634. this._tempInfluences = new Array();
  103635. if (!scene) {
  103636. scene = BABYLON.Engine.LastCreatedScene;
  103637. }
  103638. this._scene = scene;
  103639. if (this._scene) {
  103640. this._scene.morphTargetManagers.push(this);
  103641. this._uniqueId = this._scene.getUniqueId();
  103642. }
  103643. }
  103644. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  103645. /**
  103646. * Gets the unique ID of this manager
  103647. */
  103648. get: function () {
  103649. return this._uniqueId;
  103650. },
  103651. enumerable: true,
  103652. configurable: true
  103653. });
  103654. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  103655. /**
  103656. * Gets the number of vertices handled by this manager
  103657. */
  103658. get: function () {
  103659. return this._vertexCount;
  103660. },
  103661. enumerable: true,
  103662. configurable: true
  103663. });
  103664. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  103665. /**
  103666. * Gets a boolean indicating if this manager supports morphing of normals
  103667. */
  103668. get: function () {
  103669. return this._supportsNormals;
  103670. },
  103671. enumerable: true,
  103672. configurable: true
  103673. });
  103674. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  103675. /**
  103676. * Gets a boolean indicating if this manager supports morphing of tangents
  103677. */
  103678. get: function () {
  103679. return this._supportsTangents;
  103680. },
  103681. enumerable: true,
  103682. configurable: true
  103683. });
  103684. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  103685. /**
  103686. * Gets the number of targets stored in this manager
  103687. */
  103688. get: function () {
  103689. return this._targets.length;
  103690. },
  103691. enumerable: true,
  103692. configurable: true
  103693. });
  103694. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  103695. /**
  103696. * Gets the number of influencers (ie. the number of targets with influences > 0)
  103697. */
  103698. get: function () {
  103699. return this._activeTargets.length;
  103700. },
  103701. enumerable: true,
  103702. configurable: true
  103703. });
  103704. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  103705. /**
  103706. * Gets the list of influences (one per target)
  103707. */
  103708. get: function () {
  103709. return this._influences;
  103710. },
  103711. enumerable: true,
  103712. configurable: true
  103713. });
  103714. /**
  103715. * Gets the active target at specified index. An active target is a target with an influence > 0
  103716. * @param index defines the index to check
  103717. * @returns the requested target
  103718. */
  103719. MorphTargetManager.prototype.getActiveTarget = function (index) {
  103720. return this._activeTargets.data[index];
  103721. };
  103722. /**
  103723. * Gets the target at specified index
  103724. * @param index defines the index to check
  103725. * @returns the requested target
  103726. */
  103727. MorphTargetManager.prototype.getTarget = function (index) {
  103728. return this._targets[index];
  103729. };
  103730. /**
  103731. * Add a new target to this manager
  103732. * @param target defines the target to add
  103733. */
  103734. MorphTargetManager.prototype.addTarget = function (target) {
  103735. var _this = this;
  103736. this._targets.push(target);
  103737. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  103738. _this._syncActiveTargets(needUpdate);
  103739. }));
  103740. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  103741. _this._syncActiveTargets(true);
  103742. }));
  103743. this._syncActiveTargets(true);
  103744. };
  103745. /**
  103746. * Removes a target from the manager
  103747. * @param target defines the target to remove
  103748. */
  103749. MorphTargetManager.prototype.removeTarget = function (target) {
  103750. var index = this._targets.indexOf(target);
  103751. if (index >= 0) {
  103752. this._targets.splice(index, 1);
  103753. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  103754. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  103755. this._syncActiveTargets(true);
  103756. }
  103757. };
  103758. /**
  103759. * Serializes the current manager into a Serialization object
  103760. * @returns the serialized object
  103761. */
  103762. MorphTargetManager.prototype.serialize = function () {
  103763. var serializationObject = {};
  103764. serializationObject.id = this.uniqueId;
  103765. serializationObject.targets = [];
  103766. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103767. var target = _a[_i];
  103768. serializationObject.targets.push(target.serialize());
  103769. }
  103770. return serializationObject;
  103771. };
  103772. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  103773. var influenceCount = 0;
  103774. this._activeTargets.reset();
  103775. this._supportsNormals = true;
  103776. this._supportsTangents = true;
  103777. this._vertexCount = 0;
  103778. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103779. var target = _a[_i];
  103780. if (target.influence === 0) {
  103781. continue;
  103782. }
  103783. this._activeTargets.push(target);
  103784. this._tempInfluences[influenceCount++] = target.influence;
  103785. this._supportsNormals = this._supportsNormals && target.hasNormals;
  103786. this._supportsTangents = this._supportsTangents && target.hasTangents;
  103787. var positions = target.getPositions();
  103788. if (positions) {
  103789. var vertexCount = positions.length / 3;
  103790. if (this._vertexCount === 0) {
  103791. this._vertexCount = vertexCount;
  103792. }
  103793. else if (this._vertexCount !== vertexCount) {
  103794. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  103795. return;
  103796. }
  103797. }
  103798. }
  103799. if (!this._influences || this._influences.length !== influenceCount) {
  103800. this._influences = new Float32Array(influenceCount);
  103801. }
  103802. for (var index = 0; index < influenceCount; index++) {
  103803. this._influences[index] = this._tempInfluences[index];
  103804. }
  103805. if (needUpdate) {
  103806. this.synchronize();
  103807. }
  103808. };
  103809. /**
  103810. * Syncrhonize the targets with all the meshes using this morph target manager
  103811. */
  103812. MorphTargetManager.prototype.synchronize = function () {
  103813. if (!this._scene) {
  103814. return;
  103815. }
  103816. // Flag meshes as dirty to resync with the active targets
  103817. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  103818. var mesh = _a[_i];
  103819. if (mesh.morphTargetManager === this) {
  103820. mesh._syncGeometryWithMorphTargetManager();
  103821. }
  103822. }
  103823. };
  103824. // Statics
  103825. /**
  103826. * Creates a new MorphTargetManager from serialized data
  103827. * @param serializationObject defines the serialized data
  103828. * @param scene defines the hosting scene
  103829. * @returns the new MorphTargetManager
  103830. */
  103831. MorphTargetManager.Parse = function (serializationObject, scene) {
  103832. var result = new MorphTargetManager(scene);
  103833. result._uniqueId = serializationObject.id;
  103834. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  103835. var targetData = _a[_i];
  103836. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  103837. }
  103838. return result;
  103839. };
  103840. return MorphTargetManager;
  103841. }());
  103842. BABYLON.MorphTargetManager = MorphTargetManager;
  103843. })(BABYLON || (BABYLON = {}));
  103844. //# sourceMappingURL=babylon.morphTargetManager.js.map
  103845. var BABYLON;
  103846. (function (BABYLON) {
  103847. /**
  103848. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  103849. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103850. */
  103851. var Octree = /** @class */ (function () {
  103852. /**
  103853. * Creates a octree
  103854. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103855. * @param creationFunc function to be used to instatiate the octree
  103856. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  103857. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  103858. */
  103859. function Octree(creationFunc, maxBlockCapacity,
  103860. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  103861. maxDepth) {
  103862. if (maxDepth === void 0) { maxDepth = 2; }
  103863. this.maxDepth = maxDepth;
  103864. /**
  103865. * Content stored in the octree
  103866. */
  103867. this.dynamicContent = new Array();
  103868. this._maxBlockCapacity = maxBlockCapacity || 64;
  103869. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  103870. this._creationFunc = creationFunc;
  103871. }
  103872. // Methods
  103873. /**
  103874. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  103875. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103876. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103877. * @param entries meshes to be added to the octree blocks
  103878. */
  103879. Octree.prototype.update = function (worldMin, worldMax, entries) {
  103880. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  103881. };
  103882. /**
  103883. * Adds a mesh to the octree
  103884. * @param entry Mesh to add to the octree
  103885. */
  103886. Octree.prototype.addMesh = function (entry) {
  103887. for (var index = 0; index < this.blocks.length; index++) {
  103888. var block = this.blocks[index];
  103889. block.addEntry(entry);
  103890. }
  103891. };
  103892. /**
  103893. * Selects an array of meshes within the frustum
  103894. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  103895. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  103896. * @returns array of meshes within the frustum
  103897. */
  103898. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  103899. this._selectionContent.reset();
  103900. for (var index = 0; index < this.blocks.length; index++) {
  103901. var block = this.blocks[index];
  103902. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  103903. }
  103904. if (allowDuplicate) {
  103905. this._selectionContent.concat(this.dynamicContent);
  103906. }
  103907. else {
  103908. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103909. }
  103910. return this._selectionContent;
  103911. };
  103912. /**
  103913. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  103914. * @param sphereCenter defines the bounding sphere center
  103915. * @param sphereRadius defines the bounding sphere radius
  103916. * @param allowDuplicate defines if the selection array can contains duplicated entries
  103917. * @returns an array of objects that intersect the sphere
  103918. */
  103919. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  103920. this._selectionContent.reset();
  103921. for (var index = 0; index < this.blocks.length; index++) {
  103922. var block = this.blocks[index];
  103923. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  103924. }
  103925. if (allowDuplicate) {
  103926. this._selectionContent.concat(this.dynamicContent);
  103927. }
  103928. else {
  103929. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103930. }
  103931. return this._selectionContent;
  103932. };
  103933. /**
  103934. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  103935. * @param ray defines the ray to test with
  103936. * @returns array of intersected objects
  103937. */
  103938. Octree.prototype.intersectsRay = function (ray) {
  103939. this._selectionContent.reset();
  103940. for (var index = 0; index < this.blocks.length; index++) {
  103941. var block = this.blocks[index];
  103942. block.intersectsRay(ray, this._selectionContent);
  103943. }
  103944. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  103945. return this._selectionContent;
  103946. };
  103947. /**
  103948. * @hidden
  103949. */
  103950. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  103951. target.blocks = new Array();
  103952. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103953. // Segmenting space
  103954. for (var x = 0; x < 2; x++) {
  103955. for (var y = 0; y < 2; y++) {
  103956. for (var z = 0; z < 2; z++) {
  103957. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  103958. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  103959. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  103960. block.addEntries(entries);
  103961. target.blocks.push(block);
  103962. }
  103963. }
  103964. }
  103965. };
  103966. /**
  103967. * Adds a mesh into the octree block if it intersects the block
  103968. */
  103969. Octree.CreationFuncForMeshes = function (entry, block) {
  103970. var boundingInfo = entry.getBoundingInfo();
  103971. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103972. block.entries.push(entry);
  103973. }
  103974. };
  103975. /**
  103976. * Adds a submesh into the octree block if it intersects the block
  103977. */
  103978. Octree.CreationFuncForSubMeshes = function (entry, block) {
  103979. var boundingInfo = entry.getBoundingInfo();
  103980. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  103981. block.entries.push(entry);
  103982. }
  103983. };
  103984. return Octree;
  103985. }());
  103986. BABYLON.Octree = Octree;
  103987. })(BABYLON || (BABYLON = {}));
  103988. //# sourceMappingURL=babylon.octree.js.map
  103989. var BABYLON;
  103990. (function (BABYLON) {
  103991. /**
  103992. * Class used to store a cell in an octree
  103993. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103994. */
  103995. var OctreeBlock = /** @class */ (function () {
  103996. /**
  103997. * Creates a new block
  103998. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  103999. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  104000. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  104001. * @param depth defines the current depth of this block in the octree
  104002. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  104003. * @param creationFunc defines a callback to call when an element is added to the block
  104004. */
  104005. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  104006. /**
  104007. * Gets the content of the current block
  104008. */
  104009. this.entries = new Array();
  104010. this._boundingVectors = new Array();
  104011. this._capacity = capacity;
  104012. this._depth = depth;
  104013. this._maxDepth = maxDepth;
  104014. this._creationFunc = creationFunc;
  104015. this._minPoint = minPoint;
  104016. this._maxPoint = maxPoint;
  104017. this._boundingVectors.push(minPoint.clone());
  104018. this._boundingVectors.push(maxPoint.clone());
  104019. this._boundingVectors.push(minPoint.clone());
  104020. this._boundingVectors[2].x = maxPoint.x;
  104021. this._boundingVectors.push(minPoint.clone());
  104022. this._boundingVectors[3].y = maxPoint.y;
  104023. this._boundingVectors.push(minPoint.clone());
  104024. this._boundingVectors[4].z = maxPoint.z;
  104025. this._boundingVectors.push(maxPoint.clone());
  104026. this._boundingVectors[5].z = minPoint.z;
  104027. this._boundingVectors.push(maxPoint.clone());
  104028. this._boundingVectors[6].x = minPoint.x;
  104029. this._boundingVectors.push(maxPoint.clone());
  104030. this._boundingVectors[7].y = minPoint.y;
  104031. }
  104032. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  104033. // Property
  104034. /**
  104035. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  104036. */
  104037. get: function () {
  104038. return this._capacity;
  104039. },
  104040. enumerable: true,
  104041. configurable: true
  104042. });
  104043. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  104044. /**
  104045. * Gets the minimum vector (in world space) of the block's bounding box
  104046. */
  104047. get: function () {
  104048. return this._minPoint;
  104049. },
  104050. enumerable: true,
  104051. configurable: true
  104052. });
  104053. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  104054. /**
  104055. * Gets the maximum vector (in world space) of the block's bounding box
  104056. */
  104057. get: function () {
  104058. return this._maxPoint;
  104059. },
  104060. enumerable: true,
  104061. configurable: true
  104062. });
  104063. // Methods
  104064. /**
  104065. * Add a new element to this block
  104066. * @param entry defines the element to add
  104067. */
  104068. OctreeBlock.prototype.addEntry = function (entry) {
  104069. if (this.blocks) {
  104070. for (var index = 0; index < this.blocks.length; index++) {
  104071. var block = this.blocks[index];
  104072. block.addEntry(entry);
  104073. }
  104074. return;
  104075. }
  104076. this._creationFunc(entry, this);
  104077. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  104078. this.createInnerBlocks();
  104079. }
  104080. };
  104081. /**
  104082. * Add an array of elements to this block
  104083. * @param entries defines the array of elements to add
  104084. */
  104085. OctreeBlock.prototype.addEntries = function (entries) {
  104086. for (var index = 0; index < entries.length; index++) {
  104087. var mesh = entries[index];
  104088. this.addEntry(mesh);
  104089. }
  104090. };
  104091. /**
  104092. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  104093. * @param frustumPlanes defines the frustum planes to test
  104094. * @param selection defines the array to store current content if selection is positive
  104095. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104096. */
  104097. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  104098. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  104099. if (this.blocks) {
  104100. for (var index = 0; index < this.blocks.length; index++) {
  104101. var block = this.blocks[index];
  104102. block.select(frustumPlanes, selection, allowDuplicate);
  104103. }
  104104. return;
  104105. }
  104106. if (allowDuplicate) {
  104107. selection.concat(this.entries);
  104108. }
  104109. else {
  104110. selection.concatWithNoDuplicate(this.entries);
  104111. }
  104112. }
  104113. };
  104114. /**
  104115. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  104116. * @param sphereCenter defines the bounding sphere center
  104117. * @param sphereRadius defines the bounding sphere radius
  104118. * @param selection defines the array to store current content if selection is positive
  104119. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104120. */
  104121. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  104122. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  104123. if (this.blocks) {
  104124. for (var index = 0; index < this.blocks.length; index++) {
  104125. var block = this.blocks[index];
  104126. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  104127. }
  104128. return;
  104129. }
  104130. if (allowDuplicate) {
  104131. selection.concat(this.entries);
  104132. }
  104133. else {
  104134. selection.concatWithNoDuplicate(this.entries);
  104135. }
  104136. }
  104137. };
  104138. /**
  104139. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  104140. * @param ray defines the ray to test with
  104141. * @param selection defines the array to store current content if selection is positive
  104142. */
  104143. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  104144. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  104145. if (this.blocks) {
  104146. for (var index = 0; index < this.blocks.length; index++) {
  104147. var block = this.blocks[index];
  104148. block.intersectsRay(ray, selection);
  104149. }
  104150. return;
  104151. }
  104152. selection.concatWithNoDuplicate(this.entries);
  104153. }
  104154. };
  104155. /**
  104156. * Subdivide the content into child blocks (this block will then be empty)
  104157. */
  104158. OctreeBlock.prototype.createInnerBlocks = function () {
  104159. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  104160. };
  104161. return OctreeBlock;
  104162. }());
  104163. BABYLON.OctreeBlock = OctreeBlock;
  104164. })(BABYLON || (BABYLON = {}));
  104165. //# sourceMappingURL=babylon.octreeBlock.js.map
  104166. var BABYLON;
  104167. (function (BABYLON) {
  104168. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  104169. if (maxCapacity === void 0) { maxCapacity = 64; }
  104170. if (maxDepth === void 0) { maxDepth = 2; }
  104171. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104172. if (!component) {
  104173. component = new OctreeSceneComponent(this);
  104174. this._addComponent(component);
  104175. }
  104176. if (!this._selectionOctree) {
  104177. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  104178. }
  104179. var worldExtends = this.getWorldExtends();
  104180. // Update octree
  104181. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  104182. return this._selectionOctree;
  104183. };
  104184. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  104185. get: function () {
  104186. return this._selectionOctree;
  104187. },
  104188. enumerable: true,
  104189. configurable: true
  104190. });
  104191. /**
  104192. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  104193. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  104194. * @param maxCapacity defines the maximum size of each block (64 by default)
  104195. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  104196. * @returns the new octree
  104197. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  104198. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104199. */
  104200. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  104201. if (maxCapacity === void 0) { maxCapacity = 64; }
  104202. if (maxDepth === void 0) { maxDepth = 2; }
  104203. var scene = this.getScene();
  104204. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104205. if (!component) {
  104206. component = new OctreeSceneComponent(scene);
  104207. scene._addComponent(component);
  104208. }
  104209. if (!this._submeshesOctree) {
  104210. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  104211. }
  104212. this.computeWorldMatrix(true);
  104213. var boundingInfo = this.getBoundingInfo();
  104214. // Update octree
  104215. var bbox = boundingInfo.boundingBox;
  104216. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  104217. return this._submeshesOctree;
  104218. };
  104219. /**
  104220. * Defines the octree scene component responsible to manage any octrees
  104221. * in a given scene.
  104222. */
  104223. var OctreeSceneComponent = /** @class */ (function () {
  104224. /**
  104225. * Creates a new instance of the component for the given scene
  104226. * @param scene Defines the scene to register the component in
  104227. */
  104228. function OctreeSceneComponent(scene) {
  104229. /**
  104230. * The component name helpfull to identify the component in the list of scene components.
  104231. */
  104232. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  104233. /**
  104234. * Indicates if the meshes have been checked to make sure they are isEnabled()
  104235. */
  104236. this.checksIsEnabled = true;
  104237. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  104238. this.scene = scene;
  104239. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  104240. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  104241. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  104242. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  104243. }
  104244. /**
  104245. * Registers the component in a given scene
  104246. */
  104247. OctreeSceneComponent.prototype.register = function () {
  104248. var _this = this;
  104249. this.scene.onMeshRemovedObservable.add(function (mesh) {
  104250. var sceneOctree = _this.scene.selectionOctree;
  104251. if (sceneOctree !== undefined && sceneOctree !== null) {
  104252. var index = sceneOctree.dynamicContent.indexOf(mesh);
  104253. if (index !== -1) {
  104254. sceneOctree.dynamicContent.splice(index, 1);
  104255. }
  104256. }
  104257. });
  104258. this.scene.onMeshImportedObservable.add(function (mesh) {
  104259. var sceneOctree = _this.scene.selectionOctree;
  104260. if (sceneOctree !== undefined && sceneOctree !== null) {
  104261. sceneOctree.addMesh(mesh);
  104262. }
  104263. });
  104264. };
  104265. /**
  104266. * Return the list of active meshes
  104267. * @returns the list of active meshes
  104268. */
  104269. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  104270. if (this.scene._selectionOctree) {
  104271. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  104272. return selection;
  104273. }
  104274. return this.scene._getDefaultMeshCandidates();
  104275. };
  104276. /**
  104277. * Return the list of active sub meshes
  104278. * @param mesh The mesh to get the candidates sub meshes from
  104279. * @returns the list of active sub meshes
  104280. */
  104281. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  104282. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  104283. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  104284. return intersections;
  104285. }
  104286. return this.scene._getDefaultSubMeshCandidates(mesh);
  104287. };
  104288. /**
  104289. * Return the list of sub meshes intersecting with a given local ray
  104290. * @param mesh defines the mesh to find the submesh for
  104291. * @param localRay defines the ray in local space
  104292. * @returns the list of intersecting sub meshes
  104293. */
  104294. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  104295. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  104296. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  104297. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  104298. return intersections;
  104299. }
  104300. return this.scene._getDefaultSubMeshCandidates(mesh);
  104301. };
  104302. /**
  104303. * Return the list of sub meshes colliding with a collider
  104304. * @param mesh defines the mesh to find the submesh for
  104305. * @param collider defines the collider to evaluate the collision against
  104306. * @returns the list of colliding sub meshes
  104307. */
  104308. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  104309. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  104310. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  104311. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  104312. return intersections;
  104313. }
  104314. return this.scene._getDefaultSubMeshCandidates(mesh);
  104315. };
  104316. /**
  104317. * Rebuilds the elements related to this component in case of
  104318. * context lost for instance.
  104319. */
  104320. OctreeSceneComponent.prototype.rebuild = function () {
  104321. // Nothing to do here.
  104322. };
  104323. /**
  104324. * Disposes the component and the associated ressources.
  104325. */
  104326. OctreeSceneComponent.prototype.dispose = function () {
  104327. // Nothing to do here.
  104328. };
  104329. return OctreeSceneComponent;
  104330. }());
  104331. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  104332. })(BABYLON || (BABYLON = {}));
  104333. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  104334. var BABYLON;
  104335. (function (BABYLON) {
  104336. /**
  104337. * Postprocess used to generate anaglyphic rendering
  104338. */
  104339. var AnaglyphPostProcess = /** @class */ (function (_super) {
  104340. __extends(AnaglyphPostProcess, _super);
  104341. /**
  104342. * Creates a new AnaglyphPostProcess
  104343. * @param name defines postprocess name
  104344. * @param options defines creation options or target ratio scale
  104345. * @param rigCameras defines cameras using this postprocess
  104346. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  104347. * @param engine defines hosting engine
  104348. * @param reusable defines if the postprocess will be reused multiple times per frame
  104349. */
  104350. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  104351. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  104352. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104353. _this.onApplyObservable.add(function (effect) {
  104354. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  104355. });
  104356. return _this;
  104357. }
  104358. return AnaglyphPostProcess;
  104359. }(BABYLON.PostProcess));
  104360. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  104361. })(BABYLON || (BABYLON = {}));
  104362. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  104363. var BABYLON;
  104364. (function (BABYLON) {
  104365. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  104366. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104367. });
  104368. /**
  104369. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  104370. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104371. */
  104372. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  104373. __extends(AnaglyphArcRotateCamera, _super);
  104374. /**
  104375. * Creates a new AnaglyphArcRotateCamera
  104376. * @param name defines camera name
  104377. * @param alpha defines alpha angle (in radians)
  104378. * @param beta defines beta angle (in radians)
  104379. * @param radius defines radius
  104380. * @param target defines camera target
  104381. * @param interaxialDistance defines distance between each color axis
  104382. * @param scene defines the hosting scene
  104383. */
  104384. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  104385. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104386. _this.interaxialDistance = interaxialDistance;
  104387. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104388. return _this;
  104389. }
  104390. /**
  104391. * Gets camera class name
  104392. * @returns AnaglyphArcRotateCamera
  104393. */
  104394. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  104395. return "AnaglyphArcRotateCamera";
  104396. };
  104397. return AnaglyphArcRotateCamera;
  104398. }(BABYLON.ArcRotateCamera));
  104399. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  104400. })(BABYLON || (BABYLON = {}));
  104401. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  104402. var BABYLON;
  104403. (function (BABYLON) {
  104404. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  104405. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104406. });
  104407. /**
  104408. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  104409. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104410. */
  104411. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  104412. __extends(AnaglyphFreeCamera, _super);
  104413. /**
  104414. * Creates a new AnaglyphFreeCamera
  104415. * @param name defines camera name
  104416. * @param position defines initial position
  104417. * @param interaxialDistance defines distance between each color axis
  104418. * @param scene defines the hosting scene
  104419. */
  104420. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  104421. var _this = _super.call(this, name, position, scene) || this;
  104422. _this.interaxialDistance = interaxialDistance;
  104423. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104424. return _this;
  104425. }
  104426. /**
  104427. * Gets camera class name
  104428. * @returns AnaglyphFreeCamera
  104429. */
  104430. AnaglyphFreeCamera.prototype.getClassName = function () {
  104431. return "AnaglyphFreeCamera";
  104432. };
  104433. return AnaglyphFreeCamera;
  104434. }(BABYLON.FreeCamera));
  104435. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  104436. })(BABYLON || (BABYLON = {}));
  104437. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  104438. var BABYLON;
  104439. (function (BABYLON) {
  104440. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  104441. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104442. });
  104443. /**
  104444. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  104445. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104446. */
  104447. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  104448. __extends(AnaglyphGamepadCamera, _super);
  104449. /**
  104450. * Creates a new AnaglyphGamepadCamera
  104451. * @param name defines camera name
  104452. * @param position defines initial position
  104453. * @param interaxialDistance defines distance between each color axis
  104454. * @param scene defines the hosting scene
  104455. */
  104456. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  104457. var _this = _super.call(this, name, position, scene) || this;
  104458. _this.interaxialDistance = interaxialDistance;
  104459. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104460. return _this;
  104461. }
  104462. /**
  104463. * Gets camera class name
  104464. * @returns AnaglyphGamepadCamera
  104465. */
  104466. AnaglyphGamepadCamera.prototype.getClassName = function () {
  104467. return "AnaglyphGamepadCamera";
  104468. };
  104469. return AnaglyphGamepadCamera;
  104470. }(BABYLON.GamepadCamera));
  104471. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  104472. })(BABYLON || (BABYLON = {}));
  104473. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  104474. var BABYLON;
  104475. (function (BABYLON) {
  104476. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  104477. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104478. });
  104479. /**
  104480. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  104481. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104482. */
  104483. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  104484. __extends(AnaglyphUniversalCamera, _super);
  104485. /**
  104486. * Creates a new AnaglyphUniversalCamera
  104487. * @param name defines camera name
  104488. * @param position defines initial position
  104489. * @param interaxialDistance defines distance between each color axis
  104490. * @param scene defines the hosting scene
  104491. */
  104492. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  104493. var _this = _super.call(this, name, position, scene) || this;
  104494. _this.interaxialDistance = interaxialDistance;
  104495. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104496. return _this;
  104497. }
  104498. /**
  104499. * Gets camera class name
  104500. * @returns AnaglyphUniversalCamera
  104501. */
  104502. AnaglyphUniversalCamera.prototype.getClassName = function () {
  104503. return "AnaglyphUniversalCamera";
  104504. };
  104505. return AnaglyphUniversalCamera;
  104506. }(BABYLON.UniversalCamera));
  104507. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  104508. })(BABYLON || (BABYLON = {}));
  104509. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  104510. var BABYLON;
  104511. (function (BABYLON) {
  104512. /**
  104513. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  104514. */
  104515. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  104516. __extends(StereoscopicInterlacePostProcess, _super);
  104517. /**
  104518. * Initializes a StereoscopicInterlacePostProcess
  104519. * @param name The name of the effect.
  104520. * @param rigCameras The rig cameras to be appled to the post process
  104521. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  104522. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  104523. * @param engine The engine which the post process will be applied. (default: current engine)
  104524. * @param reusable If the post process can be reused on the same frame. (default: false)
  104525. */
  104526. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  104527. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  104528. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104529. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104530. _this.onSizeChangedObservable.add(function () {
  104531. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104532. });
  104533. _this.onApplyObservable.add(function (effect) {
  104534. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  104535. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  104536. });
  104537. return _this;
  104538. }
  104539. return StereoscopicInterlacePostProcess;
  104540. }(BABYLON.PostProcess));
  104541. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  104542. })(BABYLON || (BABYLON = {}));
  104543. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  104544. var BABYLON;
  104545. (function (BABYLON) {
  104546. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  104547. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104548. });
  104549. /**
  104550. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  104551. * @see http://doc.babylonjs.com/features/cameras
  104552. */
  104553. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  104554. __extends(StereoscopicArcRotateCamera, _super);
  104555. /**
  104556. * Creates a new StereoscopicArcRotateCamera
  104557. * @param name defines camera name
  104558. * @param alpha defines alpha angle (in radians)
  104559. * @param beta defines beta angle (in radians)
  104560. * @param radius defines radius
  104561. * @param target defines camera target
  104562. * @param interaxialDistance defines distance between each color axis
  104563. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104564. * @param scene defines the hosting scene
  104565. */
  104566. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  104567. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104568. _this.interaxialDistance = interaxialDistance;
  104569. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104570. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104571. return _this;
  104572. }
  104573. /**
  104574. * Gets camera class name
  104575. * @returns StereoscopicArcRotateCamera
  104576. */
  104577. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  104578. return "StereoscopicArcRotateCamera";
  104579. };
  104580. return StereoscopicArcRotateCamera;
  104581. }(BABYLON.ArcRotateCamera));
  104582. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  104583. })(BABYLON || (BABYLON = {}));
  104584. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  104585. var BABYLON;
  104586. (function (BABYLON) {
  104587. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104588. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104589. });
  104590. /**
  104591. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  104592. * @see http://doc.babylonjs.com/features/cameras
  104593. */
  104594. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  104595. __extends(StereoscopicFreeCamera, _super);
  104596. /**
  104597. * Creates a new StereoscopicFreeCamera
  104598. * @param name defines camera name
  104599. * @param position defines initial position
  104600. * @param interaxialDistance defines distance between each color axis
  104601. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104602. * @param scene defines the hosting scene
  104603. */
  104604. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104605. var _this = _super.call(this, name, position, scene) || this;
  104606. _this.interaxialDistance = interaxialDistance;
  104607. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104608. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104609. return _this;
  104610. }
  104611. /**
  104612. * Gets camera class name
  104613. * @returns StereoscopicFreeCamera
  104614. */
  104615. StereoscopicFreeCamera.prototype.getClassName = function () {
  104616. return "StereoscopicFreeCamera";
  104617. };
  104618. return StereoscopicFreeCamera;
  104619. }(BABYLON.FreeCamera));
  104620. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  104621. })(BABYLON || (BABYLON = {}));
  104622. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  104623. var BABYLON;
  104624. (function (BABYLON) {
  104625. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  104626. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104627. });
  104628. /**
  104629. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  104630. * @see http://doc.babylonjs.com/features/cameras
  104631. */
  104632. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  104633. __extends(StereoscopicGamepadCamera, _super);
  104634. /**
  104635. * Creates a new StereoscopicGamepadCamera
  104636. * @param name defines camera name
  104637. * @param position defines initial position
  104638. * @param interaxialDistance defines distance between each color axis
  104639. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104640. * @param scene defines the hosting scene
  104641. */
  104642. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104643. var _this = _super.call(this, name, position, scene) || this;
  104644. _this.interaxialDistance = interaxialDistance;
  104645. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104646. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104647. return _this;
  104648. }
  104649. /**
  104650. * Gets camera class name
  104651. * @returns StereoscopicGamepadCamera
  104652. */
  104653. StereoscopicGamepadCamera.prototype.getClassName = function () {
  104654. return "StereoscopicGamepadCamera";
  104655. };
  104656. return StereoscopicGamepadCamera;
  104657. }(BABYLON.GamepadCamera));
  104658. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  104659. })(BABYLON || (BABYLON = {}));
  104660. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  104661. var BABYLON;
  104662. (function (BABYLON) {
  104663. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104664. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104665. });
  104666. /**
  104667. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  104668. * @see http://doc.babylonjs.com/features/cameras
  104669. */
  104670. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  104671. __extends(StereoscopicUniversalCamera, _super);
  104672. /**
  104673. * Creates a new StereoscopicUniversalCamera
  104674. * @param name defines camera name
  104675. * @param position defines initial position
  104676. * @param interaxialDistance defines distance between each color axis
  104677. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104678. * @param scene defines the hosting scene
  104679. */
  104680. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104681. var _this = _super.call(this, name, position, scene) || this;
  104682. _this.interaxialDistance = interaxialDistance;
  104683. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104684. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104685. return _this;
  104686. }
  104687. /**
  104688. * Gets camera class name
  104689. * @returns StereoscopicUniversalCamera
  104690. */
  104691. StereoscopicUniversalCamera.prototype.getClassName = function () {
  104692. return "StereoscopicUniversalCamera";
  104693. };
  104694. return StereoscopicUniversalCamera;
  104695. }(BABYLON.UniversalCamera));
  104696. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  104697. })(BABYLON || (BABYLON = {}));
  104698. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  104699. var BABYLON;
  104700. (function (BABYLON) {
  104701. /**
  104702. * VRDistortionCorrectionPostProcess used for mobile VR
  104703. */
  104704. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  104705. __extends(VRDistortionCorrectionPostProcess, _super);
  104706. /**
  104707. * Initializes the VRDistortionCorrectionPostProcess
  104708. * @param name The name of the effect.
  104709. * @param camera The camera to apply the render pass to.
  104710. * @param isRightEye If this is for the right eye distortion
  104711. * @param vrMetrics All the required metrics for the VR camera
  104712. */
  104713. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  104714. var _this = _super.call(this, name, "vrDistortionCorrection", [
  104715. 'LensCenter',
  104716. 'Scale',
  104717. 'ScaleIn',
  104718. 'HmdWarpParam'
  104719. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  104720. _this._isRightEye = isRightEye;
  104721. _this._distortionFactors = vrMetrics.distortionK;
  104722. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  104723. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  104724. _this.adaptScaleToCurrentViewport = true;
  104725. _this.onSizeChangedObservable.add(function () {
  104726. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  104727. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  104728. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  104729. });
  104730. _this.onApplyObservable.add(function (effect) {
  104731. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  104732. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  104733. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  104734. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  104735. });
  104736. return _this;
  104737. }
  104738. return VRDistortionCorrectionPostProcess;
  104739. }(BABYLON.PostProcess));
  104740. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  104741. })(BABYLON || (BABYLON = {}));
  104742. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  104743. var BABYLON;
  104744. (function (BABYLON) {
  104745. /**
  104746. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  104747. * Screen rotation is taken into account.
  104748. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104749. */
  104750. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  104751. /**
  104752. * Instantiates a new input
  104753. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104754. */
  104755. function FreeCameraDeviceOrientationInput() {
  104756. var _this = this;
  104757. this._screenOrientationAngle = 0;
  104758. this._screenQuaternion = new BABYLON.Quaternion();
  104759. this._alpha = 0;
  104760. this._beta = 0;
  104761. this._gamma = 0;
  104762. this._orientationChanged = function () {
  104763. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0));
  104764. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  104765. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  104766. };
  104767. this._deviceOrientation = function (evt) {
  104768. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  104769. _this._beta = evt.beta !== null ? evt.beta : 0;
  104770. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  104771. };
  104772. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  104773. this._orientationChanged();
  104774. }
  104775. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  104776. /**
  104777. * Define the camera controlled by the input.
  104778. */
  104779. get: function () {
  104780. return this._camera;
  104781. },
  104782. set: function (camera) {
  104783. this._camera = camera;
  104784. if (this._camera != null && !this._camera.rotationQuaternion) {
  104785. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  104786. }
  104787. },
  104788. enumerable: true,
  104789. configurable: true
  104790. });
  104791. /**
  104792. * Attach the input controls to a specific dom element to get the input from.
  104793. * @param element Defines the element the controls should be listened from
  104794. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104795. */
  104796. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104797. window.addEventListener("orientationchange", this._orientationChanged);
  104798. window.addEventListener("deviceorientation", this._deviceOrientation);
  104799. //In certain cases, the attach control is called AFTER orientation was changed,
  104800. //So this is needed.
  104801. this._orientationChanged();
  104802. };
  104803. /**
  104804. * Detach the current controls from the specified dom element.
  104805. * @param element Defines the element to stop listening the inputs from
  104806. */
  104807. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  104808. window.removeEventListener("orientationchange", this._orientationChanged);
  104809. window.removeEventListener("deviceorientation", this._deviceOrientation);
  104810. };
  104811. /**
  104812. * Update the current camera state depending on the inputs that have been used this frame.
  104813. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104814. */
  104815. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  104816. //if no device orientation provided, don't update the rotation.
  104817. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  104818. if (!this._alpha) {
  104819. return;
  104820. }
  104821. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  104822. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  104823. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  104824. //Mirror on XY Plane
  104825. this._camera.rotationQuaternion.z *= -1;
  104826. this._camera.rotationQuaternion.w *= -1;
  104827. };
  104828. /**
  104829. * Gets the class name of the current intput.
  104830. * @returns the class name
  104831. */
  104832. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  104833. return "FreeCameraDeviceOrientationInput";
  104834. };
  104835. /**
  104836. * Get the friendly name associated with the input class.
  104837. * @returns the input friendly name
  104838. */
  104839. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  104840. return "deviceOrientation";
  104841. };
  104842. return FreeCameraDeviceOrientationInput;
  104843. }());
  104844. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  104845. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  104846. })(BABYLON || (BABYLON = {}));
  104847. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  104848. var BABYLON;
  104849. (function (BABYLON) {
  104850. /**
  104851. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  104852. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104853. */
  104854. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  104855. /**
  104856. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  104857. */
  104858. function ArcRotateCameraVRDeviceOrientationInput() {
  104859. /**
  104860. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  104861. */
  104862. this.alphaCorrection = 1;
  104863. /**
  104864. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  104865. */
  104866. this.betaCorrection = 1;
  104867. /**
  104868. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  104869. */
  104870. this.gammaCorrection = 1;
  104871. this._alpha = 0;
  104872. this._gamma = 0;
  104873. this._dirty = false;
  104874. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  104875. }
  104876. /**
  104877. * Attach the input controls to a specific dom element to get the input from.
  104878. * @param element Defines the element the controls should be listened from
  104879. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104880. */
  104881. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104882. this.camera.attachControl(element, noPreventDefault);
  104883. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  104884. };
  104885. /** @hidden */
  104886. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  104887. if (evt.alpha !== null) {
  104888. this._alpha = +evt.alpha | 0;
  104889. }
  104890. if (evt.gamma !== null) {
  104891. this._gamma = +evt.gamma | 0;
  104892. }
  104893. this._dirty = true;
  104894. };
  104895. /**
  104896. * Update the current camera state depending on the inputs that have been used this frame.
  104897. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104898. */
  104899. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  104900. if (this._dirty) {
  104901. this._dirty = false;
  104902. if (this._gamma < 0) {
  104903. this._gamma = 180 + this._gamma;
  104904. }
  104905. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  104906. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  104907. }
  104908. };
  104909. /**
  104910. * Detach the current controls from the specified dom element.
  104911. * @param element Defines the element to stop listening the inputs from
  104912. */
  104913. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  104914. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  104915. };
  104916. /**
  104917. * Gets the class name of the current intput.
  104918. * @returns the class name
  104919. */
  104920. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  104921. return "ArcRotateCameraVRDeviceOrientationInput";
  104922. };
  104923. /**
  104924. * Get the friendly name associated with the input class.
  104925. * @returns the input friendly name
  104926. */
  104927. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  104928. return "VRDeviceOrientation";
  104929. };
  104930. return ArcRotateCameraVRDeviceOrientationInput;
  104931. }());
  104932. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  104933. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  104934. })(BABYLON || (BABYLON = {}));
  104935. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  104936. var BABYLON;
  104937. (function (BABYLON) {
  104938. /**
  104939. * This represents all the required metrics to create a VR camera.
  104940. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  104941. */
  104942. var VRCameraMetrics = /** @class */ (function () {
  104943. function VRCameraMetrics() {
  104944. /**
  104945. * Define if the current vr camera should compensate the distortion of the lense or not.
  104946. */
  104947. this.compensateDistortion = true;
  104948. }
  104949. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  104950. /**
  104951. * Gets the rendering aspect ratio based on the provided resolutions.
  104952. */
  104953. get: function () {
  104954. return this.hResolution / (2 * this.vResolution);
  104955. },
  104956. enumerable: true,
  104957. configurable: true
  104958. });
  104959. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  104960. /**
  104961. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  104962. */
  104963. get: function () {
  104964. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  104965. },
  104966. enumerable: true,
  104967. configurable: true
  104968. });
  104969. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  104970. /**
  104971. * @hidden
  104972. */
  104973. get: function () {
  104974. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104975. var h = (4 * meters) / this.hScreenSize;
  104976. return BABYLON.Matrix.Translation(h, 0, 0);
  104977. },
  104978. enumerable: true,
  104979. configurable: true
  104980. });
  104981. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  104982. /**
  104983. * @hidden
  104984. */
  104985. get: function () {
  104986. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  104987. var h = (4 * meters) / this.hScreenSize;
  104988. return BABYLON.Matrix.Translation(-h, 0, 0);
  104989. },
  104990. enumerable: true,
  104991. configurable: true
  104992. });
  104993. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  104994. /**
  104995. * @hidden
  104996. */
  104997. get: function () {
  104998. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  104999. },
  105000. enumerable: true,
  105001. configurable: true
  105002. });
  105003. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  105004. /**
  105005. * @hidden
  105006. */
  105007. get: function () {
  105008. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  105009. },
  105010. enumerable: true,
  105011. configurable: true
  105012. });
  105013. /**
  105014. * Get the default VRMetrics based on the most generic setup.
  105015. * @returns the default vr metrics
  105016. */
  105017. VRCameraMetrics.GetDefault = function () {
  105018. var result = new VRCameraMetrics();
  105019. result.hResolution = 1280;
  105020. result.vResolution = 800;
  105021. result.hScreenSize = 0.149759993;
  105022. result.vScreenSize = 0.0935999975;
  105023. result.vScreenCenter = 0.0467999987;
  105024. result.eyeToScreenDistance = 0.0410000011;
  105025. result.lensSeparationDistance = 0.0635000020;
  105026. result.interpupillaryDistance = 0.0640000030;
  105027. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  105028. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  105029. result.postProcessScaleFactor = 1.714605507808412;
  105030. result.lensCenterOffset = 0.151976421;
  105031. return result;
  105032. };
  105033. return VRCameraMetrics;
  105034. }());
  105035. BABYLON.VRCameraMetrics = VRCameraMetrics;
  105036. })(BABYLON || (BABYLON = {}));
  105037. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  105038. var BABYLON;
  105039. (function (BABYLON) {
  105040. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  105041. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105042. });
  105043. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  105044. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105045. });
  105046. /**
  105047. * This represents a WebVR camera.
  105048. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  105049. * @example http://doc.babylonjs.com/how_to/webvr_camera
  105050. */
  105051. var WebVRFreeCamera = /** @class */ (function (_super) {
  105052. __extends(WebVRFreeCamera, _super);
  105053. /**
  105054. * Instantiates a WebVRFreeCamera.
  105055. * @param name The name of the WebVRFreeCamera
  105056. * @param position The starting anchor position for the camera
  105057. * @param scene The scene the camera belongs to
  105058. * @param webVROptions a set of customizable options for the webVRCamera
  105059. */
  105060. function WebVRFreeCamera(name, position, scene, webVROptions) {
  105061. if (webVROptions === void 0) { webVROptions = {}; }
  105062. var _this = _super.call(this, name, position, scene) || this;
  105063. _this.webVROptions = webVROptions;
  105064. /**
  105065. * @hidden
  105066. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  105067. */
  105068. _this._vrDevice = null;
  105069. /**
  105070. * The rawPose of the vrDevice.
  105071. */
  105072. _this.rawPose = null;
  105073. _this._specsVersion = "1.1";
  105074. _this._attached = false;
  105075. _this._descendants = [];
  105076. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  105077. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  105078. /** @hidden */
  105079. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  105080. _this._standingMatrix = null;
  105081. /**
  105082. * Represents device position in babylon space.
  105083. */
  105084. _this.devicePosition = BABYLON.Vector3.Zero();
  105085. /**
  105086. * Represents device rotation in babylon space.
  105087. */
  105088. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  105089. /**
  105090. * The scale of the device to be used when translating from device space to babylon space.
  105091. */
  105092. _this.deviceScaleFactor = 1;
  105093. _this._deviceToWorld = BABYLON.Matrix.Identity();
  105094. _this._worldToDevice = BABYLON.Matrix.Identity();
  105095. /**
  105096. * References to the webVR controllers for the vrDevice.
  105097. */
  105098. _this.controllers = [];
  105099. /**
  105100. * Emits an event when a controller is attached.
  105101. */
  105102. _this.onControllersAttachedObservable = new BABYLON.Observable();
  105103. /**
  105104. * Emits an event when a controller's mesh has been loaded;
  105105. */
  105106. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105107. /**
  105108. * Emits an event when the HMD's pose has been updated.
  105109. */
  105110. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  105111. _this._poseSet = false;
  105112. /**
  105113. * If the rig cameras be used as parent instead of this camera.
  105114. */
  105115. _this.rigParenting = true;
  105116. _this._defaultHeight = undefined;
  105117. _this._htmlElementAttached = null;
  105118. _this._detachIfAttached = function () {
  105119. var vrDisplay = _this.getEngine().getVRDevice();
  105120. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  105121. _this.detachControl(_this._htmlElementAttached);
  105122. }
  105123. };
  105124. _this._workingVector = BABYLON.Vector3.Zero();
  105125. _this._oneVector = BABYLON.Vector3.One();
  105126. _this._workingMatrix = BABYLON.Matrix.Identity();
  105127. _this._tmpMatrix = new BABYLON.Matrix();
  105128. _this._cache.position = BABYLON.Vector3.Zero();
  105129. if (webVROptions.defaultHeight) {
  105130. _this._defaultHeight = webVROptions.defaultHeight;
  105131. _this.position.y = _this._defaultHeight;
  105132. }
  105133. _this.minZ = 0.1;
  105134. //legacy support - the compensation boolean was removed.
  105135. if (arguments.length === 5) {
  105136. _this.webVROptions = arguments[4];
  105137. }
  105138. // default webVR options
  105139. if (_this.webVROptions.trackPosition == undefined) {
  105140. _this.webVROptions.trackPosition = true;
  105141. }
  105142. if (_this.webVROptions.controllerMeshes == undefined) {
  105143. _this.webVROptions.controllerMeshes = true;
  105144. }
  105145. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  105146. _this.webVROptions.defaultLightingOnControllers = true;
  105147. }
  105148. _this.rotationQuaternion = new BABYLON.Quaternion();
  105149. if (_this.webVROptions && _this.webVROptions.positionScale) {
  105150. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  105151. }
  105152. //enable VR
  105153. var engine = _this.getEngine();
  105154. _this._onVREnabled = function (success) { if (success) {
  105155. _this.initControllers();
  105156. } };
  105157. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  105158. engine.initWebVR().add(function (event) {
  105159. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  105160. return;
  105161. }
  105162. _this._vrDevice = event.vrDisplay;
  105163. //reset the rig parameters.
  105164. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  105165. if (_this._attached) {
  105166. _this.getEngine().enableVR();
  105167. }
  105168. });
  105169. if (typeof (VRFrameData) !== "undefined") {
  105170. _this._frameData = new VRFrameData();
  105171. }
  105172. /**
  105173. * The idea behind the following lines:
  105174. * objects that have the camera as parent should actually have the rig cameras as a parent.
  105175. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  105176. * the second will not show it correctly.
  105177. *
  105178. * To solve this - each object that has the camera as parent will be added to a protected array.
  105179. * When the rig camera renders, it will take this array and set all of those to be its children.
  105180. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  105181. * Amazing!
  105182. */
  105183. scene.onBeforeCameraRenderObservable.add(function (camera) {
  105184. if (camera.parent === _this && _this.rigParenting) {
  105185. _this._descendants = _this.getDescendants(true, function (n) {
  105186. // don't take the cameras or the controllers!
  105187. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  105188. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  105189. return !isController && !isRigCamera;
  105190. });
  105191. _this._descendants.forEach(function (node) {
  105192. node.parent = camera;
  105193. });
  105194. }
  105195. });
  105196. scene.onAfterCameraRenderObservable.add(function (camera) {
  105197. if (camera.parent === _this && _this.rigParenting) {
  105198. _this._descendants.forEach(function (node) {
  105199. node.parent = _this;
  105200. });
  105201. }
  105202. });
  105203. return _this;
  105204. }
  105205. /**
  105206. * Gets the device distance from the ground in meters.
  105207. * @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.
  105208. */
  105209. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  105210. if (this._standingMatrix) {
  105211. // Add standing matrix offset to get real offset from ground in room
  105212. this._standingMatrix.getTranslationToRef(this._workingVector);
  105213. return this._deviceRoomPosition.y + this._workingVector.y;
  105214. }
  105215. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  105216. return this._defaultHeight || 0;
  105217. };
  105218. /**
  105219. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105220. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  105221. */
  105222. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  105223. var _this = this;
  105224. if (callback === void 0) { callback = function (bool) { }; }
  105225. // Use standing matrix if available
  105226. this.getEngine().initWebVRAsync().then(function (result) {
  105227. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  105228. callback(false);
  105229. }
  105230. else {
  105231. _this._standingMatrix = new BABYLON.Matrix();
  105232. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  105233. if (!_this.getScene().useRightHandedSystem) {
  105234. [2, 6, 8, 9, 14].forEach(function (num) {
  105235. if (_this._standingMatrix) {
  105236. _this._standingMatrix.m[num] *= -1;
  105237. }
  105238. });
  105239. }
  105240. callback(true);
  105241. }
  105242. });
  105243. };
  105244. /**
  105245. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105246. * @returns A promise with a boolean set to if the standing matrix is supported.
  105247. */
  105248. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  105249. var _this = this;
  105250. return new Promise(function (res, rej) {
  105251. _this.useStandingMatrix(function (supported) {
  105252. res(supported);
  105253. });
  105254. });
  105255. };
  105256. /**
  105257. * Disposes the camera
  105258. */
  105259. WebVRFreeCamera.prototype.dispose = function () {
  105260. this._detachIfAttached();
  105261. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  105262. if (this._updateCacheWhenTrackingDisabledObserver) {
  105263. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  105264. }
  105265. _super.prototype.dispose.call(this);
  105266. };
  105267. /**
  105268. * Gets a vrController by name.
  105269. * @param name The name of the controller to retreive
  105270. * @returns the controller matching the name specified or null if not found
  105271. */
  105272. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  105273. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  105274. var gp = _a[_i];
  105275. if (gp.hand === name) {
  105276. return gp;
  105277. }
  105278. }
  105279. return null;
  105280. };
  105281. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  105282. /**
  105283. * The controller corrisponding to the users left hand.
  105284. */
  105285. get: function () {
  105286. if (!this._leftController) {
  105287. this._leftController = this.getControllerByName("left");
  105288. }
  105289. return this._leftController;
  105290. },
  105291. enumerable: true,
  105292. configurable: true
  105293. });
  105294. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  105295. /**
  105296. * The controller corrisponding to the users right hand.
  105297. */
  105298. get: function () {
  105299. if (!this._rightController) {
  105300. this._rightController = this.getControllerByName("right");
  105301. }
  105302. return this._rightController;
  105303. },
  105304. enumerable: true,
  105305. configurable: true
  105306. });
  105307. /**
  105308. * Casts a ray forward from the vrCamera's gaze.
  105309. * @param length Length of the ray (default: 100)
  105310. * @returns the ray corrisponding to the gaze
  105311. */
  105312. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  105313. if (length === void 0) { length = 100; }
  105314. if (this.leftCamera) {
  105315. // Use left eye to avoid computation to compute center on every call
  105316. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  105317. }
  105318. else {
  105319. return _super.prototype.getForwardRay.call(this, length);
  105320. }
  105321. };
  105322. /**
  105323. * @hidden
  105324. * Updates the camera based on device's frame data
  105325. */
  105326. WebVRFreeCamera.prototype._checkInputs = function () {
  105327. if (this._vrDevice && this._vrDevice.isPresenting) {
  105328. this._vrDevice.getFrameData(this._frameData);
  105329. this.updateFromDevice(this._frameData.pose);
  105330. }
  105331. _super.prototype._checkInputs.call(this);
  105332. };
  105333. /**
  105334. * Updates the poseControlled values based on the input device pose.
  105335. * @param poseData Pose coming from the device
  105336. */
  105337. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  105338. if (poseData && poseData.orientation) {
  105339. this.rawPose = poseData;
  105340. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  105341. if (this.getScene().useRightHandedSystem) {
  105342. this._deviceRoomRotationQuaternion.z *= -1;
  105343. this._deviceRoomRotationQuaternion.w *= -1;
  105344. }
  105345. if (this.webVROptions.trackPosition && this.rawPose.position) {
  105346. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  105347. if (this.getScene().useRightHandedSystem) {
  105348. this._deviceRoomPosition.z *= -1;
  105349. }
  105350. }
  105351. this._poseSet = true;
  105352. }
  105353. };
  105354. /**
  105355. * WebVR's attach control will start broadcasting frames to the device.
  105356. * Note that in certain browsers (chrome for example) this function must be called
  105357. * within a user-interaction callback. Example:
  105358. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  105359. *
  105360. * @param element html element to attach the vrDevice to
  105361. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  105362. */
  105363. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  105364. _super.prototype.attachControl.call(this, element, noPreventDefault);
  105365. this._attached = true;
  105366. this._htmlElementAttached = element;
  105367. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  105368. if (this._vrDevice) {
  105369. this.getEngine().enableVR();
  105370. }
  105371. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105372. };
  105373. /**
  105374. * Detaches the camera from the html element and disables VR
  105375. *
  105376. * @param element html element to detach from
  105377. */
  105378. WebVRFreeCamera.prototype.detachControl = function (element) {
  105379. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  105380. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  105381. _super.prototype.detachControl.call(this, element);
  105382. this._attached = false;
  105383. this.getEngine().disableVR();
  105384. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105385. };
  105386. /**
  105387. * @returns the name of this class
  105388. */
  105389. WebVRFreeCamera.prototype.getClassName = function () {
  105390. return "WebVRFreeCamera";
  105391. };
  105392. /**
  105393. * Calls resetPose on the vrDisplay
  105394. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  105395. */
  105396. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  105397. //uses the vrDisplay's "resetPose()".
  105398. //pitch and roll won't be affected.
  105399. this._vrDevice.resetPose();
  105400. };
  105401. /**
  105402. * @hidden
  105403. * Updates the rig cameras (left and right eye)
  105404. */
  105405. WebVRFreeCamera.prototype._updateRigCameras = function () {
  105406. var camLeft = this._rigCameras[0];
  105407. var camRight = this._rigCameras[1];
  105408. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105409. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105410. camLeft.position.copyFrom(this._deviceRoomPosition);
  105411. camRight.position.copyFrom(this._deviceRoomPosition);
  105412. };
  105413. // Remove translation from 6dof headset if trackposition is set to false
  105414. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  105415. if (isViewMatrix === void 0) { isViewMatrix = false; }
  105416. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  105417. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  105418. if (!isViewMatrix) {
  105419. this._tmpMatrix.invert();
  105420. }
  105421. this._tmpMatrix.multiplyToRef(matrix, matrix);
  105422. }
  105423. };
  105424. /**
  105425. * @hidden
  105426. * Updates the cached values of the camera
  105427. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  105428. */
  105429. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  105430. var _this = this;
  105431. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  105432. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  105433. if (!this.updateCacheCalled) {
  105434. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  105435. this.updateCacheCalled = true;
  105436. this.update();
  105437. }
  105438. // Set working vector to the device position in room space rotated by the new rotation
  105439. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  105440. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  105441. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  105442. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  105443. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  105444. // Add translation from anchor position
  105445. this._deviceToWorld.getTranslationToRef(this._workingVector);
  105446. this._workingVector.addInPlace(this.position);
  105447. this._workingVector.subtractInPlace(this._cache.position);
  105448. this._deviceToWorld.setTranslation(this._workingVector);
  105449. // Set an inverted matrix to be used when updating the camera
  105450. this._deviceToWorld.invertToRef(this._worldToDevice);
  105451. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  105452. this.controllers.forEach(function (controller) {
  105453. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  105454. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  105455. controller.update();
  105456. });
  105457. }
  105458. if (!ignoreParentClass) {
  105459. _super.prototype._updateCache.call(this);
  105460. }
  105461. this.updateCacheCalled = false;
  105462. };
  105463. /**
  105464. * @hidden
  105465. * Get current device position in babylon world
  105466. */
  105467. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  105468. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  105469. };
  105470. /**
  105471. * Updates the current device position and rotation in the babylon world
  105472. */
  105473. WebVRFreeCamera.prototype.update = function () {
  105474. this._computeDevicePosition();
  105475. // Get current device rotation in babylon world
  105476. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  105477. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  105478. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  105479. if (this._poseSet) {
  105480. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  105481. }
  105482. _super.prototype.update.call(this);
  105483. };
  105484. /**
  105485. * @hidden
  105486. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  105487. * @returns an identity matrix
  105488. */
  105489. WebVRFreeCamera.prototype._getViewMatrix = function () {
  105490. return BABYLON.Matrix.Identity();
  105491. };
  105492. /**
  105493. * This function is called by the two RIG cameras.
  105494. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  105495. */
  105496. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  105497. var _this = this;
  105498. // Update the parent camera prior to using a child camera to avoid desynchronization
  105499. var parentCamera = this._cameraRigParams["parentCamera"];
  105500. parentCamera._updateCache();
  105501. //WebVR 1.1
  105502. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  105503. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  105504. if (!this.getScene().useRightHandedSystem) {
  105505. [2, 6, 8, 9, 14].forEach(function (num) {
  105506. _this._webvrViewMatrix.m[num] *= -1;
  105507. });
  105508. }
  105509. // update the camera rotation matrix
  105510. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  105511. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  105512. // Computing target and final matrix
  105513. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  105514. // should the view matrix be updated with scale and position offset?
  105515. if (parentCamera.deviceScaleFactor !== 1) {
  105516. this._webvrViewMatrix.invert();
  105517. // scale the position, if set
  105518. if (parentCamera.deviceScaleFactor) {
  105519. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  105520. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  105521. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  105522. }
  105523. this._webvrViewMatrix.invert();
  105524. }
  105525. // Remove translation from 6dof headset if trackposition is set to false
  105526. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  105527. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  105528. // Compute global position
  105529. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  105530. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  105531. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  105532. this._workingMatrix.getTranslationToRef(this._globalPosition);
  105533. this._markSyncedWithParent();
  105534. return this._webvrViewMatrix;
  105535. };
  105536. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  105537. var _this = this;
  105538. var parentCamera = this.parent;
  105539. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  105540. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  105541. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  105542. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  105543. //babylon compatible matrix
  105544. if (!this.getScene().useRightHandedSystem) {
  105545. [8, 9, 10, 11].forEach(function (num) {
  105546. _this._projectionMatrix.m[num] *= -1;
  105547. });
  105548. }
  105549. return this._projectionMatrix;
  105550. };
  105551. /**
  105552. * Initializes the controllers and their meshes
  105553. */
  105554. WebVRFreeCamera.prototype.initControllers = function () {
  105555. var _this = this;
  105556. this.controllers = [];
  105557. var manager = this.getScene().gamepadManager;
  105558. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  105559. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105560. var webVrController = gamepad;
  105561. if (webVrController.defaultModel) {
  105562. webVrController.defaultModel.setEnabled(false);
  105563. }
  105564. if (webVrController.hand === "right") {
  105565. _this._rightController = null;
  105566. }
  105567. if (webVrController.hand === "left") {
  105568. _this._leftController = null;
  105569. }
  105570. var controllerIndex = _this.controllers.indexOf(webVrController);
  105571. if (controllerIndex !== -1) {
  105572. _this.controllers.splice(controllerIndex, 1);
  105573. }
  105574. }
  105575. });
  105576. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  105577. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105578. var webVrController_1 = gamepad;
  105579. if (!_this.webVROptions.trackPosition) {
  105580. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  105581. // Cache must be updated before rendering controllers to avoid them being one frame behind
  105582. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  105583. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  105584. _this._updateCache();
  105585. });
  105586. }
  105587. }
  105588. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  105589. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  105590. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  105591. if (_this.webVROptions.controllerMeshes) {
  105592. if (webVrController_1.defaultModel) {
  105593. webVrController_1.defaultModel.setEnabled(true);
  105594. }
  105595. else {
  105596. // Load the meshes
  105597. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  105598. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  105599. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  105600. if (_this.webVROptions.defaultLightingOnControllers) {
  105601. if (!_this._lightOnControllers) {
  105602. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  105603. }
  105604. var activateLightOnSubMeshes_1 = function (mesh, light) {
  105605. var children = mesh.getChildren();
  105606. if (children && children.length !== 0) {
  105607. children.forEach(function (mesh) {
  105608. light.includedOnlyMeshes.push(mesh);
  105609. activateLightOnSubMeshes_1(mesh, light);
  105610. });
  105611. }
  105612. };
  105613. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  105614. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  105615. }
  105616. });
  105617. }
  105618. }
  105619. webVrController_1.attachToPoseControlledCamera(_this);
  105620. // since this is async - sanity check. Is the controller already stored?
  105621. if (_this.controllers.indexOf(webVrController_1) === -1) {
  105622. //add to the controllers array
  105623. _this.controllers.push(webVrController_1);
  105624. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  105625. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  105626. // So we're overriding setting left & right manually to be sure
  105627. var firstViveWandDetected = false;
  105628. for (var i = 0; i < _this.controllers.length; i++) {
  105629. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105630. if (!firstViveWandDetected) {
  105631. firstViveWandDetected = true;
  105632. _this.controllers[i].hand = "left";
  105633. }
  105634. else {
  105635. _this.controllers[i].hand = "right";
  105636. }
  105637. }
  105638. }
  105639. //did we find enough controllers? Great! let the developer know.
  105640. if (_this.controllers.length >= 2) {
  105641. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  105642. }
  105643. }
  105644. }
  105645. });
  105646. };
  105647. return WebVRFreeCamera;
  105648. }(BABYLON.FreeCamera));
  105649. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  105650. })(BABYLON || (BABYLON = {}));
  105651. //# sourceMappingURL=babylon.webVRCamera.js.map
  105652. var BABYLON;
  105653. (function (BABYLON) {
  105654. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  105655. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  105656. });
  105657. // We're mainly based on the logic defined into the FreeCamera code
  105658. /**
  105659. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  105660. * being tilted forward or back and left or right.
  105661. */
  105662. var DeviceOrientationCamera = /** @class */ (function (_super) {
  105663. __extends(DeviceOrientationCamera, _super);
  105664. /**
  105665. * Creates a new device orientation camera
  105666. * @param name The name of the camera
  105667. * @param position The start position camera
  105668. * @param scene The scene the camera belongs to
  105669. */
  105670. function DeviceOrientationCamera(name, position, scene) {
  105671. var _this = _super.call(this, name, position, scene) || this;
  105672. _this._quaternionCache = new BABYLON.Quaternion();
  105673. _this.inputs.addDeviceOrientation();
  105674. return _this;
  105675. }
  105676. /**
  105677. * Gets the current instance class name ("DeviceOrientationCamera").
  105678. * This helps avoiding instanceof at run time.
  105679. * @returns the class name
  105680. */
  105681. DeviceOrientationCamera.prototype.getClassName = function () {
  105682. return "DeviceOrientationCamera";
  105683. };
  105684. /**
  105685. * @hidden
  105686. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  105687. */
  105688. DeviceOrientationCamera.prototype._checkInputs = function () {
  105689. _super.prototype._checkInputs.call(this);
  105690. this._quaternionCache.copyFrom(this.rotationQuaternion);
  105691. if (this._initialQuaternion) {
  105692. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105693. }
  105694. };
  105695. /**
  105696. * Reset the camera to its default orientation on the specified axis only.
  105697. * @param axis The axis to reset
  105698. */
  105699. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  105700. var _this = this;
  105701. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  105702. //can only work if this camera has a rotation quaternion already.
  105703. if (!this.rotationQuaternion) {
  105704. return;
  105705. }
  105706. if (!this._initialQuaternion) {
  105707. this._initialQuaternion = new BABYLON.Quaternion();
  105708. }
  105709. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  105710. ['x', 'y', 'z'].forEach(function (axisName) {
  105711. if (!axis[axisName]) {
  105712. _this._initialQuaternion[axisName] = 0;
  105713. }
  105714. else {
  105715. _this._initialQuaternion[axisName] *= -1;
  105716. }
  105717. });
  105718. this._initialQuaternion.normalize();
  105719. //force rotation update
  105720. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105721. };
  105722. return DeviceOrientationCamera;
  105723. }(BABYLON.FreeCamera));
  105724. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  105725. })(BABYLON || (BABYLON = {}));
  105726. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  105727. var BABYLON;
  105728. (function (BABYLON) {
  105729. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105730. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105731. });
  105732. /**
  105733. * Camera used to simulate VR rendering (based on FreeCamera)
  105734. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105735. */
  105736. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  105737. __extends(VRDeviceOrientationFreeCamera, _super);
  105738. /**
  105739. * Creates a new VRDeviceOrientationFreeCamera
  105740. * @param name defines camera name
  105741. * @param position defines the start position of the camera
  105742. * @param scene defines the scene the camera belongs to
  105743. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105744. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105745. */
  105746. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105747. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105748. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105749. var _this = _super.call(this, name, position, scene) || this;
  105750. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105751. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105752. return _this;
  105753. }
  105754. /**
  105755. * Gets camera class name
  105756. * @returns VRDeviceOrientationFreeCamera
  105757. */
  105758. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  105759. return "VRDeviceOrientationFreeCamera";
  105760. };
  105761. return VRDeviceOrientationFreeCamera;
  105762. }(BABYLON.DeviceOrientationCamera));
  105763. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  105764. })(BABYLON || (BABYLON = {}));
  105765. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  105766. var BABYLON;
  105767. (function (BABYLON) {
  105768. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105769. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  105770. });
  105771. /**
  105772. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  105773. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105774. */
  105775. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  105776. __extends(VRDeviceOrientationArcRotateCamera, _super);
  105777. /**
  105778. * Creates a new VRDeviceOrientationArcRotateCamera
  105779. * @param name defines camera name
  105780. * @param alpha defines the camera rotation along the logitudinal axis
  105781. * @param beta defines the camera rotation along the latitudinal axis
  105782. * @param radius defines the camera distance from its target
  105783. * @param target defines the camera target
  105784. * @param scene defines the scene the camera belongs to
  105785. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105786. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105787. */
  105788. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  105789. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105790. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105791. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  105792. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105793. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105794. _this.inputs.addVRDeviceOrientation();
  105795. return _this;
  105796. }
  105797. /**
  105798. * Gets camera class name
  105799. * @returns VRDeviceOrientationArcRotateCamera
  105800. */
  105801. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  105802. return "VRDeviceOrientationArcRotateCamera";
  105803. };
  105804. return VRDeviceOrientationArcRotateCamera;
  105805. }(BABYLON.ArcRotateCamera));
  105806. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  105807. })(BABYLON || (BABYLON = {}));
  105808. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  105809. var BABYLON;
  105810. (function (BABYLON) {
  105811. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  105812. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  105813. });
  105814. /**
  105815. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  105816. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105817. */
  105818. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  105819. __extends(VRDeviceOrientationGamepadCamera, _super);
  105820. /**
  105821. * Creates a new VRDeviceOrientationGamepadCamera
  105822. * @param name defines camera name
  105823. * @param position defines the start position of the camera
  105824. * @param scene defines the scene the camera belongs to
  105825. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105826. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105827. */
  105828. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105829. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105830. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105831. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  105832. _this.inputs.addGamepad();
  105833. return _this;
  105834. }
  105835. /**
  105836. * Gets camera class name
  105837. * @returns VRDeviceOrientationGamepadCamera
  105838. */
  105839. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  105840. return "VRDeviceOrientationGamepadCamera";
  105841. };
  105842. return VRDeviceOrientationGamepadCamera;
  105843. }(BABYLON.VRDeviceOrientationFreeCamera));
  105844. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  105845. })(BABYLON || (BABYLON = {}));
  105846. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  105847. var BABYLON;
  105848. (function (BABYLON) {
  105849. var VRExperienceHelperGazer = /** @class */ (function () {
  105850. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  105851. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  105852. this.scene = scene;
  105853. /** @hidden */
  105854. this._pointerDownOnMeshAsked = false;
  105855. /** @hidden */
  105856. this._isActionableMesh = false;
  105857. /** @hidden */
  105858. this._teleportationRequestInitiated = false;
  105859. /** @hidden */
  105860. this._teleportationBackRequestInitiated = false;
  105861. /** @hidden */
  105862. this._rotationRightAsked = false;
  105863. /** @hidden */
  105864. this._rotationLeftAsked = false;
  105865. /** @hidden */
  105866. this._dpadPressed = true;
  105867. /** @hidden */
  105868. this._activePointer = false;
  105869. this._id = VRExperienceHelperGazer._idCounter++;
  105870. // Gaze tracker
  105871. if (!gazeTrackerToClone) {
  105872. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  105873. this._gazeTracker.bakeCurrentTransformIntoVertices();
  105874. this._gazeTracker.isPickable = false;
  105875. this._gazeTracker.isVisible = false;
  105876. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  105877. targetMat.specularColor = BABYLON.Color3.Black();
  105878. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105879. targetMat.backFaceCulling = false;
  105880. this._gazeTracker.material = targetMat;
  105881. }
  105882. else {
  105883. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  105884. }
  105885. }
  105886. /** @hidden */
  105887. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  105888. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  105889. };
  105890. /** @hidden */
  105891. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  105892. this._pointerDownOnMeshAsked = true;
  105893. if (this._currentHit) {
  105894. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  105895. }
  105896. };
  105897. /** @hidden */
  105898. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  105899. if (this._currentHit) {
  105900. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  105901. }
  105902. this._pointerDownOnMeshAsked = false;
  105903. };
  105904. /** @hidden */
  105905. VRExperienceHelperGazer.prototype._activatePointer = function () {
  105906. this._activePointer = true;
  105907. };
  105908. /** @hidden */
  105909. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  105910. this._activePointer = false;
  105911. };
  105912. /** @hidden */
  105913. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  105914. if (distance === void 0) { distance = 100; }
  105915. };
  105916. VRExperienceHelperGazer.prototype.dispose = function () {
  105917. this._interactionsEnabled = false;
  105918. this._teleportationEnabled = false;
  105919. if (this._gazeTracker) {
  105920. this._gazeTracker.dispose();
  105921. }
  105922. };
  105923. VRExperienceHelperGazer._idCounter = 0;
  105924. return VRExperienceHelperGazer;
  105925. }());
  105926. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  105927. __extends(VRExperienceHelperControllerGazer, _super);
  105928. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  105929. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  105930. _this.webVRController = webVRController;
  105931. // Laser pointer
  105932. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  105933. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  105934. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105935. laserPointerMaterial.alpha = 0.6;
  105936. _this._laserPointer.material = laserPointerMaterial;
  105937. _this._laserPointer.rotation.x = Math.PI / 2;
  105938. _this._laserPointer.position.z = -0.5;
  105939. _this._laserPointer.isVisible = false;
  105940. _this._laserPointer.isPickable = false;
  105941. if (!webVRController.mesh) {
  105942. // Create an empty mesh that is used prior to loading the high quality model
  105943. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  105944. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  105945. preloadPointerPose.rotation.x = -0.7;
  105946. preloadMesh.addChild(preloadPointerPose);
  105947. webVRController.attachToMesh(preloadMesh);
  105948. }
  105949. _this._setLaserPointerParent(webVRController.mesh);
  105950. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  105951. _this._setLaserPointerParent(mesh);
  105952. });
  105953. return _this;
  105954. }
  105955. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  105956. return this.webVRController.getForwardRay(length);
  105957. };
  105958. /** @hidden */
  105959. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  105960. _super.prototype._activatePointer.call(this);
  105961. this._laserPointer.isVisible = true;
  105962. };
  105963. /** @hidden */
  105964. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  105965. _super.prototype._deactivatePointer.call(this);
  105966. this._laserPointer.isVisible = false;
  105967. };
  105968. /** @hidden */
  105969. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  105970. this._laserPointer.material.emissiveColor = color;
  105971. };
  105972. /** @hidden */
  105973. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  105974. var makeNotPick = function (root) {
  105975. root.isPickable = false;
  105976. root.getChildMeshes().forEach(function (c) {
  105977. makeNotPick(c);
  105978. });
  105979. };
  105980. makeNotPick(mesh);
  105981. var childMeshes = mesh.getChildMeshes();
  105982. this.webVRController._pointingPoseNode = null;
  105983. for (var i = 0; i < childMeshes.length; i++) {
  105984. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  105985. mesh = childMeshes[i];
  105986. this.webVRController._pointingPoseNode = mesh;
  105987. break;
  105988. }
  105989. }
  105990. this._laserPointer.parent = mesh;
  105991. };
  105992. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  105993. if (distance === void 0) { distance = 100; }
  105994. this._laserPointer.scaling.y = distance;
  105995. this._laserPointer.position.z = -distance / 2;
  105996. };
  105997. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  105998. _super.prototype.dispose.call(this);
  105999. this._laserPointer.dispose();
  106000. if (this._meshAttachedObserver) {
  106001. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  106002. }
  106003. };
  106004. return VRExperienceHelperControllerGazer;
  106005. }(VRExperienceHelperGazer));
  106006. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  106007. __extends(VRExperienceHelperCameraGazer, _super);
  106008. function VRExperienceHelperCameraGazer(getCamera, scene) {
  106009. var _this = _super.call(this, scene) || this;
  106010. _this.getCamera = getCamera;
  106011. return _this;
  106012. }
  106013. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  106014. var camera = this.getCamera();
  106015. if (camera) {
  106016. return camera.getForwardRay(length);
  106017. }
  106018. else {
  106019. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  106020. }
  106021. };
  106022. return VRExperienceHelperCameraGazer;
  106023. }(VRExperienceHelperGazer));
  106024. /**
  106025. * Helps to quickly add VR support to an existing scene.
  106026. * See http://doc.babylonjs.com/how_to/webvr_helper
  106027. */
  106028. var VRExperienceHelper = /** @class */ (function () {
  106029. /**
  106030. * Instantiates a VRExperienceHelper.
  106031. * Helps to quickly add VR support to an existing scene.
  106032. * @param scene The scene the VRExperienceHelper belongs to.
  106033. * @param webVROptions Options to modify the vr experience helper's behavior.
  106034. */
  106035. function VRExperienceHelper(scene,
  106036. /** Options to modify the vr experience helper's behavior. */
  106037. webVROptions) {
  106038. if (webVROptions === void 0) { webVROptions = {}; }
  106039. var _this = this;
  106040. this.webVROptions = webVROptions;
  106041. // Can the system support WebVR, even if a headset isn't plugged in?
  106042. this._webVRsupported = false;
  106043. // If WebVR is supported, is a headset plugged in and are we ready to present?
  106044. this._webVRready = false;
  106045. // Are we waiting for the requestPresent callback to complete?
  106046. this._webVRrequesting = false;
  106047. // Are we presenting to the headset right now? (this is the vrDevice state)
  106048. this._webVRpresenting = false;
  106049. // Are we presenting in the fullscreen fallback?
  106050. this._fullscreenVRpresenting = false;
  106051. /**
  106052. * Observable raised when entering VR.
  106053. */
  106054. this.onEnteringVRObservable = new BABYLON.Observable();
  106055. /**
  106056. * Observable raised when exiting VR.
  106057. */
  106058. this.onExitingVRObservable = new BABYLON.Observable();
  106059. /**
  106060. * Observable raised when controller mesh is loaded.
  106061. */
  106062. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  106063. this._useCustomVRButton = false;
  106064. this._teleportationRequested = false;
  106065. this._teleportActive = false;
  106066. this._floorMeshesCollection = [];
  106067. this._rotationAllowed = true;
  106068. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  106069. this._isDefaultTeleportationTarget = true;
  106070. this._teleportationFillColor = "#444444";
  106071. this._teleportationBorderColor = "#FFFFFF";
  106072. this._rotationAngle = 0;
  106073. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  106074. this._padSensibilityUp = 0.65;
  106075. this._padSensibilityDown = 0.35;
  106076. this._leftController = null;
  106077. this._rightController = null;
  106078. /**
  106079. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  106080. */
  106081. this.onNewMeshSelected = new BABYLON.Observable();
  106082. /**
  106083. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  106084. */
  106085. this.onNewMeshPicked = new BABYLON.Observable();
  106086. /**
  106087. * Observable raised before camera teleportation
  106088. */
  106089. this.onBeforeCameraTeleport = new BABYLON.Observable();
  106090. /**
  106091. * Observable raised after camera teleportation
  106092. */
  106093. this.onAfterCameraTeleport = new BABYLON.Observable();
  106094. /**
  106095. * Observable raised when current selected mesh gets unselected
  106096. */
  106097. this.onSelectedMeshUnselected = new BABYLON.Observable();
  106098. /**
  106099. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  106100. */
  106101. this.teleportationEnabled = true;
  106102. this._teleportationInitialized = false;
  106103. this._interactionsEnabled = false;
  106104. this._interactionsRequested = false;
  106105. this._displayGaze = true;
  106106. this._displayLaserPointer = true;
  106107. /**
  106108. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  106109. */
  106110. this.updateGazeTrackerScale = true;
  106111. this._onResize = function () {
  106112. _this.moveButtonToBottomRight();
  106113. if (_this._fullscreenVRpresenting && _this._webVRready) {
  106114. _this.exitVR();
  106115. }
  106116. };
  106117. this._onFullscreenChange = function () {
  106118. if (document.fullscreen !== undefined) {
  106119. _this._fullscreenVRpresenting = document.fullscreen;
  106120. }
  106121. else if (document.mozFullScreen !== undefined) {
  106122. _this._fullscreenVRpresenting = document.mozFullScreen;
  106123. }
  106124. else if (document.webkitIsFullScreen !== undefined) {
  106125. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  106126. }
  106127. else if (document.msIsFullScreen !== undefined) {
  106128. _this._fullscreenVRpresenting = document.msIsFullScreen;
  106129. }
  106130. else if (document.msFullscreenElement !== undefined) {
  106131. _this._fullscreenVRpresenting = document.msFullscreenElement;
  106132. }
  106133. if (!_this._fullscreenVRpresenting && _this._canvas) {
  106134. _this.exitVR();
  106135. if (!_this._useCustomVRButton) {
  106136. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  106137. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  106138. }
  106139. }
  106140. };
  106141. this.beforeRender = function () {
  106142. if (_this._leftController && _this._leftController._activePointer) {
  106143. _this._castRayAndSelectObject(_this._leftController);
  106144. }
  106145. if (_this._rightController && _this._rightController._activePointer) {
  106146. _this._castRayAndSelectObject(_this._rightController);
  106147. }
  106148. if (_this._noControllerIsActive) {
  106149. _this._castRayAndSelectObject(_this._cameraGazer);
  106150. }
  106151. else {
  106152. _this._cameraGazer._gazeTracker.isVisible = false;
  106153. }
  106154. };
  106155. this._onNewGamepadConnected = function (gamepad) {
  106156. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  106157. if (gamepad.leftStick) {
  106158. gamepad.onleftstickchanged(function (stickValues) {
  106159. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  106160. // Listening to classic/xbox gamepad only if no VR controller is active
  106161. if ((!_this._leftController && !_this._rightController) ||
  106162. ((_this._leftController && !_this._leftController._activePointer) &&
  106163. (_this._rightController && !_this._rightController._activePointer))) {
  106164. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  106165. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  106166. }
  106167. }
  106168. });
  106169. }
  106170. if (gamepad.rightStick) {
  106171. gamepad.onrightstickchanged(function (stickValues) {
  106172. if (_this._teleportationInitialized) {
  106173. _this._checkRotate(stickValues, _this._cameraGazer);
  106174. }
  106175. });
  106176. }
  106177. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  106178. gamepad.onbuttondown(function (buttonPressed) {
  106179. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106180. _this._cameraGazer._selectionPointerDown();
  106181. }
  106182. });
  106183. gamepad.onbuttonup(function (buttonPressed) {
  106184. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106185. _this._cameraGazer._selectionPointerUp();
  106186. }
  106187. });
  106188. }
  106189. }
  106190. else {
  106191. var webVRController = gamepad;
  106192. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  106193. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  106194. _this._rightController = controller;
  106195. }
  106196. else {
  106197. _this._leftController = controller;
  106198. }
  106199. _this._tryEnableInteractionOnController(controller);
  106200. }
  106201. };
  106202. // 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
  106203. this._tryEnableInteractionOnController = function (controller) {
  106204. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  106205. _this._enableInteractionOnController(controller);
  106206. }
  106207. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  106208. _this._enableTeleportationOnController(controller);
  106209. }
  106210. };
  106211. this._onNewGamepadDisconnected = function (gamepad) {
  106212. if (gamepad instanceof BABYLON.WebVRController) {
  106213. if (gamepad.hand === "left" && _this._leftController != null) {
  106214. _this._leftController.dispose();
  106215. _this._leftController = null;
  106216. }
  106217. if (gamepad.hand === "right" && _this._rightController != null) {
  106218. _this._rightController.dispose();
  106219. _this._rightController = null;
  106220. }
  106221. }
  106222. };
  106223. this._workingVector = BABYLON.Vector3.Zero();
  106224. this._workingQuaternion = BABYLON.Quaternion.Identity();
  106225. this._workingMatrix = BABYLON.Matrix.Identity();
  106226. this._scene = scene;
  106227. this._canvas = scene.getEngine().getRenderingCanvas();
  106228. // Parse options
  106229. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  106230. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  106231. }
  106232. if (webVROptions.createDeviceOrientationCamera === undefined) {
  106233. webVROptions.createDeviceOrientationCamera = true;
  106234. }
  106235. if (webVROptions.laserToggle === undefined) {
  106236. webVROptions.laserToggle = true;
  106237. }
  106238. if (webVROptions.defaultHeight === undefined) {
  106239. webVROptions.defaultHeight = 1.7;
  106240. }
  106241. if (webVROptions.useCustomVRButton) {
  106242. this._useCustomVRButton = true;
  106243. if (webVROptions.customVRButton) {
  106244. this._btnVR = webVROptions.customVRButton;
  106245. }
  106246. }
  106247. if (webVROptions.rayLength) {
  106248. this._rayLength = webVROptions.rayLength;
  106249. }
  106250. this._defaultHeight = webVROptions.defaultHeight;
  106251. if (webVROptions.positionScale) {
  106252. this._rayLength *= webVROptions.positionScale;
  106253. this._defaultHeight *= webVROptions.positionScale;
  106254. }
  106255. this._hasEnteredVR = false;
  106256. // Set position
  106257. if (this._scene.activeCamera) {
  106258. this._position = this._scene.activeCamera.position.clone();
  106259. }
  106260. else {
  106261. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  106262. }
  106263. // Set non-vr camera
  106264. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  106265. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  106266. // Copy data from existing camera
  106267. if (this._scene.activeCamera) {
  106268. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106269. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  106270. // Set rotation from previous camera
  106271. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  106272. var targetCamera = this._scene.activeCamera;
  106273. if (targetCamera.rotationQuaternion) {
  106274. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  106275. }
  106276. else {
  106277. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  106278. }
  106279. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  106280. }
  106281. }
  106282. this._scene.activeCamera = this._deviceOrientationCamera;
  106283. if (this._canvas) {
  106284. this._scene.activeCamera.attachControl(this._canvas);
  106285. }
  106286. }
  106287. else {
  106288. this._existingCamera = this._scene.activeCamera;
  106289. }
  106290. // Create VR cameras
  106291. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106292. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  106293. }
  106294. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  106295. this._webVRCamera.useStandingMatrix();
  106296. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  106297. // Create default button
  106298. if (!this._useCustomVRButton) {
  106299. this._btnVR = document.createElement("BUTTON");
  106300. this._btnVR.className = "babylonVRicon";
  106301. this._btnVR.id = "babylonVRiconbtn";
  106302. this._btnVR.title = "Click to switch to VR";
  106303. 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) }";
  106304. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  106305. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  106306. // css += ".babylonVRicon.vrdisplaysupported { }";
  106307. // css += ".babylonVRicon.vrdisplayready { }";
  106308. // css += ".babylonVRicon.vrdisplayrequesting { }";
  106309. var style = document.createElement('style');
  106310. style.appendChild(document.createTextNode(css));
  106311. document.getElementsByTagName('head')[0].appendChild(style);
  106312. this.moveButtonToBottomRight();
  106313. }
  106314. // VR button click event
  106315. if (this._btnVR) {
  106316. this._btnVR.addEventListener("click", function () {
  106317. if (!_this.isInVRMode) {
  106318. _this.enterVR();
  106319. }
  106320. else {
  106321. _this.exitVR();
  106322. }
  106323. });
  106324. }
  106325. // Window events
  106326. window.addEventListener("resize", this._onResize);
  106327. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  106328. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  106329. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  106330. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  106331. document.onmsfullscreenchange = this._onFullscreenChange;
  106332. // Display vr button when headset is connected
  106333. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106334. this.displayVRButton();
  106335. }
  106336. else {
  106337. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  106338. if (e.vrDisplay) {
  106339. _this.displayVRButton();
  106340. }
  106341. });
  106342. }
  106343. // Exiting VR mode using 'ESC' key on desktop
  106344. this._onKeyDown = function (event) {
  106345. if (event.keyCode === 27 && _this.isInVRMode) {
  106346. _this.exitVR();
  106347. }
  106348. };
  106349. document.addEventListener("keydown", this._onKeyDown);
  106350. // Exiting VR mode double tapping the touch screen
  106351. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  106352. if (_this.isInVRMode) {
  106353. _this.exitVR();
  106354. if (_this._fullscreenVRpresenting) {
  106355. _this._scene.getEngine().switchFullscreen(true);
  106356. }
  106357. }
  106358. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  106359. // Listen for WebVR display changes
  106360. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  106361. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  106362. this._onVRRequestPresentStart = function () {
  106363. _this._webVRrequesting = true;
  106364. _this.updateButtonVisibility();
  106365. };
  106366. this._onVRRequestPresentComplete = function (success) {
  106367. _this._webVRrequesting = false;
  106368. _this.updateButtonVisibility();
  106369. };
  106370. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  106371. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  106372. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  106373. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106374. scene.onDisposeObservable.add(function () {
  106375. _this.dispose();
  106376. });
  106377. // Gamepad connection events
  106378. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  106379. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  106380. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  106381. this.updateButtonVisibility();
  106382. //create easing functions
  106383. this._circleEase = new BABYLON.CircleEase();
  106384. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  106385. if (this.webVROptions.floorMeshes) {
  106386. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  106387. }
  106388. }
  106389. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  106390. /** Return this.onEnteringVRObservable
  106391. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  106392. */
  106393. get: function () {
  106394. return this.onEnteringVRObservable;
  106395. },
  106396. enumerable: true,
  106397. configurable: true
  106398. });
  106399. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  106400. /** Return this.onExitingVRObservable
  106401. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  106402. */
  106403. get: function () {
  106404. return this.onExitingVRObservable;
  106405. },
  106406. enumerable: true,
  106407. configurable: true
  106408. });
  106409. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  106410. /** Return this.onControllerMeshLoadedObservable
  106411. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  106412. */
  106413. get: function () {
  106414. return this.onControllerMeshLoadedObservable;
  106415. },
  106416. enumerable: true,
  106417. configurable: true
  106418. });
  106419. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  106420. /**
  106421. * The mesh used to display where the user is going to teleport.
  106422. */
  106423. get: function () {
  106424. return this._teleportationTarget;
  106425. },
  106426. /**
  106427. * Sets the mesh to be used to display where the user is going to teleport.
  106428. */
  106429. set: function (value) {
  106430. if (value) {
  106431. value.name = "teleportationTarget";
  106432. this._isDefaultTeleportationTarget = false;
  106433. this._teleportationTarget = value;
  106434. }
  106435. },
  106436. enumerable: true,
  106437. configurable: true
  106438. });
  106439. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  106440. /**
  106441. * 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
  106442. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  106443. * See http://doc.babylonjs.com/resources/baking_transformations
  106444. */
  106445. get: function () {
  106446. return this._cameraGazer._gazeTracker;
  106447. },
  106448. set: function (value) {
  106449. if (value) {
  106450. // Dispose of existing meshes
  106451. if (this._cameraGazer._gazeTracker) {
  106452. this._cameraGazer._gazeTracker.dispose();
  106453. }
  106454. if (this._leftController && this._leftController._gazeTracker) {
  106455. this._leftController._gazeTracker.dispose();
  106456. }
  106457. if (this._rightController && this._rightController._gazeTracker) {
  106458. this._rightController._gazeTracker.dispose();
  106459. }
  106460. // Set and create gaze trackers on head and controllers
  106461. this._cameraGazer._gazeTracker = value;
  106462. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  106463. this._cameraGazer._gazeTracker.isPickable = false;
  106464. this._cameraGazer._gazeTracker.isVisible = false;
  106465. this._cameraGazer._gazeTracker.name = "gazeTracker";
  106466. if (this._leftController) {
  106467. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106468. }
  106469. if (this._rightController) {
  106470. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106471. }
  106472. }
  106473. },
  106474. enumerable: true,
  106475. configurable: true
  106476. });
  106477. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  106478. /**
  106479. * The gaze tracking mesh corresponding to the left controller
  106480. */
  106481. get: function () {
  106482. if (this._leftController) {
  106483. return this._leftController._gazeTracker;
  106484. }
  106485. return null;
  106486. },
  106487. enumerable: true,
  106488. configurable: true
  106489. });
  106490. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  106491. /**
  106492. * The gaze tracking mesh corresponding to the right controller
  106493. */
  106494. get: function () {
  106495. if (this._rightController) {
  106496. return this._rightController._gazeTracker;
  106497. }
  106498. return null;
  106499. },
  106500. enumerable: true,
  106501. configurable: true
  106502. });
  106503. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  106504. /**
  106505. * If the ray of the gaze should be displayed.
  106506. */
  106507. get: function () {
  106508. return this._displayGaze;
  106509. },
  106510. /**
  106511. * Sets if the ray of the gaze should be displayed.
  106512. */
  106513. set: function (value) {
  106514. this._displayGaze = value;
  106515. if (!value) {
  106516. this._cameraGazer._gazeTracker.isVisible = false;
  106517. if (this._leftController) {
  106518. this._leftController._gazeTracker.isVisible = false;
  106519. }
  106520. if (this._rightController) {
  106521. this._rightController._gazeTracker.isVisible = false;
  106522. }
  106523. }
  106524. },
  106525. enumerable: true,
  106526. configurable: true
  106527. });
  106528. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  106529. /**
  106530. * If the ray of the LaserPointer should be displayed.
  106531. */
  106532. get: function () {
  106533. return this._displayLaserPointer;
  106534. },
  106535. /**
  106536. * Sets if the ray of the LaserPointer should be displayed.
  106537. */
  106538. set: function (value) {
  106539. this._displayLaserPointer = value;
  106540. if (!value) {
  106541. if (this._rightController) {
  106542. this._rightController._deactivatePointer();
  106543. this._rightController._gazeTracker.isVisible = false;
  106544. }
  106545. if (this._leftController) {
  106546. this._leftController._deactivatePointer();
  106547. this._leftController._gazeTracker.isVisible = false;
  106548. }
  106549. }
  106550. else {
  106551. if (this._rightController) {
  106552. this._rightController._activatePointer();
  106553. }
  106554. if (this._leftController) {
  106555. this._leftController._activatePointer();
  106556. }
  106557. }
  106558. },
  106559. enumerable: true,
  106560. configurable: true
  106561. });
  106562. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  106563. /**
  106564. * The deviceOrientationCamera used as the camera when not in VR.
  106565. */
  106566. get: function () {
  106567. return this._deviceOrientationCamera;
  106568. },
  106569. enumerable: true,
  106570. configurable: true
  106571. });
  106572. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  106573. /**
  106574. * Based on the current WebVR support, returns the current VR camera used.
  106575. */
  106576. get: function () {
  106577. if (this._webVRready) {
  106578. return this._webVRCamera;
  106579. }
  106580. else {
  106581. return this._scene.activeCamera;
  106582. }
  106583. },
  106584. enumerable: true,
  106585. configurable: true
  106586. });
  106587. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  106588. /**
  106589. * The webVRCamera which is used when in VR.
  106590. */
  106591. get: function () {
  106592. return this._webVRCamera;
  106593. },
  106594. enumerable: true,
  106595. configurable: true
  106596. });
  106597. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  106598. /**
  106599. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  106600. */
  106601. get: function () {
  106602. return this._vrDeviceOrientationCamera;
  106603. },
  106604. enumerable: true,
  106605. configurable: true
  106606. });
  106607. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  106608. get: function () {
  106609. var result = this._cameraGazer._teleportationRequestInitiated
  106610. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  106611. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  106612. return result;
  106613. },
  106614. enumerable: true,
  106615. configurable: true
  106616. });
  106617. // Raised when one of the controller has loaded successfully its associated default mesh
  106618. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  106619. if (this._leftController && this._leftController.webVRController == webVRController) {
  106620. if (webVRController.mesh) {
  106621. this._leftController._setLaserPointerParent(webVRController.mesh);
  106622. }
  106623. }
  106624. if (this._rightController && this._rightController.webVRController == webVRController) {
  106625. if (webVRController.mesh) {
  106626. this._rightController._setLaserPointerParent(webVRController.mesh);
  106627. }
  106628. }
  106629. try {
  106630. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  106631. }
  106632. catch (err) {
  106633. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  106634. }
  106635. };
  106636. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  106637. /**
  106638. * Gets a value indicating if we are currently in VR mode.
  106639. */
  106640. get: function () {
  106641. return this._webVRpresenting || this._fullscreenVRpresenting;
  106642. },
  106643. enumerable: true,
  106644. configurable: true
  106645. });
  106646. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  106647. var vrDisplay = this._scene.getEngine().getVRDevice();
  106648. if (vrDisplay) {
  106649. var wasPresenting = this._webVRpresenting;
  106650. this._webVRpresenting = vrDisplay.isPresenting;
  106651. if (wasPresenting && !this._webVRpresenting) {
  106652. this.exitVR();
  106653. }
  106654. }
  106655. else {
  106656. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  106657. }
  106658. this.updateButtonVisibility();
  106659. };
  106660. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  106661. this._webVRsupported = eventArgs.vrSupported;
  106662. this._webVRready = !!eventArgs.vrDisplay;
  106663. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  106664. this.updateButtonVisibility();
  106665. };
  106666. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  106667. if (this._canvas && !this._useCustomVRButton) {
  106668. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  106669. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  106670. }
  106671. };
  106672. VRExperienceHelper.prototype.displayVRButton = function () {
  106673. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  106674. document.body.appendChild(this._btnVR);
  106675. this._btnVRDisplayed = true;
  106676. }
  106677. };
  106678. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  106679. if (!this._btnVR || this._useCustomVRButton) {
  106680. return;
  106681. }
  106682. this._btnVR.className = "babylonVRicon";
  106683. if (this.isInVRMode) {
  106684. this._btnVR.className += " vrdisplaypresenting";
  106685. }
  106686. else {
  106687. if (this._webVRready) {
  106688. this._btnVR.className += " vrdisplayready";
  106689. }
  106690. if (this._webVRsupported) {
  106691. this._btnVR.className += " vrdisplaysupported";
  106692. }
  106693. if (this._webVRrequesting) {
  106694. this._btnVR.className += " vrdisplayrequesting";
  106695. }
  106696. }
  106697. };
  106698. /**
  106699. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  106700. * Otherwise, will use the fullscreen API.
  106701. */
  106702. VRExperienceHelper.prototype.enterVR = function () {
  106703. if (this.onEnteringVRObservable) {
  106704. try {
  106705. this.onEnteringVRObservable.notifyObservers(this);
  106706. }
  106707. catch (err) {
  106708. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  106709. }
  106710. }
  106711. if (this._scene.activeCamera) {
  106712. this._position = this._scene.activeCamera.position.clone();
  106713. // make sure that we return to the last active camera
  106714. this._existingCamera = this._scene.activeCamera;
  106715. }
  106716. if (this._webVRrequesting) {
  106717. return;
  106718. }
  106719. // If WebVR is supported and a headset is connected
  106720. if (this._webVRready) {
  106721. if (!this._webVRpresenting) {
  106722. this._webVRCamera.position = this._position;
  106723. this._scene.activeCamera = this._webVRCamera;
  106724. }
  106725. }
  106726. else if (this._vrDeviceOrientationCamera) {
  106727. this._vrDeviceOrientationCamera.position = this._position;
  106728. if (this._scene.activeCamera) {
  106729. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106730. }
  106731. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  106732. this._scene.getEngine().switchFullscreen(true);
  106733. this.updateButtonVisibility();
  106734. }
  106735. if (this._scene.activeCamera && this._canvas) {
  106736. this._scene.activeCamera.attachControl(this._canvas);
  106737. }
  106738. if (this._interactionsEnabled) {
  106739. this._scene.registerBeforeRender(this.beforeRender);
  106740. }
  106741. this._hasEnteredVR = true;
  106742. };
  106743. /**
  106744. * Attempt to exit VR, or fullscreen.
  106745. */
  106746. VRExperienceHelper.prototype.exitVR = function () {
  106747. if (this._hasEnteredVR) {
  106748. if (this.onExitingVRObservable) {
  106749. try {
  106750. this.onExitingVRObservable.notifyObservers(this);
  106751. }
  106752. catch (err) {
  106753. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  106754. }
  106755. }
  106756. if (this._webVRpresenting) {
  106757. this._scene.getEngine().disableVR();
  106758. }
  106759. if (this._scene.activeCamera) {
  106760. this._position = this._scene.activeCamera.position.clone();
  106761. }
  106762. if (this._deviceOrientationCamera) {
  106763. this._deviceOrientationCamera.position = this._position;
  106764. this._scene.activeCamera = this._deviceOrientationCamera;
  106765. if (this._canvas) {
  106766. this._scene.activeCamera.attachControl(this._canvas);
  106767. }
  106768. }
  106769. else if (this._existingCamera) {
  106770. this._existingCamera.position = this._position;
  106771. this._scene.activeCamera = this._existingCamera;
  106772. }
  106773. this.updateButtonVisibility();
  106774. if (this._interactionsEnabled) {
  106775. this._scene.unregisterBeforeRender(this.beforeRender);
  106776. this._cameraGazer._gazeTracker.isVisible = false;
  106777. if (this._leftController) {
  106778. this._leftController._gazeTracker.isVisible = false;
  106779. }
  106780. if (this._rightController) {
  106781. this._rightController._gazeTracker.isVisible = false;
  106782. }
  106783. }
  106784. // resize to update width and height when exiting vr exits fullscreen
  106785. this._scene.getEngine().resize();
  106786. this._hasEnteredVR = false;
  106787. }
  106788. };
  106789. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  106790. /**
  106791. * The position of the vr experience helper.
  106792. */
  106793. get: function () {
  106794. return this._position;
  106795. },
  106796. /**
  106797. * Sets the position of the vr experience helper.
  106798. */
  106799. set: function (value) {
  106800. this._position = value;
  106801. if (this._scene.activeCamera) {
  106802. this._scene.activeCamera.position = value;
  106803. }
  106804. },
  106805. enumerable: true,
  106806. configurable: true
  106807. });
  106808. /**
  106809. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  106810. */
  106811. VRExperienceHelper.prototype.enableInteractions = function () {
  106812. var _this = this;
  106813. if (!this._interactionsEnabled) {
  106814. this._interactionsRequested = true;
  106815. if (this._leftController) {
  106816. this._enableInteractionOnController(this._leftController);
  106817. }
  106818. if (this._rightController) {
  106819. this._enableInteractionOnController(this._rightController);
  106820. }
  106821. this.raySelectionPredicate = function (mesh) {
  106822. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  106823. };
  106824. this.meshSelectionPredicate = function (mesh) {
  106825. return true;
  106826. };
  106827. this._raySelectionPredicate = function (mesh) {
  106828. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  106829. && mesh.name.indexOf("teleportationTarget") === -1
  106830. && mesh.name.indexOf("torusTeleportation") === -1)) {
  106831. return _this.raySelectionPredicate(mesh);
  106832. }
  106833. return false;
  106834. };
  106835. this._interactionsEnabled = true;
  106836. }
  106837. };
  106838. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  106839. get: function () {
  106840. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  106841. },
  106842. enumerable: true,
  106843. configurable: true
  106844. });
  106845. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  106846. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  106847. if (this._floorMeshesCollection[i].id === mesh.id) {
  106848. return true;
  106849. }
  106850. }
  106851. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  106852. return true;
  106853. }
  106854. return false;
  106855. };
  106856. /**
  106857. * Adds a floor mesh to be used for teleportation.
  106858. * @param floorMesh the mesh to be used for teleportation.
  106859. */
  106860. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  106861. if (!this._floorMeshesCollection) {
  106862. return;
  106863. }
  106864. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  106865. return;
  106866. }
  106867. this._floorMeshesCollection.push(floorMesh);
  106868. };
  106869. /**
  106870. * Removes a floor mesh from being used for teleportation.
  106871. * @param floorMesh the mesh to be removed.
  106872. */
  106873. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  106874. if (!this._floorMeshesCollection) {
  106875. return;
  106876. }
  106877. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  106878. if (meshIndex !== -1) {
  106879. this._floorMeshesCollection.splice(meshIndex, 1);
  106880. }
  106881. };
  106882. /**
  106883. * Enables interactions and teleportation using the VR controllers and gaze.
  106884. * @param vrTeleportationOptions options to modify teleportation behavior.
  106885. */
  106886. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  106887. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  106888. if (!this._teleportationInitialized) {
  106889. this._teleportationRequested = true;
  106890. this.enableInteractions();
  106891. if (vrTeleportationOptions.floorMeshName) {
  106892. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  106893. }
  106894. if (vrTeleportationOptions.floorMeshes) {
  106895. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  106896. }
  106897. if (this._leftController != null) {
  106898. this._enableTeleportationOnController(this._leftController);
  106899. }
  106900. if (this._rightController != null) {
  106901. this._enableTeleportationOnController(this._rightController);
  106902. }
  106903. // Creates an image processing post process for the vignette not relying
  106904. // on the main scene configuration for image processing to reduce setup and spaces
  106905. // (gamma/linear) conflicts.
  106906. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  106907. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  106908. imageProcessingConfiguration.vignetteEnabled = true;
  106909. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  106910. this._webVRCamera.detachPostProcess(this._postProcessMove);
  106911. this._teleportationInitialized = true;
  106912. if (this._isDefaultTeleportationTarget) {
  106913. this._createTeleportationCircles();
  106914. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  106915. }
  106916. }
  106917. };
  106918. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  106919. var _this = this;
  106920. var controllerMesh = controller.webVRController.mesh;
  106921. if (controllerMesh) {
  106922. controller._interactionsEnabled = true;
  106923. controller._activatePointer();
  106924. if (this.webVROptions.laserToggle) {
  106925. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  106926. // Enabling / disabling laserPointer
  106927. if (_this._displayLaserPointer && stateObject.value === 1) {
  106928. if (controller._activePointer) {
  106929. controller._deactivatePointer();
  106930. }
  106931. else {
  106932. controller._activatePointer();
  106933. }
  106934. if (_this.displayGaze) {
  106935. controller._gazeTracker.isVisible = controller._activePointer;
  106936. }
  106937. }
  106938. });
  106939. }
  106940. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  106941. var gazer = controller;
  106942. if (_this._noControllerIsActive) {
  106943. gazer = _this._cameraGazer;
  106944. }
  106945. if (!gazer._pointerDownOnMeshAsked) {
  106946. if (stateObject.value > _this._padSensibilityUp) {
  106947. gazer._selectionPointerDown();
  106948. }
  106949. }
  106950. else if (stateObject.value < _this._padSensibilityDown) {
  106951. gazer._selectionPointerUp();
  106952. }
  106953. });
  106954. }
  106955. };
  106956. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  106957. // Dont teleport if another gaze already requested teleportation
  106958. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  106959. return;
  106960. }
  106961. if (!gazer._teleportationRequestInitiated) {
  106962. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  106963. gazer._activatePointer();
  106964. gazer._teleportationRequestInitiated = true;
  106965. }
  106966. }
  106967. else {
  106968. // Listening to the proper controller values changes to confirm teleportation
  106969. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  106970. if (this._teleportActive) {
  106971. this.teleportCamera(this._haloCenter);
  106972. }
  106973. gazer._teleportationRequestInitiated = false;
  106974. }
  106975. }
  106976. };
  106977. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  106978. // Only rotate when user is not currently selecting a teleportation location
  106979. if (gazer._teleportationRequestInitiated) {
  106980. return;
  106981. }
  106982. if (!gazer._rotationLeftAsked) {
  106983. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  106984. gazer._rotationLeftAsked = true;
  106985. if (this._rotationAllowed) {
  106986. this._rotateCamera(false);
  106987. }
  106988. }
  106989. }
  106990. else {
  106991. if (stateObject.x > -this._padSensibilityDown) {
  106992. gazer._rotationLeftAsked = false;
  106993. }
  106994. }
  106995. if (!gazer._rotationRightAsked) {
  106996. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  106997. gazer._rotationRightAsked = true;
  106998. if (this._rotationAllowed) {
  106999. this._rotateCamera(true);
  107000. }
  107001. }
  107002. }
  107003. else {
  107004. if (stateObject.x < this._padSensibilityDown) {
  107005. gazer._rotationRightAsked = false;
  107006. }
  107007. }
  107008. };
  107009. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  107010. // Only teleport backwards when user is not currently selecting a teleportation location
  107011. if (gazer._teleportationRequestInitiated) {
  107012. return;
  107013. }
  107014. // Teleport backwards
  107015. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  107016. if (!gazer._teleportationBackRequestInitiated) {
  107017. if (!this.currentVRCamera) {
  107018. return;
  107019. }
  107020. // Get rotation and position of the current camera
  107021. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  107022. var position = this.currentVRCamera.position;
  107023. // If the camera has device position, use that instead
  107024. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  107025. rotation = this.currentVRCamera.deviceRotationQuaternion;
  107026. position = this.currentVRCamera.devicePosition;
  107027. }
  107028. // Get matrix with only the y rotation of the device rotation
  107029. rotation.toEulerAnglesToRef(this._workingVector);
  107030. this._workingVector.z = 0;
  107031. this._workingVector.x = 0;
  107032. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  107033. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  107034. // Rotate backwards ray by device rotation to cast at the ground behind the user
  107035. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  107036. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  107037. var ray = new BABYLON.Ray(position, this._workingVector);
  107038. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107039. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  107040. this.teleportCamera(hit.pickedPoint);
  107041. }
  107042. gazer._teleportationBackRequestInitiated = true;
  107043. }
  107044. }
  107045. else {
  107046. gazer._teleportationBackRequestInitiated = false;
  107047. }
  107048. };
  107049. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  107050. var _this = this;
  107051. var controllerMesh = controller.webVRController.mesh;
  107052. if (controllerMesh) {
  107053. if (!controller._interactionsEnabled) {
  107054. this._enableInteractionOnController(controller);
  107055. }
  107056. controller._interactionsEnabled = true;
  107057. controller._teleportationEnabled = true;
  107058. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  107059. controller._dpadPressed = false;
  107060. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  107061. controller._dpadPressed = stateObject.pressed;
  107062. if (!controller._dpadPressed) {
  107063. controller._rotationLeftAsked = false;
  107064. controller._rotationRightAsked = false;
  107065. controller._teleportationBackRequestInitiated = false;
  107066. }
  107067. });
  107068. }
  107069. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  107070. if (_this.teleportationEnabled) {
  107071. _this._checkTeleportBackwards(stateObject, controller);
  107072. _this._checkTeleportWithRay(stateObject, controller);
  107073. }
  107074. _this._checkRotate(stateObject, controller);
  107075. });
  107076. }
  107077. };
  107078. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  107079. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  107080. this._teleportationTarget.isPickable = false;
  107081. var length = 512;
  107082. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  107083. dynamicTexture.hasAlpha = true;
  107084. var context = dynamicTexture.getContext();
  107085. var centerX = length / 2;
  107086. var centerY = length / 2;
  107087. var radius = 200;
  107088. context.beginPath();
  107089. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  107090. context.fillStyle = this._teleportationFillColor;
  107091. context.fill();
  107092. context.lineWidth = 10;
  107093. context.strokeStyle = this._teleportationBorderColor;
  107094. context.stroke();
  107095. context.closePath();
  107096. dynamicTexture.update();
  107097. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  107098. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  107099. this._teleportationTarget.material = teleportationCircleMaterial;
  107100. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  107101. torus.isPickable = false;
  107102. torus.parent = this._teleportationTarget;
  107103. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107104. var keys = [];
  107105. keys.push({
  107106. frame: 0,
  107107. value: 0
  107108. });
  107109. keys.push({
  107110. frame: 30,
  107111. value: 0.4
  107112. });
  107113. keys.push({
  107114. frame: 60,
  107115. value: 0
  107116. });
  107117. animationInnerCircle.setKeys(keys);
  107118. var easingFunction = new BABYLON.SineEase();
  107119. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  107120. animationInnerCircle.setEasingFunction(easingFunction);
  107121. torus.animations = [];
  107122. torus.animations.push(animationInnerCircle);
  107123. this._scene.beginAnimation(torus, 0, 60, true);
  107124. this._hideTeleportationTarget();
  107125. };
  107126. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  107127. this._teleportActive = true;
  107128. if (this._teleportationInitialized) {
  107129. this._teleportationTarget.isVisible = true;
  107130. if (this._isDefaultTeleportationTarget) {
  107131. this._teleportationTarget.getChildren()[0].isVisible = true;
  107132. }
  107133. }
  107134. };
  107135. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  107136. this._teleportActive = false;
  107137. if (this._teleportationInitialized) {
  107138. this._teleportationTarget.isVisible = false;
  107139. if (this._isDefaultTeleportationTarget) {
  107140. this._teleportationTarget.getChildren()[0].isVisible = false;
  107141. }
  107142. }
  107143. };
  107144. VRExperienceHelper.prototype._rotateCamera = function (right) {
  107145. var _this = this;
  107146. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107147. return;
  107148. }
  107149. if (right) {
  107150. this._rotationAngle++;
  107151. }
  107152. else {
  107153. this._rotationAngle--;
  107154. }
  107155. this.currentVRCamera.animations = [];
  107156. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  107157. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107158. var animationRotationKeys = [];
  107159. animationRotationKeys.push({
  107160. frame: 0,
  107161. value: this.currentVRCamera.rotationQuaternion
  107162. });
  107163. animationRotationKeys.push({
  107164. frame: 6,
  107165. value: target
  107166. });
  107167. animationRotation.setKeys(animationRotationKeys);
  107168. animationRotation.setEasingFunction(this._circleEase);
  107169. this.currentVRCamera.animations.push(animationRotation);
  107170. this._postProcessMove.animations = [];
  107171. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107172. var vignetteWeightKeys = [];
  107173. vignetteWeightKeys.push({
  107174. frame: 0,
  107175. value: 0
  107176. });
  107177. vignetteWeightKeys.push({
  107178. frame: 3,
  107179. value: 4
  107180. });
  107181. vignetteWeightKeys.push({
  107182. frame: 6,
  107183. value: 0
  107184. });
  107185. animationPP.setKeys(vignetteWeightKeys);
  107186. animationPP.setEasingFunction(this._circleEase);
  107187. this._postProcessMove.animations.push(animationPP);
  107188. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107189. var vignetteStretchKeys = [];
  107190. vignetteStretchKeys.push({
  107191. frame: 0,
  107192. value: 0
  107193. });
  107194. vignetteStretchKeys.push({
  107195. frame: 3,
  107196. value: 10
  107197. });
  107198. vignetteStretchKeys.push({
  107199. frame: 6,
  107200. value: 0
  107201. });
  107202. animationPP2.setKeys(vignetteStretchKeys);
  107203. animationPP2.setEasingFunction(this._circleEase);
  107204. this._postProcessMove.animations.push(animationPP2);
  107205. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107206. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107207. this._postProcessMove.samples = 4;
  107208. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107209. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  107210. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107211. });
  107212. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  107213. };
  107214. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  107215. if (hit.pickedPoint) {
  107216. if (gazer._teleportationRequestInitiated) {
  107217. this._displayTeleportationTarget();
  107218. this._haloCenter.copyFrom(hit.pickedPoint);
  107219. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  107220. }
  107221. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  107222. if (pickNormal) {
  107223. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107224. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107225. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  107226. }
  107227. this._teleportationTarget.position.y += 0.1;
  107228. }
  107229. };
  107230. /**
  107231. * Teleports the users feet to the desired location
  107232. * @param location The location where the user's feet should be placed
  107233. */
  107234. VRExperienceHelper.prototype.teleportCamera = function (location) {
  107235. var _this = this;
  107236. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107237. return;
  107238. }
  107239. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  107240. // offset of the headset from the anchor.
  107241. if (this.webVRCamera.leftCamera) {
  107242. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  107243. this._workingVector.subtractInPlace(this.webVRCamera.position);
  107244. location.subtractToRef(this._workingVector, this._workingVector);
  107245. }
  107246. else {
  107247. this._workingVector.copyFrom(location);
  107248. }
  107249. // Add height to account for user's height offset
  107250. if (this.isInVRMode) {
  107251. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  107252. }
  107253. else {
  107254. this._workingVector.y += this._defaultHeight;
  107255. }
  107256. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  107257. // Create animation from the camera's position to the new location
  107258. this.currentVRCamera.animations = [];
  107259. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107260. var animationCameraTeleportationKeys = [{
  107261. frame: 0,
  107262. value: this.currentVRCamera.position
  107263. },
  107264. {
  107265. frame: 11,
  107266. value: this._workingVector
  107267. }
  107268. ];
  107269. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  107270. animationCameraTeleportation.setEasingFunction(this._circleEase);
  107271. this.currentVRCamera.animations.push(animationCameraTeleportation);
  107272. this._postProcessMove.animations = [];
  107273. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107274. var vignetteWeightKeys = [];
  107275. vignetteWeightKeys.push({
  107276. frame: 0,
  107277. value: 0
  107278. });
  107279. vignetteWeightKeys.push({
  107280. frame: 5,
  107281. value: 8
  107282. });
  107283. vignetteWeightKeys.push({
  107284. frame: 11,
  107285. value: 0
  107286. });
  107287. animationPP.setKeys(vignetteWeightKeys);
  107288. this._postProcessMove.animations.push(animationPP);
  107289. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107290. var vignetteStretchKeys = [];
  107291. vignetteStretchKeys.push({
  107292. frame: 0,
  107293. value: 0
  107294. });
  107295. vignetteStretchKeys.push({
  107296. frame: 5,
  107297. value: 10
  107298. });
  107299. vignetteStretchKeys.push({
  107300. frame: 11,
  107301. value: 0
  107302. });
  107303. animationPP2.setKeys(vignetteStretchKeys);
  107304. this._postProcessMove.animations.push(animationPP2);
  107305. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107306. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107307. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107308. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  107309. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107310. });
  107311. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  107312. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  107313. });
  107314. this._hideTeleportationTarget();
  107315. };
  107316. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  107317. if (normal) {
  107318. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  107319. if (angle < Math.PI / 2) {
  107320. normal.scaleInPlace(-1);
  107321. }
  107322. }
  107323. return normal;
  107324. };
  107325. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  107326. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107327. return;
  107328. }
  107329. var ray = gazer._getForwardRay(this._rayLength);
  107330. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107331. if (hit) {
  107332. // Populate the contrllers mesh that can be used for drag/drop
  107333. if (gazer._laserPointer) {
  107334. hit.originMesh = gazer._laserPointer.parent;
  107335. }
  107336. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  107337. }
  107338. gazer._currentHit = hit;
  107339. // Moving the gazeTracker on the mesh face targetted
  107340. if (hit && hit.pickedPoint) {
  107341. if (this._displayGaze) {
  107342. var multiplier = 1;
  107343. gazer._gazeTracker.isVisible = true;
  107344. if (gazer._isActionableMesh) {
  107345. multiplier = 3;
  107346. }
  107347. if (this.updateGazeTrackerScale) {
  107348. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  107349. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  107350. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  107351. }
  107352. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  107353. // To avoid z-fighting
  107354. var deltaFighting = 0.002;
  107355. if (pickNormal) {
  107356. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107357. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107358. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  107359. }
  107360. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  107361. if (gazer._gazeTracker.position.x < 0) {
  107362. gazer._gazeTracker.position.x += deltaFighting;
  107363. }
  107364. else {
  107365. gazer._gazeTracker.position.x -= deltaFighting;
  107366. }
  107367. if (gazer._gazeTracker.position.y < 0) {
  107368. gazer._gazeTracker.position.y += deltaFighting;
  107369. }
  107370. else {
  107371. gazer._gazeTracker.position.y -= deltaFighting;
  107372. }
  107373. if (gazer._gazeTracker.position.z < 0) {
  107374. gazer._gazeTracker.position.z += deltaFighting;
  107375. }
  107376. else {
  107377. gazer._gazeTracker.position.z -= deltaFighting;
  107378. }
  107379. }
  107380. // Changing the size of the laser pointer based on the distance from the targetted point
  107381. gazer._updatePointerDistance(hit.distance);
  107382. }
  107383. else {
  107384. gazer._updatePointerDistance();
  107385. gazer._gazeTracker.isVisible = false;
  107386. }
  107387. if (hit && hit.pickedMesh) {
  107388. // The object selected is the floor, we're in a teleportation scenario
  107389. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  107390. // Moving the teleportation area to this targetted point
  107391. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  107392. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  107393. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107394. }
  107395. gazer._currentMeshSelected = null;
  107396. if (gazer._teleportationRequestInitiated) {
  107397. this._moveTeleportationSelectorTo(hit, gazer, ray);
  107398. }
  107399. return;
  107400. }
  107401. // If not, we're in a selection scenario
  107402. //this._teleportationAllowed = false;
  107403. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  107404. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  107405. this.onNewMeshPicked.notifyObservers(hit);
  107406. gazer._currentMeshSelected = hit.pickedMesh;
  107407. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  107408. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  107409. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  107410. gazer._isActionableMesh = true;
  107411. }
  107412. else {
  107413. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107414. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107415. gazer._isActionableMesh = false;
  107416. }
  107417. try {
  107418. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  107419. }
  107420. catch (err) {
  107421. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  107422. }
  107423. }
  107424. else {
  107425. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107426. gazer._currentMeshSelected = null;
  107427. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107428. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107429. }
  107430. }
  107431. }
  107432. else {
  107433. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107434. gazer._currentMeshSelected = null;
  107435. //this._teleportationAllowed = false;
  107436. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107437. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107438. }
  107439. };
  107440. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  107441. if (mesh) {
  107442. this.onSelectedMeshUnselected.notifyObservers(mesh);
  107443. }
  107444. };
  107445. /**
  107446. * Sets the color of the laser ray from the vr controllers.
  107447. * @param color new color for the ray.
  107448. */
  107449. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  107450. if (this._leftController) {
  107451. this._leftController._setLaserPointerColor(color);
  107452. }
  107453. if (this._rightController) {
  107454. this._rightController._setLaserPointerColor(color);
  107455. }
  107456. };
  107457. /**
  107458. * Sets the color of the ray from the vr headsets gaze.
  107459. * @param color new color for the ray.
  107460. */
  107461. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  107462. if (!this._cameraGazer._gazeTracker.material) {
  107463. return;
  107464. }
  107465. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  107466. if (this._leftController) {
  107467. this._leftController._gazeTracker.material.emissiveColor = color;
  107468. }
  107469. if (this._rightController) {
  107470. this._rightController._gazeTracker.material.emissiveColor = color;
  107471. }
  107472. };
  107473. /**
  107474. * Exits VR and disposes of the vr experience helper
  107475. */
  107476. VRExperienceHelper.prototype.dispose = function () {
  107477. if (this.isInVRMode) {
  107478. this.exitVR();
  107479. }
  107480. if (this._postProcessMove) {
  107481. this._postProcessMove.dispose();
  107482. }
  107483. if (this._webVRCamera) {
  107484. this._webVRCamera.dispose();
  107485. }
  107486. if (this._vrDeviceOrientationCamera) {
  107487. this._vrDeviceOrientationCamera.dispose();
  107488. }
  107489. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  107490. document.body.removeChild(this._btnVR);
  107491. }
  107492. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  107493. this._deviceOrientationCamera.dispose();
  107494. }
  107495. if (this._cameraGazer) {
  107496. this._cameraGazer.dispose();
  107497. }
  107498. if (this._leftController) {
  107499. this._leftController.dispose();
  107500. }
  107501. if (this._rightController) {
  107502. this._rightController.dispose();
  107503. }
  107504. if (this._teleportationTarget) {
  107505. this._teleportationTarget.dispose();
  107506. }
  107507. this._floorMeshesCollection = [];
  107508. document.removeEventListener("keydown", this._onKeyDown);
  107509. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107510. window.removeEventListener("resize", this._onResize);
  107511. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  107512. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  107513. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  107514. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  107515. document.onmsfullscreenchange = null;
  107516. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  107517. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  107518. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  107519. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107520. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  107521. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  107522. this._scene.unregisterBeforeRender(this.beforeRender);
  107523. };
  107524. /**
  107525. * Gets the name of the VRExperienceHelper class
  107526. * @returns "VRExperienceHelper"
  107527. */
  107528. VRExperienceHelper.prototype.getClassName = function () {
  107529. return "VRExperienceHelper";
  107530. };
  107531. return VRExperienceHelper;
  107532. }());
  107533. BABYLON.VRExperienceHelper = VRExperienceHelper;
  107534. })(BABYLON || (BABYLON = {}));
  107535. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  107536. var BABYLON;
  107537. (function (BABYLON) {
  107538. /**
  107539. * WebXR Camera which holds the views for the xrSession
  107540. * @see https://doc.babylonjs.com/how_to/webxr
  107541. */
  107542. var WebXRCamera = /** @class */ (function (_super) {
  107543. __extends(WebXRCamera, _super);
  107544. /**
  107545. * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager
  107546. * @param name the name of the camera
  107547. * @param scene the scene to add the camera to
  107548. */
  107549. function WebXRCamera(name, scene) {
  107550. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  107551. // Initial camera configuration
  107552. _this.minZ = 0;
  107553. _this.rotationQuaternion = new BABYLON.Quaternion();
  107554. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_CUSTOM;
  107555. _this._updateNumberOfRigCameras(1);
  107556. return _this;
  107557. }
  107558. WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) {
  107559. if (viewCount === void 0) { viewCount = 1; }
  107560. while (this.rigCameras.length < viewCount) {
  107561. var newCamera = new BABYLON.TargetCamera("view: " + this.rigCameras.length, BABYLON.Vector3.Zero(), this.getScene());
  107562. newCamera.minZ = 0;
  107563. newCamera.parent = this;
  107564. this.rigCameras.push(newCamera);
  107565. }
  107566. while (this.rigCameras.length > viewCount) {
  107567. var removedCamera = this.rigCameras.pop();
  107568. if (removedCamera) {
  107569. removedCamera.dispose();
  107570. }
  107571. }
  107572. };
  107573. /** @hidden */
  107574. WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) {
  107575. if (pupilDistance === void 0) { pupilDistance = 0.01; }
  107576. // Create initial camera rigs
  107577. this._updateNumberOfRigCameras(2);
  107578. this.rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  107579. this.rigCameras[0].position.x = -pupilDistance / 2;
  107580. this.rigCameras[0].outputRenderTarget = null;
  107581. this.rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  107582. this.rigCameras[1].position.x = pupilDistance / 2;
  107583. this.rigCameras[1].outputRenderTarget = null;
  107584. };
  107585. /**
  107586. * Updates the cameras position from the current pose information of the XR session
  107587. * @param xrSessionManager the session containing pose information
  107588. */
  107589. WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) {
  107590. var _this = this;
  107591. // Ensure all frame data is available
  107592. if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) {
  107593. return;
  107594. }
  107595. var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference);
  107596. if (!pose || !pose.poseModelMatrix) {
  107597. return;
  107598. }
  107599. // Update the parent cameras matrix
  107600. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix);
  107601. if (!this._scene.useRightHandedSystem) {
  107602. WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace();
  107603. }
  107604. WebXRCamera._TmpMatrix.getTranslationToRef(this.position);
  107605. WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix);
  107606. BABYLON.Quaternion.FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion);
  107607. this.computeWorldMatrix();
  107608. // Update camera rigs
  107609. this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length);
  107610. xrSessionManager._currentXRFrame.views.forEach(function (view, i) {
  107611. // Update view/projection matrix
  107612. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix);
  107613. BABYLON.Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix);
  107614. if (!_this._scene.useRightHandedSystem) {
  107615. _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace();
  107616. _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace();
  107617. }
  107618. // Update viewport
  107619. var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view);
  107620. var width = xrSessionManager._xrSession.baseLayer.framebufferWidth;
  107621. var height = xrSessionManager._xrSession.baseLayer.framebufferHeight;
  107622. _this.rigCameras[i].viewport.width = viewport.width / width;
  107623. _this.rigCameras[i].viewport.height = viewport.height / height;
  107624. _this.rigCameras[i].viewport.x = viewport.x / width;
  107625. _this.rigCameras[i].viewport.y = viewport.y / height;
  107626. // Set cameras to render to the session's render target
  107627. _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture;
  107628. });
  107629. };
  107630. WebXRCamera._TmpMatrix = new BABYLON.Matrix();
  107631. return WebXRCamera;
  107632. }(BABYLON.FreeCamera));
  107633. BABYLON.WebXRCamera = WebXRCamera;
  107634. })(BABYLON || (BABYLON = {}));
  107635. //# sourceMappingURL=babylon.webXRCamera.js.map
  107636. var BABYLON;
  107637. (function (BABYLON) {
  107638. /**
  107639. * Manages an XRSession
  107640. * @see https://doc.babylonjs.com/how_to/webxr
  107641. */
  107642. var WebXRSessionManager = /** @class */ (function () {
  107643. /**
  107644. * Constructs a WebXRSessionManager, this must be initialized within a user action before usage
  107645. * @param scene The scene which the session should be created for
  107646. */
  107647. function WebXRSessionManager(scene) {
  107648. this.scene = scene;
  107649. this._tmpMatrix = new BABYLON.Matrix();
  107650. }
  107651. /**
  107652. * Initializes the manager, this must be done with a user action (eg. button click event)
  107653. * After initialization enterXR can be called to start an XR session
  107654. * @returns Promise which resolves after it is initialized
  107655. */
  107656. WebXRSessionManager.prototype.initialize = function () {
  107657. var _this = this;
  107658. // Check if the browser supports webXR
  107659. this._xrNavigator = navigator;
  107660. if (!this._xrNavigator.xr) {
  107661. return Promise.reject("webXR not supported by this browser");
  107662. }
  107663. // Request the webXR device
  107664. return this._xrNavigator.xr.requestDevice().then(function (device) {
  107665. _this._xrDevice = device;
  107666. return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice);
  107667. });
  107668. };
  107669. /**
  107670. * Enters XR with the desired XR session options
  107671. * @param sessionCreationOptions xr options to create the session with
  107672. * @param frameOfReferenceType option to configure how the xr pose is expressed
  107673. * @returns Promise which resolves after it enters XR
  107674. */
  107675. WebXRSessionManager.prototype.enterXR = function (sessionCreationOptions, frameOfReferenceType) {
  107676. var _this = this;
  107677. // initialize session
  107678. return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) {
  107679. _this._xrSession = session;
  107680. _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl);
  107681. return _this._xrSession.requestFrameOfReference(frameOfReferenceType);
  107682. }).then(function (frameOfRef) {
  107683. _this._frameOfReference = frameOfRef;
  107684. // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information
  107685. _this.scene.getEngine().customAnimationFrameRequester = {
  107686. requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession),
  107687. renderFunction: function (timestamp, xrFrame) {
  107688. // Store the XR frame in the manager to be consumed by the XR camera to update pose
  107689. _this._currentXRFrame = xrFrame;
  107690. _this.scene.getEngine()._renderLoop();
  107691. }
  107692. };
  107693. // Create render target texture from xr's webgl render target
  107694. _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene);
  107695. });
  107696. };
  107697. /**
  107698. * Stops the xrSession and restores the renderloop
  107699. * @returns Promise which resolves after it exits XR
  107700. */
  107701. WebXRSessionManager.prototype.exitXR = function () {
  107702. var _this = this;
  107703. return new Promise(function (res) {
  107704. _this.scene.getEngine().customAnimationFrameRequester = null;
  107705. _this._xrSession.end();
  107706. // Restore frame buffer to avoid clear on xr framebuffer after session end
  107707. _this.scene.getEngine().restoreDefaultFramebuffer();
  107708. // Need to restart render loop as after calling session.end the last request for new frame will never call callback
  107709. _this.scene.getEngine()._renderLoop();
  107710. res();
  107711. });
  107712. };
  107713. /**
  107714. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  107715. * @param ray ray to cast into the environment
  107716. * @returns Promise which resolves with a collision point in the environment if it exists
  107717. */
  107718. WebXRSessionManager.prototype.environmentPointHitTest = function (ray) {
  107719. var _this = this;
  107720. return new Promise(function (res, rej) {
  107721. // Compute left handed inputs to request hit test
  107722. var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]);
  107723. var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]);
  107724. if (!_this.scene.useRightHandedSystem) {
  107725. origin[2] *= -1;
  107726. direction[2] *= -1;
  107727. }
  107728. // Fire hittest
  107729. _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference)
  107730. .then(function (hits) {
  107731. if (hits.length > 0) {
  107732. BABYLON.Matrix.FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix);
  107733. var hitPoint = _this._tmpMatrix.getTranslation();
  107734. if (!_this.scene.useRightHandedSystem) {
  107735. hitPoint.z *= -1;
  107736. }
  107737. res(hitPoint);
  107738. }
  107739. else {
  107740. res(null);
  107741. }
  107742. }).catch(function (e) {
  107743. res(null);
  107744. });
  107745. });
  107746. };
  107747. /**
  107748. * @hidden
  107749. * Converts the render layer of xrSession to a render target
  107750. * @param session session to create render target for
  107751. * @param scene scene the new render target should be created for
  107752. */
  107753. WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) {
  107754. // Create internal texture
  107755. var internalTexture = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_UNKNOWN, true);
  107756. internalTexture.width = session.baseLayer.framebufferWidth;
  107757. internalTexture.height = session.baseLayer.framebufferHeight;
  107758. internalTexture._framebuffer = session.baseLayer.framebuffer;
  107759. // Create render target texture from the internal texture
  107760. var renderTargetTexture = new BABYLON.RenderTargetTexture("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
  107761. renderTargetTexture._texture = internalTexture;
  107762. return renderTargetTexture;
  107763. };
  107764. return WebXRSessionManager;
  107765. }());
  107766. BABYLON.WebXRSessionManager = WebXRSessionManager;
  107767. })(BABYLON || (BABYLON = {}));
  107768. //# sourceMappingURL=babylon.webXRSessionManager.js.map
  107769. // Mainly based on these 2 articles :
  107770. // 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
  107771. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  107772. var BABYLON;
  107773. (function (BABYLON) {
  107774. /**
  107775. * Defines the potential axis of a Joystick
  107776. */
  107777. var JoystickAxis;
  107778. (function (JoystickAxis) {
  107779. /** X axis */
  107780. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  107781. /** Y axis */
  107782. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  107783. /** Z axis */
  107784. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  107785. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  107786. /**
  107787. * Class used to define virtual joystick (used in touch mode)
  107788. */
  107789. var VirtualJoystick = /** @class */ (function () {
  107790. /**
  107791. * Creates a new virtual joystick
  107792. * @param leftJoystick defines that the joystick is for left hand (false by default)
  107793. */
  107794. function VirtualJoystick(leftJoystick) {
  107795. var _this = this;
  107796. if (leftJoystick) {
  107797. this._leftJoystick = true;
  107798. }
  107799. else {
  107800. this._leftJoystick = false;
  107801. }
  107802. VirtualJoystick._globalJoystickIndex++;
  107803. // By default left & right arrow keys are moving the X
  107804. // and up & down keys are moving the Y
  107805. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  107806. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  107807. this.reverseLeftRight = false;
  107808. this.reverseUpDown = false;
  107809. // collections of pointers
  107810. this._touches = new BABYLON.StringDictionary();
  107811. this.deltaPosition = BABYLON.Vector3.Zero();
  107812. this._joystickSensibility = 25;
  107813. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  107814. this._onResize = function (evt) {
  107815. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  107816. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  107817. if (VirtualJoystick.vjCanvas) {
  107818. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  107819. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  107820. }
  107821. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  107822. };
  107823. // injecting a canvas element on top of the canvas 3D game
  107824. if (!VirtualJoystick.vjCanvas) {
  107825. window.addEventListener("resize", this._onResize, false);
  107826. VirtualJoystick.vjCanvas = document.createElement("canvas");
  107827. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  107828. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  107829. VirtualJoystick.vjCanvas.width = window.innerWidth;
  107830. VirtualJoystick.vjCanvas.height = window.innerHeight;
  107831. VirtualJoystick.vjCanvas.style.width = "100%";
  107832. VirtualJoystick.vjCanvas.style.height = "100%";
  107833. VirtualJoystick.vjCanvas.style.position = "absolute";
  107834. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  107835. VirtualJoystick.vjCanvas.style.top = "0px";
  107836. VirtualJoystick.vjCanvas.style.left = "0px";
  107837. VirtualJoystick.vjCanvas.style.zIndex = "5";
  107838. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  107839. // Support for jQuery PEP polyfill
  107840. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  107841. var context = VirtualJoystick.vjCanvas.getContext('2d');
  107842. if (!context) {
  107843. throw new Error("Unable to create canvas for virtual joystick");
  107844. }
  107845. VirtualJoystick.vjCanvasContext = context;
  107846. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  107847. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  107848. document.body.appendChild(VirtualJoystick.vjCanvas);
  107849. }
  107850. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  107851. this.pressed = false;
  107852. // default joystick color
  107853. this._joystickColor = "cyan";
  107854. this._joystickPointerID = -1;
  107855. // current joystick position
  107856. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  107857. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  107858. // origin joystick position
  107859. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  107860. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  107861. this._onPointerDownHandlerRef = function (evt) {
  107862. _this._onPointerDown(evt);
  107863. };
  107864. this._onPointerMoveHandlerRef = function (evt) {
  107865. _this._onPointerMove(evt);
  107866. };
  107867. this._onPointerUpHandlerRef = function (evt) {
  107868. _this._onPointerUp(evt);
  107869. };
  107870. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  107871. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  107872. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  107873. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  107874. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  107875. evt.preventDefault(); // Disables system menu
  107876. }, false);
  107877. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  107878. }
  107879. /**
  107880. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  107881. * @param newJoystickSensibility defines the new sensibility
  107882. */
  107883. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  107884. this._joystickSensibility = newJoystickSensibility;
  107885. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  107886. };
  107887. VirtualJoystick.prototype._onPointerDown = function (e) {
  107888. var positionOnScreenCondition;
  107889. e.preventDefault();
  107890. if (this._leftJoystick === true) {
  107891. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  107892. }
  107893. else {
  107894. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  107895. }
  107896. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  107897. // First contact will be dedicated to the virtual joystick
  107898. this._joystickPointerID = e.pointerId;
  107899. this._joystickPointerStartPos.x = e.clientX;
  107900. this._joystickPointerStartPos.y = e.clientY;
  107901. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  107902. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  107903. this._deltaJoystickVector.x = 0;
  107904. this._deltaJoystickVector.y = 0;
  107905. this.pressed = true;
  107906. this._touches.add(e.pointerId.toString(), e);
  107907. }
  107908. else {
  107909. // You can only trigger the action buttons with a joystick declared
  107910. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  107911. this._action();
  107912. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  107913. }
  107914. }
  107915. };
  107916. VirtualJoystick.prototype._onPointerMove = function (e) {
  107917. // If the current pointer is the one associated to the joystick (first touch contact)
  107918. if (this._joystickPointerID == e.pointerId) {
  107919. this._joystickPointerPos.x = e.clientX;
  107920. this._joystickPointerPos.y = e.clientY;
  107921. this._deltaJoystickVector = this._joystickPointerPos.clone();
  107922. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  107923. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  107924. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  107925. switch (this._axisTargetedByLeftAndRight) {
  107926. case JoystickAxis.X:
  107927. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  107928. break;
  107929. case JoystickAxis.Y:
  107930. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  107931. break;
  107932. case JoystickAxis.Z:
  107933. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  107934. break;
  107935. }
  107936. var directionUpDown = this.reverseUpDown ? 1 : -1;
  107937. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  107938. switch (this._axisTargetedByUpAndDown) {
  107939. case JoystickAxis.X:
  107940. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  107941. break;
  107942. case JoystickAxis.Y:
  107943. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  107944. break;
  107945. case JoystickAxis.Z:
  107946. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  107947. break;
  107948. }
  107949. }
  107950. else {
  107951. var data = this._touches.get(e.pointerId.toString());
  107952. if (data) {
  107953. data.x = e.clientX;
  107954. data.y = e.clientY;
  107955. }
  107956. }
  107957. };
  107958. VirtualJoystick.prototype._onPointerUp = function (e) {
  107959. if (this._joystickPointerID == e.pointerId) {
  107960. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  107961. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  107962. this._joystickPointerID = -1;
  107963. this.pressed = false;
  107964. }
  107965. else {
  107966. var touch = this._touches.get(e.pointerId.toString());
  107967. if (touch) {
  107968. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  107969. }
  107970. }
  107971. this._deltaJoystickVector.x = 0;
  107972. this._deltaJoystickVector.y = 0;
  107973. this._touches.remove(e.pointerId.toString());
  107974. };
  107975. /**
  107976. * Change the color of the virtual joystick
  107977. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  107978. */
  107979. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  107980. this._joystickColor = newColor;
  107981. };
  107982. /**
  107983. * Defines a callback to call when the joystick is touched
  107984. * @param action defines the callback
  107985. */
  107986. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  107987. this._action = action;
  107988. };
  107989. /**
  107990. * Defines which axis you'd like to control for left & right
  107991. * @param axis defines the axis to use
  107992. */
  107993. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  107994. switch (axis) {
  107995. case JoystickAxis.X:
  107996. case JoystickAxis.Y:
  107997. case JoystickAxis.Z:
  107998. this._axisTargetedByLeftAndRight = axis;
  107999. break;
  108000. default:
  108001. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108002. break;
  108003. }
  108004. };
  108005. /**
  108006. * Defines which axis you'd like to control for up & down
  108007. * @param axis defines the axis to use
  108008. */
  108009. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  108010. switch (axis) {
  108011. case JoystickAxis.X:
  108012. case JoystickAxis.Y:
  108013. case JoystickAxis.Z:
  108014. this._axisTargetedByUpAndDown = axis;
  108015. break;
  108016. default:
  108017. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108018. break;
  108019. }
  108020. };
  108021. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  108022. var _this = this;
  108023. if (this.pressed) {
  108024. this._touches.forEach(function (key, touch) {
  108025. if (touch.pointerId === _this._joystickPointerID) {
  108026. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  108027. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  108028. VirtualJoystick.vjCanvasContext.beginPath();
  108029. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108030. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108031. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  108032. VirtualJoystick.vjCanvasContext.stroke();
  108033. VirtualJoystick.vjCanvasContext.closePath();
  108034. VirtualJoystick.vjCanvasContext.beginPath();
  108035. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108036. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  108037. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  108038. VirtualJoystick.vjCanvasContext.stroke();
  108039. VirtualJoystick.vjCanvasContext.closePath();
  108040. VirtualJoystick.vjCanvasContext.beginPath();
  108041. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108042. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  108043. VirtualJoystick.vjCanvasContext.stroke();
  108044. VirtualJoystick.vjCanvasContext.closePath();
  108045. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  108046. }
  108047. else {
  108048. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  108049. VirtualJoystick.vjCanvasContext.beginPath();
  108050. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  108051. VirtualJoystick.vjCanvasContext.beginPath();
  108052. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  108053. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108054. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  108055. VirtualJoystick.vjCanvasContext.stroke();
  108056. VirtualJoystick.vjCanvasContext.closePath();
  108057. touch.prevX = touch.x;
  108058. touch.prevY = touch.y;
  108059. }
  108060. });
  108061. }
  108062. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  108063. };
  108064. /**
  108065. * Release internal HTML canvas
  108066. */
  108067. VirtualJoystick.prototype.releaseCanvas = function () {
  108068. if (VirtualJoystick.vjCanvas) {
  108069. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  108070. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  108071. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  108072. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  108073. window.removeEventListener("resize", this._onResize);
  108074. document.body.removeChild(VirtualJoystick.vjCanvas);
  108075. VirtualJoystick.vjCanvas = null;
  108076. }
  108077. };
  108078. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  108079. VirtualJoystick._globalJoystickIndex = 0;
  108080. return VirtualJoystick;
  108081. }());
  108082. BABYLON.VirtualJoystick = VirtualJoystick;
  108083. })(BABYLON || (BABYLON = {}));
  108084. //# sourceMappingURL=babylon.virtualJoystick.js.map
  108085. var BABYLON;
  108086. (function (BABYLON) {
  108087. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  108088. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  108089. });
  108090. /**
  108091. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  108092. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108093. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108094. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108095. */
  108096. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  108097. __extends(VirtualJoysticksCamera, _super);
  108098. /**
  108099. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  108100. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108101. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108102. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108103. * @param name Define the name of the camera in the scene
  108104. * @param position Define the start position of the camera in the scene
  108105. * @param scene Define the scene the camera belongs to
  108106. */
  108107. function VirtualJoysticksCamera(name, position, scene) {
  108108. var _this = _super.call(this, name, position, scene) || this;
  108109. _this.inputs.addVirtualJoystick();
  108110. return _this;
  108111. }
  108112. /**
  108113. * Gets the current object class name.
  108114. * @return the class name
  108115. */
  108116. VirtualJoysticksCamera.prototype.getClassName = function () {
  108117. return "VirtualJoysticksCamera";
  108118. };
  108119. return VirtualJoysticksCamera;
  108120. }(BABYLON.FreeCamera));
  108121. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  108122. })(BABYLON || (BABYLON = {}));
  108123. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  108124. var BABYLON;
  108125. (function (BABYLON) {
  108126. /**
  108127. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  108128. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  108129. */
  108130. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  108131. function FreeCameraVirtualJoystickInput() {
  108132. }
  108133. /**
  108134. * Gets the left stick of the virtual joystick.
  108135. * @returns The virtual Joystick
  108136. */
  108137. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  108138. return this._leftjoystick;
  108139. };
  108140. /**
  108141. * Gets the right stick of the virtual joystick.
  108142. * @returns The virtual Joystick
  108143. */
  108144. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  108145. return this._rightjoystick;
  108146. };
  108147. /**
  108148. * Update the current camera state depending on the inputs that have been used this frame.
  108149. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  108150. */
  108151. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  108152. if (this._leftjoystick) {
  108153. var camera = this.camera;
  108154. var speed = camera._computeLocalCameraSpeed() * 50;
  108155. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  108156. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  108157. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  108158. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  108159. if (!this._leftjoystick.pressed) {
  108160. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  108161. }
  108162. if (!this._rightjoystick.pressed) {
  108163. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  108164. }
  108165. }
  108166. };
  108167. /**
  108168. * Attach the input controls to a specific dom element to get the input from.
  108169. * @param element Defines the element the controls should be listened from
  108170. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  108171. */
  108172. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  108173. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  108174. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  108175. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  108176. this._leftjoystick.setJoystickSensibility(0.15);
  108177. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  108178. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  108179. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  108180. this._rightjoystick.reverseUpDown = true;
  108181. this._rightjoystick.setJoystickSensibility(0.05);
  108182. this._rightjoystick.setJoystickColor("yellow");
  108183. };
  108184. /**
  108185. * Detach the current controls from the specified dom element.
  108186. * @param element Defines the element to stop listening the inputs from
  108187. */
  108188. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  108189. this._leftjoystick.releaseCanvas();
  108190. this._rightjoystick.releaseCanvas();
  108191. };
  108192. /**
  108193. * Gets the class name of the current intput.
  108194. * @returns the class name
  108195. */
  108196. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  108197. return "FreeCameraVirtualJoystickInput";
  108198. };
  108199. /**
  108200. * Get the friendly name associated with the input class.
  108201. * @returns the input friendly name
  108202. */
  108203. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  108204. return "virtualJoystick";
  108205. };
  108206. return FreeCameraVirtualJoystickInput;
  108207. }());
  108208. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  108209. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  108210. })(BABYLON || (BABYLON = {}));
  108211. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  108212. var BABYLON;
  108213. (function (BABYLON) {
  108214. /**
  108215. * Class used to specify simplification options
  108216. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108217. */
  108218. var SimplificationSettings = /** @class */ (function () {
  108219. /**
  108220. * Creates a SimplificationSettings
  108221. * @param quality expected quality
  108222. * @param distance distance when this optimized version should be used
  108223. * @param optimizeMesh already optimized mesh
  108224. */
  108225. function SimplificationSettings(
  108226. /** expected quality */
  108227. quality,
  108228. /** distance when this optimized version should be used */
  108229. distance,
  108230. /** already optimized mesh */
  108231. optimizeMesh) {
  108232. this.quality = quality;
  108233. this.distance = distance;
  108234. this.optimizeMesh = optimizeMesh;
  108235. }
  108236. return SimplificationSettings;
  108237. }());
  108238. BABYLON.SimplificationSettings = SimplificationSettings;
  108239. /**
  108240. * Queue used to order the simplification tasks
  108241. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108242. */
  108243. var SimplificationQueue = /** @class */ (function () {
  108244. /**
  108245. * Creates a new queue
  108246. */
  108247. function SimplificationQueue() {
  108248. this.running = false;
  108249. this._simplificationArray = [];
  108250. }
  108251. /**
  108252. * Adds a new simplification task
  108253. * @param task defines a task to add
  108254. */
  108255. SimplificationQueue.prototype.addTask = function (task) {
  108256. this._simplificationArray.push(task);
  108257. };
  108258. /**
  108259. * Execute next task
  108260. */
  108261. SimplificationQueue.prototype.executeNext = function () {
  108262. var task = this._simplificationArray.pop();
  108263. if (task) {
  108264. this.running = true;
  108265. this.runSimplification(task);
  108266. }
  108267. else {
  108268. this.running = false;
  108269. }
  108270. };
  108271. /**
  108272. * Execute a simplification task
  108273. * @param task defines the task to run
  108274. */
  108275. SimplificationQueue.prototype.runSimplification = function (task) {
  108276. var _this = this;
  108277. if (task.parallelProcessing) {
  108278. //parallel simplifier
  108279. task.settings.forEach(function (setting) {
  108280. var simplifier = _this.getSimplifier(task);
  108281. simplifier.simplify(setting, function (newMesh) {
  108282. task.mesh.addLODLevel(setting.distance, newMesh);
  108283. newMesh.isVisible = true;
  108284. //check if it is the last
  108285. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  108286. //all done, run the success callback.
  108287. task.successCallback();
  108288. }
  108289. _this.executeNext();
  108290. });
  108291. });
  108292. }
  108293. else {
  108294. //single simplifier.
  108295. var simplifier = this.getSimplifier(task);
  108296. var runDecimation = function (setting, callback) {
  108297. simplifier.simplify(setting, function (newMesh) {
  108298. task.mesh.addLODLevel(setting.distance, newMesh);
  108299. newMesh.isVisible = true;
  108300. //run the next quality level
  108301. callback();
  108302. });
  108303. };
  108304. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  108305. runDecimation(task.settings[loop.index], function () {
  108306. loop.executeNext();
  108307. });
  108308. }, function () {
  108309. //execution ended, run the success callback.
  108310. if (task.successCallback) {
  108311. task.successCallback();
  108312. }
  108313. _this.executeNext();
  108314. });
  108315. }
  108316. };
  108317. SimplificationQueue.prototype.getSimplifier = function (task) {
  108318. switch (task.simplificationType) {
  108319. case SimplificationType.QUADRATIC:
  108320. default:
  108321. return new QuadraticErrorSimplification(task.mesh);
  108322. }
  108323. };
  108324. return SimplificationQueue;
  108325. }());
  108326. BABYLON.SimplificationQueue = SimplificationQueue;
  108327. /**
  108328. * The implemented types of simplification
  108329. * At the moment only Quadratic Error Decimation is implemented
  108330. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108331. */
  108332. var SimplificationType;
  108333. (function (SimplificationType) {
  108334. /** Quadratic error decimation */
  108335. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  108336. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  108337. var DecimationTriangle = /** @class */ (function () {
  108338. function DecimationTriangle(vertices) {
  108339. this.vertices = vertices;
  108340. this.error = new Array(4);
  108341. this.deleted = false;
  108342. this.isDirty = false;
  108343. this.deletePending = false;
  108344. this.borderFactor = 0;
  108345. }
  108346. return DecimationTriangle;
  108347. }());
  108348. var DecimationVertex = /** @class */ (function () {
  108349. function DecimationVertex(position, id) {
  108350. this.position = position;
  108351. this.id = id;
  108352. this.isBorder = true;
  108353. this.q = new QuadraticMatrix();
  108354. this.triangleCount = 0;
  108355. this.triangleStart = 0;
  108356. this.originalOffsets = [];
  108357. }
  108358. DecimationVertex.prototype.updatePosition = function (newPosition) {
  108359. this.position.copyFrom(newPosition);
  108360. };
  108361. return DecimationVertex;
  108362. }());
  108363. var QuadraticMatrix = /** @class */ (function () {
  108364. function QuadraticMatrix(data) {
  108365. this.data = new Array(10);
  108366. for (var i = 0; i < 10; ++i) {
  108367. if (data && data[i]) {
  108368. this.data[i] = data[i];
  108369. }
  108370. else {
  108371. this.data[i] = 0;
  108372. }
  108373. }
  108374. }
  108375. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  108376. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  108377. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  108378. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  108379. return det;
  108380. };
  108381. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  108382. for (var i = 0; i < 10; ++i) {
  108383. this.data[i] += matrix.data[i];
  108384. }
  108385. };
  108386. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  108387. for (var i = 0; i < 10; ++i) {
  108388. this.data[i] += data[i];
  108389. }
  108390. };
  108391. QuadraticMatrix.prototype.add = function (matrix) {
  108392. var m = new QuadraticMatrix();
  108393. for (var i = 0; i < 10; ++i) {
  108394. m.data[i] = this.data[i] + matrix.data[i];
  108395. }
  108396. return m;
  108397. };
  108398. QuadraticMatrix.FromData = function (a, b, c, d) {
  108399. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  108400. };
  108401. //returning an array to avoid garbage collection
  108402. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  108403. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  108404. };
  108405. return QuadraticMatrix;
  108406. }());
  108407. var Reference = /** @class */ (function () {
  108408. function Reference(vertexId, triangleId) {
  108409. this.vertexId = vertexId;
  108410. this.triangleId = triangleId;
  108411. }
  108412. return Reference;
  108413. }());
  108414. /**
  108415. * An implementation of the Quadratic Error simplification algorithm.
  108416. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  108417. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  108418. * @author RaananW
  108419. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108420. */
  108421. var QuadraticErrorSimplification = /** @class */ (function () {
  108422. function QuadraticErrorSimplification(_mesh) {
  108423. this._mesh = _mesh;
  108424. this.syncIterations = 5000;
  108425. this.aggressiveness = 7;
  108426. this.decimationIterations = 100;
  108427. this.boundingBoxEpsilon = BABYLON.Epsilon;
  108428. }
  108429. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  108430. var _this = this;
  108431. this.initDecimatedMesh();
  108432. //iterating through the submeshes array, one after the other.
  108433. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  108434. _this.initWithMesh(loop.index, function () {
  108435. _this.runDecimation(settings, loop.index, function () {
  108436. loop.executeNext();
  108437. });
  108438. }, settings.optimizeMesh);
  108439. }, function () {
  108440. setTimeout(function () {
  108441. successCallback(_this._reconstructedMesh);
  108442. }, 0);
  108443. });
  108444. };
  108445. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  108446. var _this = this;
  108447. var targetCount = ~~(this.triangles.length * settings.quality);
  108448. var deletedTriangles = 0;
  108449. var triangleCount = this.triangles.length;
  108450. var iterationFunction = function (iteration, callback) {
  108451. setTimeout(function () {
  108452. if (iteration % 5 === 0) {
  108453. _this.updateMesh(iteration === 0);
  108454. }
  108455. for (var i = 0; i < _this.triangles.length; ++i) {
  108456. _this.triangles[i].isDirty = false;
  108457. }
  108458. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  108459. var trianglesIterator = function (i) {
  108460. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  108461. var t = _this.triangles[tIdx];
  108462. if (!t) {
  108463. return;
  108464. }
  108465. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  108466. return;
  108467. }
  108468. for (var j = 0; j < 3; ++j) {
  108469. if (t.error[j] < threshold) {
  108470. var deleted0 = [];
  108471. var deleted1 = [];
  108472. var v0 = t.vertices[j];
  108473. var v1 = t.vertices[(j + 1) % 3];
  108474. if (v0.isBorder || v1.isBorder) {
  108475. continue;
  108476. }
  108477. var p = BABYLON.Vector3.Zero();
  108478. var n = BABYLON.Vector3.Zero();
  108479. var uv = BABYLON.Vector2.Zero();
  108480. var color = new BABYLON.Color4(0, 0, 0, 1);
  108481. _this.calculateError(v0, v1, p, n, uv, color);
  108482. var delTr = new Array();
  108483. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  108484. continue;
  108485. }
  108486. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  108487. continue;
  108488. }
  108489. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  108490. continue;
  108491. }
  108492. var uniqueArray = new Array();
  108493. delTr.forEach(function (deletedT) {
  108494. if (uniqueArray.indexOf(deletedT) === -1) {
  108495. deletedT.deletePending = true;
  108496. uniqueArray.push(deletedT);
  108497. }
  108498. });
  108499. if (uniqueArray.length % 2 !== 0) {
  108500. continue;
  108501. }
  108502. v0.q = v1.q.add(v0.q);
  108503. v0.updatePosition(p);
  108504. var tStart = _this.references.length;
  108505. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  108506. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  108507. var tCount = _this.references.length - tStart;
  108508. if (tCount <= v0.triangleCount) {
  108509. if (tCount) {
  108510. for (var c = 0; c < tCount; c++) {
  108511. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  108512. }
  108513. }
  108514. }
  108515. else {
  108516. v0.triangleStart = tStart;
  108517. }
  108518. v0.triangleCount = tCount;
  108519. break;
  108520. }
  108521. }
  108522. };
  108523. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  108524. }, 0);
  108525. };
  108526. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  108527. if (triangleCount - deletedTriangles <= targetCount) {
  108528. loop.breakLoop();
  108529. }
  108530. else {
  108531. iterationFunction(loop.index, function () {
  108532. loop.executeNext();
  108533. });
  108534. }
  108535. }, function () {
  108536. setTimeout(function () {
  108537. //reconstruct this part of the mesh
  108538. _this.reconstructMesh(submeshIndex);
  108539. successCallback();
  108540. }, 0);
  108541. });
  108542. };
  108543. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  108544. var _this = this;
  108545. this.vertices = [];
  108546. this.triangles = [];
  108547. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108548. var indices = this._mesh.getIndices();
  108549. var submesh = this._mesh.subMeshes[submeshIndex];
  108550. var findInVertices = function (positionToSearch) {
  108551. if (optimizeMesh) {
  108552. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  108553. if (_this.vertices[ii].position.equals(positionToSearch)) {
  108554. return _this.vertices[ii];
  108555. }
  108556. }
  108557. }
  108558. return null;
  108559. };
  108560. var vertexReferences = [];
  108561. var vertexInit = function (i) {
  108562. if (!positionData) {
  108563. return;
  108564. }
  108565. var offset = i + submesh.verticesStart;
  108566. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  108567. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  108568. vertex.originalOffsets.push(offset);
  108569. if (vertex.id === _this.vertices.length) {
  108570. _this.vertices.push(vertex);
  108571. }
  108572. vertexReferences.push(vertex.id);
  108573. };
  108574. //var totalVertices = mesh.getTotalVertices();
  108575. var totalVertices = submesh.verticesCount;
  108576. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  108577. var indicesInit = function (i) {
  108578. if (!indices) {
  108579. return;
  108580. }
  108581. var offset = (submesh.indexStart / 3) + i;
  108582. var pos = (offset * 3);
  108583. var i0 = indices[pos + 0];
  108584. var i1 = indices[pos + 1];
  108585. var i2 = indices[pos + 2];
  108586. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  108587. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  108588. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  108589. var triangle = new DecimationTriangle([v0, v1, v2]);
  108590. triangle.originalOffset = pos;
  108591. _this.triangles.push(triangle);
  108592. };
  108593. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  108594. _this.init(callback);
  108595. });
  108596. });
  108597. };
  108598. QuadraticErrorSimplification.prototype.init = function (callback) {
  108599. var _this = this;
  108600. var triangleInit1 = function (i) {
  108601. var t = _this.triangles[i];
  108602. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  108603. for (var j = 0; j < 3; j++) {
  108604. 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))));
  108605. }
  108606. };
  108607. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  108608. var triangleInit2 = function (i) {
  108609. var t = _this.triangles[i];
  108610. for (var j = 0; j < 3; ++j) {
  108611. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  108612. }
  108613. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  108614. };
  108615. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  108616. callback();
  108617. });
  108618. });
  108619. };
  108620. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  108621. var newTriangles = [];
  108622. var i;
  108623. for (i = 0; i < this.vertices.length; ++i) {
  108624. this.vertices[i].triangleCount = 0;
  108625. }
  108626. var t;
  108627. var j;
  108628. for (i = 0; i < this.triangles.length; ++i) {
  108629. if (!this.triangles[i].deleted) {
  108630. t = this.triangles[i];
  108631. for (j = 0; j < 3; ++j) {
  108632. t.vertices[j].triangleCount = 1;
  108633. }
  108634. newTriangles.push(t);
  108635. }
  108636. }
  108637. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  108638. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  108639. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  108640. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  108641. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  108642. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  108643. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  108644. var vertexCount = 0;
  108645. for (i = 0; i < this.vertices.length; ++i) {
  108646. var vertex = this.vertices[i];
  108647. vertex.id = vertexCount;
  108648. if (vertex.triangleCount) {
  108649. vertex.originalOffsets.forEach(function (originalOffset) {
  108650. if (!normalData) {
  108651. return;
  108652. }
  108653. newPositionData.push(vertex.position.x);
  108654. newPositionData.push(vertex.position.y);
  108655. newPositionData.push(vertex.position.z);
  108656. newNormalData.push(normalData[originalOffset * 3]);
  108657. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  108658. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  108659. if (uvs && uvs.length) {
  108660. newUVsData.push(uvs[(originalOffset * 2)]);
  108661. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  108662. }
  108663. else if (colorsData && colorsData.length) {
  108664. newColorsData.push(colorsData[(originalOffset * 4)]);
  108665. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  108666. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  108667. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  108668. }
  108669. ++vertexCount;
  108670. });
  108671. }
  108672. }
  108673. var startingIndex = this._reconstructedMesh.getTotalIndices();
  108674. var startingVertex = this._reconstructedMesh.getTotalVertices();
  108675. var submeshesArray = this._reconstructedMesh.subMeshes;
  108676. this._reconstructedMesh.subMeshes = [];
  108677. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  108678. var originalIndices = this._mesh.getIndices();
  108679. for (i = 0; i < newTriangles.length; ++i) {
  108680. t = newTriangles[i]; //now get the new referencing point for each vertex
  108681. [0, 1, 2].forEach(function (idx) {
  108682. var id = originalIndices[t.originalOffset + idx];
  108683. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  108684. if (offset < 0) {
  108685. offset = 0;
  108686. }
  108687. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  108688. });
  108689. }
  108690. //overwriting the old vertex buffers and indices.
  108691. this._reconstructedMesh.setIndices(newIndicesArray);
  108692. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  108693. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  108694. if (newUVsData.length > 0) {
  108695. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  108696. }
  108697. if (newColorsData.length > 0) {
  108698. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  108699. }
  108700. //create submesh
  108701. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  108702. if (submeshIndex > 0) {
  108703. this._reconstructedMesh.subMeshes = [];
  108704. submeshesArray.forEach(function (submesh) {
  108705. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  108706. });
  108707. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  108708. }
  108709. };
  108710. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  108711. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  108712. this._reconstructedMesh.material = this._mesh.material;
  108713. this._reconstructedMesh.parent = this._mesh.parent;
  108714. this._reconstructedMesh.isVisible = false;
  108715. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  108716. };
  108717. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  108718. for (var i = 0; i < vertex1.triangleCount; ++i) {
  108719. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  108720. if (t.deleted) {
  108721. continue;
  108722. }
  108723. var s = this.references[vertex1.triangleStart + i].vertexId;
  108724. var v1 = t.vertices[(s + 1) % 3];
  108725. var v2 = t.vertices[(s + 2) % 3];
  108726. if ((v1 === vertex2 || v2 === vertex2)) {
  108727. deletedArray[i] = true;
  108728. delTr.push(t);
  108729. continue;
  108730. }
  108731. var d1 = v1.position.subtract(point);
  108732. d1 = d1.normalize();
  108733. var d2 = v2.position.subtract(point);
  108734. d2 = d2.normalize();
  108735. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  108736. return true;
  108737. }
  108738. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  108739. deletedArray[i] = false;
  108740. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  108741. return true;
  108742. }
  108743. }
  108744. return false;
  108745. };
  108746. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  108747. var newDeleted = deletedTriangles;
  108748. for (var i = 0; i < vertex.triangleCount; ++i) {
  108749. var ref = this.references[vertex.triangleStart + i];
  108750. var t = this.triangles[ref.triangleId];
  108751. if (t.deleted) {
  108752. continue;
  108753. }
  108754. if (deletedArray[i] && t.deletePending) {
  108755. t.deleted = true;
  108756. newDeleted++;
  108757. continue;
  108758. }
  108759. t.vertices[ref.vertexId] = origVertex;
  108760. t.isDirty = true;
  108761. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  108762. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  108763. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  108764. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  108765. this.references.push(ref);
  108766. }
  108767. return newDeleted;
  108768. };
  108769. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  108770. for (var i = 0; i < this.vertices.length; ++i) {
  108771. var vCount = [];
  108772. var vId = [];
  108773. var v = this.vertices[i];
  108774. var j;
  108775. for (j = 0; j < v.triangleCount; ++j) {
  108776. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  108777. for (var ii = 0; ii < 3; ii++) {
  108778. var ofs = 0;
  108779. var vv = triangle.vertices[ii];
  108780. while (ofs < vCount.length) {
  108781. if (vId[ofs] === vv.id) {
  108782. break;
  108783. }
  108784. ++ofs;
  108785. }
  108786. if (ofs === vCount.length) {
  108787. vCount.push(1);
  108788. vId.push(vv.id);
  108789. }
  108790. else {
  108791. vCount[ofs]++;
  108792. }
  108793. }
  108794. }
  108795. for (j = 0; j < vCount.length; ++j) {
  108796. if (vCount[j] === 1) {
  108797. this.vertices[vId[j]].isBorder = true;
  108798. }
  108799. else {
  108800. this.vertices[vId[j]].isBorder = false;
  108801. }
  108802. }
  108803. }
  108804. };
  108805. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  108806. if (identifyBorders === void 0) { identifyBorders = false; }
  108807. var i;
  108808. if (!identifyBorders) {
  108809. var newTrianglesVector = [];
  108810. for (i = 0; i < this.triangles.length; ++i) {
  108811. if (!this.triangles[i].deleted) {
  108812. newTrianglesVector.push(this.triangles[i]);
  108813. }
  108814. }
  108815. this.triangles = newTrianglesVector;
  108816. }
  108817. for (i = 0; i < this.vertices.length; ++i) {
  108818. this.vertices[i].triangleCount = 0;
  108819. this.vertices[i].triangleStart = 0;
  108820. }
  108821. var t;
  108822. var j;
  108823. var v;
  108824. for (i = 0; i < this.triangles.length; ++i) {
  108825. t = this.triangles[i];
  108826. for (j = 0; j < 3; ++j) {
  108827. v = t.vertices[j];
  108828. v.triangleCount++;
  108829. }
  108830. }
  108831. var tStart = 0;
  108832. for (i = 0; i < this.vertices.length; ++i) {
  108833. this.vertices[i].triangleStart = tStart;
  108834. tStart += this.vertices[i].triangleCount;
  108835. this.vertices[i].triangleCount = 0;
  108836. }
  108837. var newReferences = new Array(this.triangles.length * 3);
  108838. for (i = 0; i < this.triangles.length; ++i) {
  108839. t = this.triangles[i];
  108840. for (j = 0; j < 3; ++j) {
  108841. v = t.vertices[j];
  108842. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  108843. v.triangleCount++;
  108844. }
  108845. }
  108846. this.references = newReferences;
  108847. if (identifyBorders) {
  108848. this.identifyBorder();
  108849. }
  108850. };
  108851. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  108852. var x = point.x;
  108853. var y = point.y;
  108854. var z = point.z;
  108855. 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
  108856. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  108857. };
  108858. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  108859. var q = vertex1.q.add(vertex2.q);
  108860. var border = vertex1.isBorder && vertex2.isBorder;
  108861. var error = 0;
  108862. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  108863. if (qDet !== 0 && !border) {
  108864. if (!pointResult) {
  108865. pointResult = BABYLON.Vector3.Zero();
  108866. }
  108867. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  108868. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  108869. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  108870. error = this.vertexError(q, pointResult);
  108871. }
  108872. else {
  108873. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  108874. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  108875. var error1 = this.vertexError(q, vertex1.position);
  108876. var error2 = this.vertexError(q, vertex2.position);
  108877. var error3 = this.vertexError(q, p3);
  108878. error = Math.min(error1, error2, error3);
  108879. if (error === error1) {
  108880. if (pointResult) {
  108881. pointResult.copyFrom(vertex1.position);
  108882. }
  108883. }
  108884. else if (error === error2) {
  108885. if (pointResult) {
  108886. pointResult.copyFrom(vertex2.position);
  108887. }
  108888. }
  108889. else {
  108890. if (pointResult) {
  108891. pointResult.copyFrom(p3);
  108892. }
  108893. }
  108894. }
  108895. return error;
  108896. };
  108897. return QuadraticErrorSimplification;
  108898. }());
  108899. })(BABYLON || (BABYLON = {}));
  108900. //# sourceMappingURL=babylon.meshSimplification.js.map
  108901. var BABYLON;
  108902. (function (BABYLON) {
  108903. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  108904. get: function () {
  108905. if (!this._simplificationQueue) {
  108906. this._simplificationQueue = new BABYLON.SimplificationQueue();
  108907. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  108908. if (!component) {
  108909. component = new SimplicationQueueSceneComponent(this);
  108910. this._addComponent(component);
  108911. }
  108912. }
  108913. return this._simplificationQueue;
  108914. },
  108915. set: function (value) {
  108916. this._simplificationQueue = value;
  108917. },
  108918. enumerable: true,
  108919. configurable: true
  108920. });
  108921. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  108922. if (parallelProcessing === void 0) { parallelProcessing = true; }
  108923. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  108924. this.getScene().simplificationQueue.addTask({
  108925. settings: settings,
  108926. parallelProcessing: parallelProcessing,
  108927. mesh: this,
  108928. simplificationType: simplificationType,
  108929. successCallback: successCallback
  108930. });
  108931. return this;
  108932. };
  108933. /**
  108934. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  108935. * created in a scene
  108936. */
  108937. var SimplicationQueueSceneComponent = /** @class */ (function () {
  108938. /**
  108939. * Creates a new instance of the component for the given scene
  108940. * @param scene Defines the scene to register the component in
  108941. */
  108942. function SimplicationQueueSceneComponent(scene) {
  108943. /**
  108944. * The component name helpfull to identify the component in the list of scene components.
  108945. */
  108946. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  108947. this.scene = scene;
  108948. }
  108949. /**
  108950. * Registers the component in a given scene
  108951. */
  108952. SimplicationQueueSceneComponent.prototype.register = function () {
  108953. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  108954. };
  108955. /**
  108956. * Rebuilds the elements related to this component in case of
  108957. * context lost for instance.
  108958. */
  108959. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  108960. // Nothing to do for this component
  108961. };
  108962. /**
  108963. * Disposes the component and the associated ressources
  108964. */
  108965. SimplicationQueueSceneComponent.prototype.dispose = function () {
  108966. // Nothing to do for this component
  108967. };
  108968. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  108969. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  108970. this.scene._simplificationQueue.executeNext();
  108971. }
  108972. };
  108973. return SimplicationQueueSceneComponent;
  108974. }());
  108975. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  108976. })(BABYLON || (BABYLON = {}));
  108977. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  108978. var BABYLON;
  108979. (function (BABYLON) {
  108980. /**
  108981. * Class used to represent a specific level of detail of a mesh
  108982. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  108983. */
  108984. var MeshLODLevel = /** @class */ (function () {
  108985. /**
  108986. * Creates a new LOD level
  108987. * @param distance defines the distance where this level should star being displayed
  108988. * @param mesh defines the mesh to use to render this level
  108989. */
  108990. function MeshLODLevel(
  108991. /** Defines the distance where this level should star being displayed */
  108992. distance,
  108993. /** Defines the mesh to use to render this level */
  108994. mesh) {
  108995. this.distance = distance;
  108996. this.mesh = mesh;
  108997. }
  108998. return MeshLODLevel;
  108999. }());
  109000. BABYLON.MeshLODLevel = MeshLODLevel;
  109001. })(BABYLON || (BABYLON = {}));
  109002. //# sourceMappingURL=babylon.meshLODLevel.js.map
  109003. var BABYLON;
  109004. (function (BABYLON) {
  109005. /**
  109006. * Defines the root class used to create scene optimization to use with SceneOptimizer
  109007. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109008. */
  109009. var SceneOptimization = /** @class */ (function () {
  109010. /**
  109011. * Creates the SceneOptimization object
  109012. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109013. * @param desc defines the description associated with the optimization
  109014. */
  109015. function SceneOptimization(
  109016. /**
  109017. * Defines the priority of this optimization (0 by default which means first in the list)
  109018. */
  109019. priority) {
  109020. if (priority === void 0) { priority = 0; }
  109021. this.priority = priority;
  109022. }
  109023. /**
  109024. * Gets a string describing the action executed by the current optimization
  109025. * @returns description string
  109026. */
  109027. SceneOptimization.prototype.getDescription = function () {
  109028. return "";
  109029. };
  109030. /**
  109031. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109032. * @param scene defines the current scene where to apply this optimization
  109033. * @param optimizer defines the current optimizer
  109034. * @returns true if everything that can be done was applied
  109035. */
  109036. SceneOptimization.prototype.apply = function (scene, optimizer) {
  109037. return true;
  109038. };
  109039. return SceneOptimization;
  109040. }());
  109041. BABYLON.SceneOptimization = SceneOptimization;
  109042. /**
  109043. * Defines an optimization used to reduce the size of render target textures
  109044. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109045. */
  109046. var TextureOptimization = /** @class */ (function (_super) {
  109047. __extends(TextureOptimization, _super);
  109048. /**
  109049. * Creates the TextureOptimization object
  109050. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109051. * @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
  109052. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109053. */
  109054. function TextureOptimization(
  109055. /**
  109056. * Defines the priority of this optimization (0 by default which means first in the list)
  109057. */
  109058. priority,
  109059. /**
  109060. * 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
  109061. */
  109062. maximumSize,
  109063. /**
  109064. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109065. */
  109066. step) {
  109067. if (priority === void 0) { priority = 0; }
  109068. if (maximumSize === void 0) { maximumSize = 1024; }
  109069. if (step === void 0) { step = 0.5; }
  109070. var _this = _super.call(this, priority) || this;
  109071. _this.priority = priority;
  109072. _this.maximumSize = maximumSize;
  109073. _this.step = step;
  109074. return _this;
  109075. }
  109076. /**
  109077. * Gets a string describing the action executed by the current optimization
  109078. * @returns description string
  109079. */
  109080. TextureOptimization.prototype.getDescription = function () {
  109081. return "Reducing render target texture size to " + this.maximumSize;
  109082. };
  109083. /**
  109084. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109085. * @param scene defines the current scene where to apply this optimization
  109086. * @param optimizer defines the current optimizer
  109087. * @returns true if everything that can be done was applied
  109088. */
  109089. TextureOptimization.prototype.apply = function (scene, optimizer) {
  109090. var allDone = true;
  109091. for (var index = 0; index < scene.textures.length; index++) {
  109092. var texture = scene.textures[index];
  109093. if (!texture.canRescale || texture.getContext) {
  109094. continue;
  109095. }
  109096. var currentSize = texture.getSize();
  109097. var maxDimension = Math.max(currentSize.width, currentSize.height);
  109098. if (maxDimension > this.maximumSize) {
  109099. texture.scale(this.step);
  109100. allDone = false;
  109101. }
  109102. }
  109103. return allDone;
  109104. };
  109105. return TextureOptimization;
  109106. }(SceneOptimization));
  109107. BABYLON.TextureOptimization = TextureOptimization;
  109108. /**
  109109. * Defines an optimization used to increase or decrease the rendering resolution
  109110. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109111. */
  109112. var HardwareScalingOptimization = /** @class */ (function (_super) {
  109113. __extends(HardwareScalingOptimization, _super);
  109114. /**
  109115. * Creates the HardwareScalingOptimization object
  109116. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109117. * @param maximumScale defines the maximum scale to use (2 by default)
  109118. * @param step defines the step to use between two passes (0.5 by default)
  109119. */
  109120. function HardwareScalingOptimization(
  109121. /**
  109122. * Defines the priority of this optimization (0 by default which means first in the list)
  109123. */
  109124. priority,
  109125. /**
  109126. * Defines the maximum scale to use (2 by default)
  109127. */
  109128. maximumScale,
  109129. /**
  109130. * Defines the step to use between two passes (0.5 by default)
  109131. */
  109132. step) {
  109133. if (priority === void 0) { priority = 0; }
  109134. if (maximumScale === void 0) { maximumScale = 2; }
  109135. if (step === void 0) { step = 0.25; }
  109136. var _this = _super.call(this, priority) || this;
  109137. _this.priority = priority;
  109138. _this.maximumScale = maximumScale;
  109139. _this.step = step;
  109140. _this._currentScale = -1;
  109141. _this._directionOffset = 1;
  109142. return _this;
  109143. }
  109144. /**
  109145. * Gets a string describing the action executed by the current optimization
  109146. * @return description string
  109147. */
  109148. HardwareScalingOptimization.prototype.getDescription = function () {
  109149. return "Setting hardware scaling level to " + this._currentScale;
  109150. };
  109151. /**
  109152. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109153. * @param scene defines the current scene where to apply this optimization
  109154. * @param optimizer defines the current optimizer
  109155. * @returns true if everything that can be done was applied
  109156. */
  109157. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  109158. if (this._currentScale === -1) {
  109159. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  109160. if (this._currentScale > this.maximumScale) {
  109161. this._directionOffset = -1;
  109162. }
  109163. }
  109164. this._currentScale += this._directionOffset * this.step;
  109165. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  109166. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  109167. };
  109168. return HardwareScalingOptimization;
  109169. }(SceneOptimization));
  109170. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  109171. /**
  109172. * Defines an optimization used to remove shadows
  109173. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109174. */
  109175. var ShadowsOptimization = /** @class */ (function (_super) {
  109176. __extends(ShadowsOptimization, _super);
  109177. function ShadowsOptimization() {
  109178. return _super !== null && _super.apply(this, arguments) || this;
  109179. }
  109180. /**
  109181. * Gets a string describing the action executed by the current optimization
  109182. * @return description string
  109183. */
  109184. ShadowsOptimization.prototype.getDescription = function () {
  109185. return "Turning shadows on/off";
  109186. };
  109187. /**
  109188. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109189. * @param scene defines the current scene where to apply this optimization
  109190. * @param optimizer defines the current optimizer
  109191. * @returns true if everything that can be done was applied
  109192. */
  109193. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  109194. scene.shadowsEnabled = optimizer.isInImprovementMode;
  109195. return true;
  109196. };
  109197. return ShadowsOptimization;
  109198. }(SceneOptimization));
  109199. BABYLON.ShadowsOptimization = ShadowsOptimization;
  109200. /**
  109201. * Defines an optimization used to turn post-processes off
  109202. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109203. */
  109204. var PostProcessesOptimization = /** @class */ (function (_super) {
  109205. __extends(PostProcessesOptimization, _super);
  109206. function PostProcessesOptimization() {
  109207. return _super !== null && _super.apply(this, arguments) || this;
  109208. }
  109209. /**
  109210. * Gets a string describing the action executed by the current optimization
  109211. * @return description string
  109212. */
  109213. PostProcessesOptimization.prototype.getDescription = function () {
  109214. return "Turning post-processes on/off";
  109215. };
  109216. /**
  109217. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109218. * @param scene defines the current scene where to apply this optimization
  109219. * @param optimizer defines the current optimizer
  109220. * @returns true if everything that can be done was applied
  109221. */
  109222. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  109223. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  109224. return true;
  109225. };
  109226. return PostProcessesOptimization;
  109227. }(SceneOptimization));
  109228. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  109229. /**
  109230. * Defines an optimization used to turn lens flares off
  109231. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109232. */
  109233. var LensFlaresOptimization = /** @class */ (function (_super) {
  109234. __extends(LensFlaresOptimization, _super);
  109235. function LensFlaresOptimization() {
  109236. return _super !== null && _super.apply(this, arguments) || this;
  109237. }
  109238. /**
  109239. * Gets a string describing the action executed by the current optimization
  109240. * @return description string
  109241. */
  109242. LensFlaresOptimization.prototype.getDescription = function () {
  109243. return "Turning lens flares on/off";
  109244. };
  109245. /**
  109246. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109247. * @param scene defines the current scene where to apply this optimization
  109248. * @param optimizer defines the current optimizer
  109249. * @returns true if everything that can be done was applied
  109250. */
  109251. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  109252. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  109253. return true;
  109254. };
  109255. return LensFlaresOptimization;
  109256. }(SceneOptimization));
  109257. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  109258. /**
  109259. * Defines an optimization based on user defined callback.
  109260. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109261. */
  109262. var CustomOptimization = /** @class */ (function (_super) {
  109263. __extends(CustomOptimization, _super);
  109264. function CustomOptimization() {
  109265. return _super !== null && _super.apply(this, arguments) || this;
  109266. }
  109267. /**
  109268. * Gets a string describing the action executed by the current optimization
  109269. * @returns description string
  109270. */
  109271. CustomOptimization.prototype.getDescription = function () {
  109272. if (this.onGetDescription) {
  109273. return this.onGetDescription();
  109274. }
  109275. return "Running user defined callback";
  109276. };
  109277. /**
  109278. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109279. * @param scene defines the current scene where to apply this optimization
  109280. * @param optimizer defines the current optimizer
  109281. * @returns true if everything that can be done was applied
  109282. */
  109283. CustomOptimization.prototype.apply = function (scene, optimizer) {
  109284. if (this.onApply) {
  109285. return this.onApply(scene, optimizer);
  109286. }
  109287. return true;
  109288. };
  109289. return CustomOptimization;
  109290. }(SceneOptimization));
  109291. BABYLON.CustomOptimization = CustomOptimization;
  109292. /**
  109293. * Defines an optimization used to turn particles off
  109294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109295. */
  109296. var ParticlesOptimization = /** @class */ (function (_super) {
  109297. __extends(ParticlesOptimization, _super);
  109298. function ParticlesOptimization() {
  109299. return _super !== null && _super.apply(this, arguments) || this;
  109300. }
  109301. /**
  109302. * Gets a string describing the action executed by the current optimization
  109303. * @return description string
  109304. */
  109305. ParticlesOptimization.prototype.getDescription = function () {
  109306. return "Turning particles on/off";
  109307. };
  109308. /**
  109309. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109310. * @param scene defines the current scene where to apply this optimization
  109311. * @param optimizer defines the current optimizer
  109312. * @returns true if everything that can be done was applied
  109313. */
  109314. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  109315. scene.particlesEnabled = optimizer.isInImprovementMode;
  109316. return true;
  109317. };
  109318. return ParticlesOptimization;
  109319. }(SceneOptimization));
  109320. BABYLON.ParticlesOptimization = ParticlesOptimization;
  109321. /**
  109322. * Defines an optimization used to turn render targets off
  109323. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109324. */
  109325. var RenderTargetsOptimization = /** @class */ (function (_super) {
  109326. __extends(RenderTargetsOptimization, _super);
  109327. function RenderTargetsOptimization() {
  109328. return _super !== null && _super.apply(this, arguments) || this;
  109329. }
  109330. /**
  109331. * Gets a string describing the action executed by the current optimization
  109332. * @return description string
  109333. */
  109334. RenderTargetsOptimization.prototype.getDescription = function () {
  109335. return "Turning render targets off";
  109336. };
  109337. /**
  109338. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109339. * @param scene defines the current scene where to apply this optimization
  109340. * @param optimizer defines the current optimizer
  109341. * @returns true if everything that can be done was applied
  109342. */
  109343. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  109344. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  109345. return true;
  109346. };
  109347. return RenderTargetsOptimization;
  109348. }(SceneOptimization));
  109349. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  109350. /**
  109351. * Defines an optimization used to merge meshes with compatible materials
  109352. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109353. */
  109354. var MergeMeshesOptimization = /** @class */ (function (_super) {
  109355. __extends(MergeMeshesOptimization, _super);
  109356. function MergeMeshesOptimization() {
  109357. var _this = _super !== null && _super.apply(this, arguments) || this;
  109358. _this._canBeMerged = function (abstractMesh) {
  109359. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  109360. return false;
  109361. }
  109362. var mesh = abstractMesh;
  109363. if (mesh.isDisposed()) {
  109364. return false;
  109365. }
  109366. if (!mesh.isVisible || !mesh.isEnabled()) {
  109367. return false;
  109368. }
  109369. if (mesh.instances.length > 0) {
  109370. return false;
  109371. }
  109372. if (mesh.skeleton || mesh.hasLODLevels) {
  109373. return false;
  109374. }
  109375. return true;
  109376. };
  109377. return _this;
  109378. }
  109379. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  109380. /**
  109381. * Gets or sets a boolean which defines if optimization octree has to be updated
  109382. */
  109383. get: function () {
  109384. return MergeMeshesOptimization._UpdateSelectionTree;
  109385. },
  109386. /**
  109387. * Gets or sets a boolean which defines if optimization octree has to be updated
  109388. */
  109389. set: function (value) {
  109390. MergeMeshesOptimization._UpdateSelectionTree = value;
  109391. },
  109392. enumerable: true,
  109393. configurable: true
  109394. });
  109395. /**
  109396. * Gets a string describing the action executed by the current optimization
  109397. * @return description string
  109398. */
  109399. MergeMeshesOptimization.prototype.getDescription = function () {
  109400. return "Merging similar meshes together";
  109401. };
  109402. /**
  109403. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109404. * @param scene defines the current scene where to apply this optimization
  109405. * @param optimizer defines the current optimizer
  109406. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  109407. * @returns true if everything that can be done was applied
  109408. */
  109409. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  109410. var globalPool = scene.meshes.slice(0);
  109411. var globalLength = globalPool.length;
  109412. for (var index = 0; index < globalLength; index++) {
  109413. var currentPool = new Array();
  109414. var current = globalPool[index];
  109415. // Checks
  109416. if (!this._canBeMerged(current)) {
  109417. continue;
  109418. }
  109419. currentPool.push(current);
  109420. // Find compatible meshes
  109421. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  109422. var otherMesh = globalPool[subIndex];
  109423. if (!this._canBeMerged(otherMesh)) {
  109424. continue;
  109425. }
  109426. if (otherMesh.material !== current.material) {
  109427. continue;
  109428. }
  109429. if (otherMesh.checkCollisions !== current.checkCollisions) {
  109430. continue;
  109431. }
  109432. currentPool.push(otherMesh);
  109433. globalLength--;
  109434. globalPool.splice(subIndex, 1);
  109435. subIndex--;
  109436. }
  109437. if (currentPool.length < 2) {
  109438. continue;
  109439. }
  109440. // Merge meshes
  109441. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  109442. }
  109443. // Call the octree system optimization if it is defined.
  109444. var sceneAsAny = scene;
  109445. if (sceneAsAny.createOrUpdateSelectionOctree) {
  109446. if (updateSelectionTree != undefined) {
  109447. if (updateSelectionTree) {
  109448. sceneAsAny.createOrUpdateSelectionOctree();
  109449. }
  109450. }
  109451. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  109452. sceneAsAny.createOrUpdateSelectionOctree();
  109453. }
  109454. }
  109455. return true;
  109456. };
  109457. MergeMeshesOptimization._UpdateSelectionTree = false;
  109458. return MergeMeshesOptimization;
  109459. }(SceneOptimization));
  109460. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  109461. /**
  109462. * Defines a list of options used by SceneOptimizer
  109463. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109464. */
  109465. var SceneOptimizerOptions = /** @class */ (function () {
  109466. /**
  109467. * Creates a new list of options used by SceneOptimizer
  109468. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  109469. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  109470. */
  109471. function SceneOptimizerOptions(
  109472. /**
  109473. * Defines the target frame rate to reach (60 by default)
  109474. */
  109475. targetFrameRate,
  109476. /**
  109477. * Defines the interval between two checkes (2000ms by default)
  109478. */
  109479. trackerDuration) {
  109480. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  109481. if (trackerDuration === void 0) { trackerDuration = 2000; }
  109482. this.targetFrameRate = targetFrameRate;
  109483. this.trackerDuration = trackerDuration;
  109484. /**
  109485. * Gets the list of optimizations to apply
  109486. */
  109487. this.optimizations = new Array();
  109488. }
  109489. /**
  109490. * Add a new optimization
  109491. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  109492. * @returns the current SceneOptimizerOptions
  109493. */
  109494. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  109495. this.optimizations.push(optimization);
  109496. return this;
  109497. };
  109498. /**
  109499. * Add a new custom optimization
  109500. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  109501. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  109502. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109503. * @returns the current SceneOptimizerOptions
  109504. */
  109505. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  109506. if (priority === void 0) { priority = 0; }
  109507. var optimization = new CustomOptimization(priority);
  109508. optimization.onApply = onApply;
  109509. optimization.onGetDescription = onGetDescription;
  109510. this.optimizations.push(optimization);
  109511. return this;
  109512. };
  109513. /**
  109514. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  109515. * @param targetFrameRate defines the target frame rate (60 by default)
  109516. * @returns a SceneOptimizerOptions object
  109517. */
  109518. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  109519. var result = new SceneOptimizerOptions(targetFrameRate);
  109520. var priority = 0;
  109521. result.addOptimization(new MergeMeshesOptimization(priority));
  109522. result.addOptimization(new ShadowsOptimization(priority));
  109523. result.addOptimization(new LensFlaresOptimization(priority));
  109524. // Next priority
  109525. priority++;
  109526. result.addOptimization(new PostProcessesOptimization(priority));
  109527. result.addOptimization(new ParticlesOptimization(priority));
  109528. // Next priority
  109529. priority++;
  109530. result.addOptimization(new TextureOptimization(priority, 1024));
  109531. return result;
  109532. };
  109533. /**
  109534. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  109535. * @param targetFrameRate defines the target frame rate (60 by default)
  109536. * @returns a SceneOptimizerOptions object
  109537. */
  109538. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  109539. var result = new SceneOptimizerOptions(targetFrameRate);
  109540. var priority = 0;
  109541. result.addOptimization(new MergeMeshesOptimization(priority));
  109542. result.addOptimization(new ShadowsOptimization(priority));
  109543. result.addOptimization(new LensFlaresOptimization(priority));
  109544. // Next priority
  109545. priority++;
  109546. result.addOptimization(new PostProcessesOptimization(priority));
  109547. result.addOptimization(new ParticlesOptimization(priority));
  109548. // Next priority
  109549. priority++;
  109550. result.addOptimization(new TextureOptimization(priority, 512));
  109551. // Next priority
  109552. priority++;
  109553. result.addOptimization(new RenderTargetsOptimization(priority));
  109554. // Next priority
  109555. priority++;
  109556. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  109557. return result;
  109558. };
  109559. /**
  109560. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  109561. * @param targetFrameRate defines the target frame rate (60 by default)
  109562. * @returns a SceneOptimizerOptions object
  109563. */
  109564. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  109565. var result = new SceneOptimizerOptions(targetFrameRate);
  109566. var priority = 0;
  109567. result.addOptimization(new MergeMeshesOptimization(priority));
  109568. result.addOptimization(new ShadowsOptimization(priority));
  109569. result.addOptimization(new LensFlaresOptimization(priority));
  109570. // Next priority
  109571. priority++;
  109572. result.addOptimization(new PostProcessesOptimization(priority));
  109573. result.addOptimization(new ParticlesOptimization(priority));
  109574. // Next priority
  109575. priority++;
  109576. result.addOptimization(new TextureOptimization(priority, 256));
  109577. // Next priority
  109578. priority++;
  109579. result.addOptimization(new RenderTargetsOptimization(priority));
  109580. // Next priority
  109581. priority++;
  109582. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  109583. return result;
  109584. };
  109585. return SceneOptimizerOptions;
  109586. }());
  109587. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  109588. /**
  109589. * Class used to run optimizations in order to reach a target frame rate
  109590. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109591. */
  109592. var SceneOptimizer = /** @class */ (function () {
  109593. /**
  109594. * Creates a new SceneOptimizer
  109595. * @param scene defines the scene to work on
  109596. * @param options defines the options to use with the SceneOptimizer
  109597. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  109598. * @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)
  109599. */
  109600. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  109601. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  109602. if (improvementMode === void 0) { improvementMode = false; }
  109603. var _this = this;
  109604. this._isRunning = false;
  109605. this._currentPriorityLevel = 0;
  109606. this._targetFrameRate = 60;
  109607. this._trackerDuration = 2000;
  109608. this._currentFrameRate = 0;
  109609. this._improvementMode = false;
  109610. /**
  109611. * Defines an observable called when the optimizer reaches the target frame rate
  109612. */
  109613. this.onSuccessObservable = new BABYLON.Observable();
  109614. /**
  109615. * Defines an observable called when the optimizer enables an optimization
  109616. */
  109617. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  109618. /**
  109619. * Defines an observable called when the optimizer is not able to reach the target frame rate
  109620. */
  109621. this.onFailureObservable = new BABYLON.Observable();
  109622. if (!options) {
  109623. this._options = new SceneOptimizerOptions();
  109624. }
  109625. else {
  109626. this._options = options;
  109627. }
  109628. if (this._options.targetFrameRate) {
  109629. this._targetFrameRate = this._options.targetFrameRate;
  109630. }
  109631. if (this._options.trackerDuration) {
  109632. this._trackerDuration = this._options.trackerDuration;
  109633. }
  109634. if (autoGeneratePriorities) {
  109635. var priority = 0;
  109636. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  109637. var optim = _a[_i];
  109638. optim.priority = priority++;
  109639. }
  109640. }
  109641. this._improvementMode = improvementMode;
  109642. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  109643. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  109644. _this._sceneDisposeObserver = null;
  109645. _this.dispose();
  109646. });
  109647. }
  109648. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  109649. /**
  109650. * Gets a boolean indicating if the optimizer is in improvement mode
  109651. */
  109652. get: function () {
  109653. return this._improvementMode;
  109654. },
  109655. enumerable: true,
  109656. configurable: true
  109657. });
  109658. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  109659. /**
  109660. * Gets the current priority level (0 at start)
  109661. */
  109662. get: function () {
  109663. return this._currentPriorityLevel;
  109664. },
  109665. enumerable: true,
  109666. configurable: true
  109667. });
  109668. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  109669. /**
  109670. * Gets the current frame rate checked by the SceneOptimizer
  109671. */
  109672. get: function () {
  109673. return this._currentFrameRate;
  109674. },
  109675. enumerable: true,
  109676. configurable: true
  109677. });
  109678. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  109679. /**
  109680. * Gets or sets the current target frame rate (60 by default)
  109681. */
  109682. get: function () {
  109683. return this._targetFrameRate;
  109684. },
  109685. /**
  109686. * Gets or sets the current target frame rate (60 by default)
  109687. */
  109688. set: function (value) {
  109689. this._targetFrameRate = value;
  109690. },
  109691. enumerable: true,
  109692. configurable: true
  109693. });
  109694. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  109695. /**
  109696. * Gets or sets the current interval between two checks (every 2000ms by default)
  109697. */
  109698. get: function () {
  109699. return this._trackerDuration;
  109700. },
  109701. /**
  109702. * Gets or sets the current interval between two checks (every 2000ms by default)
  109703. */
  109704. set: function (value) {
  109705. this._trackerDuration = value;
  109706. },
  109707. enumerable: true,
  109708. configurable: true
  109709. });
  109710. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  109711. /**
  109712. * Gets the list of active optimizations
  109713. */
  109714. get: function () {
  109715. return this._options.optimizations;
  109716. },
  109717. enumerable: true,
  109718. configurable: true
  109719. });
  109720. /**
  109721. * Stops the current optimizer
  109722. */
  109723. SceneOptimizer.prototype.stop = function () {
  109724. this._isRunning = false;
  109725. };
  109726. /**
  109727. * Reset the optimizer to initial step (current priority level = 0)
  109728. */
  109729. SceneOptimizer.prototype.reset = function () {
  109730. this._currentPriorityLevel = 0;
  109731. };
  109732. /**
  109733. * Start the optimizer. By default it will try to reach a specific framerate
  109734. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  109735. */
  109736. SceneOptimizer.prototype.start = function () {
  109737. var _this = this;
  109738. if (this._isRunning) {
  109739. return;
  109740. }
  109741. this._isRunning = true;
  109742. // Let's wait for the scene to be ready before running our check
  109743. this._scene.executeWhenReady(function () {
  109744. setTimeout(function () {
  109745. _this._checkCurrentState();
  109746. }, _this._trackerDuration);
  109747. });
  109748. };
  109749. SceneOptimizer.prototype._checkCurrentState = function () {
  109750. var _this = this;
  109751. if (!this._isRunning) {
  109752. return;
  109753. }
  109754. var scene = this._scene;
  109755. var options = this._options;
  109756. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  109757. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  109758. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  109759. this._isRunning = false;
  109760. this.onSuccessObservable.notifyObservers(this);
  109761. return;
  109762. }
  109763. // Apply current level of optimizations
  109764. var allDone = true;
  109765. var noOptimizationApplied = true;
  109766. for (var index = 0; index < options.optimizations.length; index++) {
  109767. var optimization = options.optimizations[index];
  109768. if (optimization.priority === this._currentPriorityLevel) {
  109769. noOptimizationApplied = false;
  109770. allDone = allDone && optimization.apply(scene, this);
  109771. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  109772. }
  109773. }
  109774. // If no optimization was applied, this is a failure :(
  109775. if (noOptimizationApplied) {
  109776. this._isRunning = false;
  109777. this.onFailureObservable.notifyObservers(this);
  109778. return;
  109779. }
  109780. // If all optimizations were done, move to next level
  109781. if (allDone) {
  109782. this._currentPriorityLevel++;
  109783. }
  109784. // Let's the system running for a specific amount of time before checking FPS
  109785. scene.executeWhenReady(function () {
  109786. setTimeout(function () {
  109787. _this._checkCurrentState();
  109788. }, _this._trackerDuration);
  109789. });
  109790. };
  109791. /**
  109792. * Release all resources
  109793. */
  109794. SceneOptimizer.prototype.dispose = function () {
  109795. this.stop();
  109796. this.onSuccessObservable.clear();
  109797. this.onFailureObservable.clear();
  109798. this.onNewOptimizationAppliedObservable.clear();
  109799. if (this._sceneDisposeObserver) {
  109800. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  109801. }
  109802. };
  109803. /**
  109804. * Helper function to create a SceneOptimizer with one single line of code
  109805. * @param scene defines the scene to work on
  109806. * @param options defines the options to use with the SceneOptimizer
  109807. * @param onSuccess defines a callback to call on success
  109808. * @param onFailure defines a callback to call on failure
  109809. * @returns the new SceneOptimizer object
  109810. */
  109811. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  109812. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  109813. if (onSuccess) {
  109814. optimizer.onSuccessObservable.add(function () {
  109815. onSuccess();
  109816. });
  109817. }
  109818. if (onFailure) {
  109819. optimizer.onFailureObservable.add(function () {
  109820. onFailure();
  109821. });
  109822. }
  109823. optimizer.start();
  109824. return optimizer;
  109825. };
  109826. return SceneOptimizer;
  109827. }());
  109828. BABYLON.SceneOptimizer = SceneOptimizer;
  109829. })(BABYLON || (BABYLON = {}));
  109830. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  109831. var BABYLON;
  109832. (function (BABYLON) {
  109833. /**
  109834. * Gets the outline renderer associated with the scene
  109835. * @returns a OutlineRenderer
  109836. */
  109837. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  109838. if (!this._outlineRenderer) {
  109839. this._outlineRenderer = new OutlineRenderer(this);
  109840. }
  109841. return this._outlineRenderer;
  109842. };
  109843. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  109844. get: function () {
  109845. return this._renderOutline;
  109846. },
  109847. set: function (value) {
  109848. if (value) {
  109849. // Lazy Load the component.
  109850. this.getScene().getOutlineRenderer();
  109851. }
  109852. this._renderOutline = value;
  109853. },
  109854. enumerable: true,
  109855. configurable: true
  109856. });
  109857. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  109858. get: function () {
  109859. return this._renderOverlay;
  109860. },
  109861. set: function (value) {
  109862. if (value) {
  109863. // Lazy Load the component.
  109864. this.getScene().getOutlineRenderer();
  109865. }
  109866. this._renderOverlay = value;
  109867. },
  109868. enumerable: true,
  109869. configurable: true
  109870. });
  109871. /**
  109872. * This class is responsible to draw bothe outline/overlay of meshes.
  109873. * It should not be used directly but through the available method on mesh.
  109874. */
  109875. var OutlineRenderer = /** @class */ (function () {
  109876. /**
  109877. * Instantiates a new outline renderer. (There could be only one per scene).
  109878. * @param scene Defines the scene it belongs to
  109879. */
  109880. function OutlineRenderer(scene) {
  109881. /**
  109882. * The name of the component. Each component must have a unique name.
  109883. */
  109884. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  109885. /**
  109886. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  109887. */
  109888. this.zOffset = 1;
  109889. this.scene = scene;
  109890. this._engine = scene.getEngine();
  109891. this.scene._addComponent(this);
  109892. }
  109893. /**
  109894. * Register the component to one instance of a scene.
  109895. */
  109896. OutlineRenderer.prototype.register = function () {
  109897. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  109898. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  109899. };
  109900. /**
  109901. * Rebuilds the elements related to this component in case of
  109902. * context lost for instance.
  109903. */
  109904. OutlineRenderer.prototype.rebuild = function () {
  109905. // Nothing to do here.
  109906. };
  109907. /**
  109908. * Disposes the component and the associated ressources.
  109909. */
  109910. OutlineRenderer.prototype.dispose = function () {
  109911. // Nothing to do here.
  109912. };
  109913. /**
  109914. * Renders the outline in the canvas.
  109915. * @param subMesh Defines the sumesh to render
  109916. * @param batch Defines the batch of meshes in case of instances
  109917. * @param useOverlay Defines if the rendering is for the overlay or the outline
  109918. */
  109919. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  109920. var _this = this;
  109921. if (useOverlay === void 0) { useOverlay = false; }
  109922. var scene = this.scene;
  109923. var engine = scene.getEngine();
  109924. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109925. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  109926. return;
  109927. }
  109928. var mesh = subMesh.getRenderingMesh();
  109929. var material = subMesh.getMaterial();
  109930. if (!material || !scene.activeCamera) {
  109931. return;
  109932. }
  109933. engine.enableEffect(this._effect);
  109934. // Logarithmic depth
  109935. if (material.useLogarithmicDepth) {
  109936. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  109937. }
  109938. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  109939. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  109940. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  109941. // Bones
  109942. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109943. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109944. }
  109945. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  109946. // Alpha test
  109947. if (material && material.needAlphaTesting()) {
  109948. var alphaTexture = material.getAlphaTestTexture();
  109949. if (alphaTexture) {
  109950. this._effect.setTexture("diffuseSampler", alphaTexture);
  109951. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  109952. }
  109953. }
  109954. engine.setZOffset(-this.zOffset);
  109955. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  109956. engine.setZOffset(0);
  109957. };
  109958. /**
  109959. * Returns whether or not the outline renderer is ready for a given submesh.
  109960. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  109961. * @param subMesh Defines the submesh to check readyness for
  109962. * @param useInstances Defines wheter wee are trying to render instances or not
  109963. * @returns true if ready otherwise false
  109964. */
  109965. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  109966. var defines = [];
  109967. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  109968. var mesh = subMesh.getMesh();
  109969. var material = subMesh.getMaterial();
  109970. if (material) {
  109971. // Alpha test
  109972. if (material.needAlphaTesting()) {
  109973. defines.push("#define ALPHATEST");
  109974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109975. attribs.push(BABYLON.VertexBuffer.UVKind);
  109976. defines.push("#define UV1");
  109977. }
  109978. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  109979. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109980. defines.push("#define UV2");
  109981. }
  109982. }
  109983. //Logarithmic depth
  109984. if (material.useLogarithmicDepth) {
  109985. defines.push("#define LOGARITHMICDEPTH");
  109986. }
  109987. }
  109988. // Bones
  109989. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109992. if (mesh.numBoneInfluencers > 4) {
  109993. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109994. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109995. }
  109996. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109997. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  109998. }
  109999. else {
  110000. defines.push("#define NUM_BONE_INFLUENCERS 0");
  110001. }
  110002. // Instances
  110003. if (useInstances) {
  110004. defines.push("#define INSTANCES");
  110005. attribs.push("world0");
  110006. attribs.push("world1");
  110007. attribs.push("world2");
  110008. attribs.push("world3");
  110009. }
  110010. // Get correct effect
  110011. var join = defines.join("\n");
  110012. if (this._cachedDefines !== join) {
  110013. this._cachedDefines = join;
  110014. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  110015. }
  110016. return this._effect.isReady();
  110017. };
  110018. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  110019. // Outline - step 1
  110020. this._savedDepthWrite = this._engine.getDepthWrite();
  110021. if (mesh.renderOutline) {
  110022. this._engine.setDepthWrite(false);
  110023. this.render(subMesh, batch);
  110024. this._engine.setDepthWrite(this._savedDepthWrite);
  110025. }
  110026. };
  110027. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  110028. // Outline - step 2
  110029. if (mesh.renderOutline && this._savedDepthWrite) {
  110030. this._engine.setDepthWrite(true);
  110031. this._engine.setColorWrite(false);
  110032. this.render(subMesh, batch);
  110033. this._engine.setColorWrite(true);
  110034. }
  110035. // Overlay
  110036. if (mesh.renderOverlay) {
  110037. var currentMode = this._engine.getAlphaMode();
  110038. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110039. this.render(subMesh, batch, true);
  110040. this._engine.setAlphaMode(currentMode);
  110041. }
  110042. };
  110043. return OutlineRenderer;
  110044. }());
  110045. BABYLON.OutlineRenderer = OutlineRenderer;
  110046. })(BABYLON || (BABYLON = {}));
  110047. //# sourceMappingURL=babylon.outlineRenderer.js.map
  110048. var BABYLON;
  110049. (function (BABYLON) {
  110050. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  110051. if (this._edgesRenderer) {
  110052. this._edgesRenderer.dispose();
  110053. this._edgesRenderer = null;
  110054. }
  110055. return this;
  110056. };
  110057. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110058. if (epsilon === void 0) { epsilon = 0.95; }
  110059. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110060. this.disableEdgesRendering();
  110061. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110062. return this;
  110063. };
  110064. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  110065. get: function () {
  110066. return this._edgesRenderer;
  110067. },
  110068. enumerable: true,
  110069. configurable: true
  110070. });
  110071. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110072. if (epsilon === void 0) { epsilon = 0.95; }
  110073. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110074. this.disableEdgesRendering();
  110075. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110076. return this;
  110077. };
  110078. /**
  110079. * FaceAdjacencies Helper class to generate edges
  110080. */
  110081. var FaceAdjacencies = /** @class */ (function () {
  110082. function FaceAdjacencies() {
  110083. this.edges = new Array();
  110084. this.edgesConnectedCount = 0;
  110085. }
  110086. return FaceAdjacencies;
  110087. }());
  110088. /**
  110089. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  110090. */
  110091. var EdgesRenderer = /** @class */ (function () {
  110092. /**
  110093. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  110094. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  110095. * @param source Mesh used to create edges
  110096. * @param epsilon sum of angles in adjacency to check for edge
  110097. * @param checkVerticesInsteadOfIndices
  110098. * @param generateEdgesLines - should generate Lines or only prepare resources.
  110099. */
  110100. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  110101. if (epsilon === void 0) { epsilon = 0.95; }
  110102. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110103. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  110104. var _this = this;
  110105. /**
  110106. * Define the size of the edges with an orthographic camera
  110107. */
  110108. this.edgesWidthScalerForOrthographic = 1000.0;
  110109. /**
  110110. * Define the size of the edges with a perspective camera
  110111. */
  110112. this.edgesWidthScalerForPerspective = 50.0;
  110113. this._linesPositions = new Array();
  110114. this._linesNormals = new Array();
  110115. this._linesIndices = new Array();
  110116. this._buffers = {};
  110117. this._checkVerticesInsteadOfIndices = false;
  110118. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  110119. this.isEnabled = true;
  110120. this._source = source;
  110121. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  110122. this._epsilon = epsilon;
  110123. this._prepareRessources();
  110124. if (generateEdgesLines) {
  110125. this._generateEdgesLines();
  110126. }
  110127. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  110128. _this._rebuild();
  110129. });
  110130. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  110131. _this.dispose();
  110132. });
  110133. }
  110134. EdgesRenderer.prototype._prepareRessources = function () {
  110135. if (this._lineShader) {
  110136. return;
  110137. }
  110138. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  110139. attributes: ["position", "normal"],
  110140. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  110141. });
  110142. this._lineShader.disableDepthWrite = true;
  110143. this._lineShader.backFaceCulling = false;
  110144. };
  110145. /** @hidden */
  110146. EdgesRenderer.prototype._rebuild = function () {
  110147. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110148. if (buffer) {
  110149. buffer._rebuild();
  110150. }
  110151. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110152. if (buffer) {
  110153. buffer._rebuild();
  110154. }
  110155. var scene = this._source.getScene();
  110156. var engine = scene.getEngine();
  110157. this._ib = engine.createIndexBuffer(this._linesIndices);
  110158. };
  110159. /**
  110160. * Releases the required resources for the edges renderer
  110161. */
  110162. EdgesRenderer.prototype.dispose = function () {
  110163. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  110164. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  110165. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110166. if (buffer) {
  110167. buffer.dispose();
  110168. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  110169. }
  110170. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110171. if (buffer) {
  110172. buffer.dispose();
  110173. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  110174. }
  110175. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  110176. this._lineShader.dispose();
  110177. };
  110178. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  110179. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  110180. return 0;
  110181. }
  110182. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  110183. return 1;
  110184. }
  110185. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  110186. return 2;
  110187. }
  110188. return -1;
  110189. };
  110190. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  110191. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  110192. return 0;
  110193. }
  110194. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  110195. return 1;
  110196. }
  110197. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  110198. return 2;
  110199. }
  110200. return -1;
  110201. };
  110202. /**
  110203. * Checks if the pair of p0 and p1 is en edge
  110204. * @param faceIndex
  110205. * @param edge
  110206. * @param faceNormals
  110207. * @param p0
  110208. * @param p1
  110209. * @private
  110210. */
  110211. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  110212. var needToCreateLine;
  110213. if (edge === undefined) {
  110214. needToCreateLine = true;
  110215. }
  110216. else {
  110217. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  110218. needToCreateLine = dotProduct < this._epsilon;
  110219. }
  110220. if (needToCreateLine) {
  110221. var offset = this._linesPositions.length / 3;
  110222. var normal = p0.subtract(p1);
  110223. normal.normalize();
  110224. // Positions
  110225. this._linesPositions.push(p0.x);
  110226. this._linesPositions.push(p0.y);
  110227. this._linesPositions.push(p0.z);
  110228. this._linesPositions.push(p0.x);
  110229. this._linesPositions.push(p0.y);
  110230. this._linesPositions.push(p0.z);
  110231. this._linesPositions.push(p1.x);
  110232. this._linesPositions.push(p1.y);
  110233. this._linesPositions.push(p1.z);
  110234. this._linesPositions.push(p1.x);
  110235. this._linesPositions.push(p1.y);
  110236. this._linesPositions.push(p1.z);
  110237. // Normals
  110238. this._linesNormals.push(p1.x);
  110239. this._linesNormals.push(p1.y);
  110240. this._linesNormals.push(p1.z);
  110241. this._linesNormals.push(-1);
  110242. this._linesNormals.push(p1.x);
  110243. this._linesNormals.push(p1.y);
  110244. this._linesNormals.push(p1.z);
  110245. this._linesNormals.push(1);
  110246. this._linesNormals.push(p0.x);
  110247. this._linesNormals.push(p0.y);
  110248. this._linesNormals.push(p0.z);
  110249. this._linesNormals.push(-1);
  110250. this._linesNormals.push(p0.x);
  110251. this._linesNormals.push(p0.y);
  110252. this._linesNormals.push(p0.z);
  110253. this._linesNormals.push(1);
  110254. // Indices
  110255. this._linesIndices.push(offset);
  110256. this._linesIndices.push(offset + 1);
  110257. this._linesIndices.push(offset + 2);
  110258. this._linesIndices.push(offset);
  110259. this._linesIndices.push(offset + 2);
  110260. this._linesIndices.push(offset + 3);
  110261. }
  110262. };
  110263. /**
  110264. * Generates lines edges from adjacencjes
  110265. * @private
  110266. */
  110267. EdgesRenderer.prototype._generateEdgesLines = function () {
  110268. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110269. var indices = this._source.getIndices();
  110270. if (!indices || !positions) {
  110271. return;
  110272. }
  110273. // First let's find adjacencies
  110274. var adjacencies = new Array();
  110275. var faceNormals = new Array();
  110276. var index;
  110277. var faceAdjacencies;
  110278. // Prepare faces
  110279. for (index = 0; index < indices.length; index += 3) {
  110280. faceAdjacencies = new FaceAdjacencies();
  110281. var p0Index = indices[index];
  110282. var p1Index = indices[index + 1];
  110283. var p2Index = indices[index + 2];
  110284. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  110285. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  110286. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  110287. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  110288. faceNormal.normalize();
  110289. faceNormals.push(faceNormal);
  110290. adjacencies.push(faceAdjacencies);
  110291. }
  110292. // Scan
  110293. for (index = 0; index < adjacencies.length; index++) {
  110294. faceAdjacencies = adjacencies[index];
  110295. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  110296. var otherFaceAdjacencies = adjacencies[otherIndex];
  110297. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  110298. break;
  110299. }
  110300. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  110301. continue;
  110302. }
  110303. var otherP0 = indices[otherIndex * 3];
  110304. var otherP1 = indices[otherIndex * 3 + 1];
  110305. var otherP2 = indices[otherIndex * 3 + 2];
  110306. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  110307. var otherEdgeIndex = 0;
  110308. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  110309. continue;
  110310. }
  110311. switch (edgeIndex) {
  110312. case 0:
  110313. if (this._checkVerticesInsteadOfIndices) {
  110314. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110315. }
  110316. else {
  110317. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  110318. }
  110319. break;
  110320. case 1:
  110321. if (this._checkVerticesInsteadOfIndices) {
  110322. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110323. }
  110324. else {
  110325. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  110326. }
  110327. break;
  110328. case 2:
  110329. if (this._checkVerticesInsteadOfIndices) {
  110330. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110331. }
  110332. else {
  110333. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  110334. }
  110335. break;
  110336. }
  110337. if (otherEdgeIndex === -1) {
  110338. continue;
  110339. }
  110340. faceAdjacencies.edges[edgeIndex] = otherIndex;
  110341. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  110342. faceAdjacencies.edgesConnectedCount++;
  110343. otherFaceAdjacencies.edgesConnectedCount++;
  110344. if (faceAdjacencies.edgesConnectedCount === 3) {
  110345. break;
  110346. }
  110347. }
  110348. }
  110349. }
  110350. // Create lines
  110351. for (index = 0; index < adjacencies.length; index++) {
  110352. // 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
  110353. var current = adjacencies[index];
  110354. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  110355. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  110356. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  110357. }
  110358. // Merge into a single mesh
  110359. var engine = this._source.getScene().getEngine();
  110360. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110361. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110362. this._ib = engine.createIndexBuffer(this._linesIndices);
  110363. this._indicesCount = this._linesIndices.length;
  110364. };
  110365. /**
  110366. * Checks wether or not the edges renderer is ready to render.
  110367. * @return true if ready, otherwise false.
  110368. */
  110369. EdgesRenderer.prototype.isReady = function () {
  110370. return this._lineShader.isReady();
  110371. };
  110372. /**
  110373. * Renders the edges of the attached mesh,
  110374. */
  110375. EdgesRenderer.prototype.render = function () {
  110376. var scene = this._source.getScene();
  110377. if (!this.isReady() || !scene.activeCamera) {
  110378. return;
  110379. }
  110380. var engine = scene.getEngine();
  110381. this._lineShader._preBind();
  110382. if (this._source.edgesColor.a !== 1) {
  110383. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110384. }
  110385. else {
  110386. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110387. }
  110388. // VBOs
  110389. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  110390. scene.resetCachedMaterial();
  110391. this._lineShader.setColor4("color", this._source.edgesColor);
  110392. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  110393. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  110394. }
  110395. else {
  110396. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  110397. }
  110398. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  110399. this._lineShader.bind(this._source.getWorldMatrix());
  110400. // Draw order
  110401. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  110402. this._lineShader.unbind();
  110403. };
  110404. return EdgesRenderer;
  110405. }());
  110406. BABYLON.EdgesRenderer = EdgesRenderer;
  110407. })(BABYLON || (BABYLON = {}));
  110408. //# sourceMappingURL=babylon.edgesRenderer.js.map
  110409. var BABYLON;
  110410. (function (BABYLON) {
  110411. /**
  110412. * FaceAdjacencies Helper class to generate edges
  110413. */
  110414. var FaceAdjacencies = /** @class */ (function () {
  110415. function FaceAdjacencies() {
  110416. this.edges = new Array();
  110417. this.edgesConnectedCount = 0;
  110418. }
  110419. return FaceAdjacencies;
  110420. }());
  110421. /**
  110422. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  110423. */
  110424. var LineEdgesRenderer = /** @class */ (function (_super) {
  110425. __extends(LineEdgesRenderer, _super);
  110426. /**
  110427. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  110428. * @param source LineMesh used to generate edges
  110429. * @param epsilon not important (specified angle for edge detection)
  110430. * @param checkVerticesInsteadOfIndices not important for LineMesh
  110431. */
  110432. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  110433. if (epsilon === void 0) { epsilon = 0.95; }
  110434. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110435. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  110436. _this._generateEdgesLines();
  110437. return _this;
  110438. }
  110439. /**
  110440. * Always create the edge since its a line so only important things are p0 and p1
  110441. * @param faceIndex not important for LineMesh
  110442. * @param edge not important for LineMesh
  110443. * @param faceNormals not important for LineMesh
  110444. * @param p0 beginnig of line
  110445. * @param p1 end of line
  110446. */
  110447. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  110448. var offset = this._linesPositions.length / 3;
  110449. var normal = p0.subtract(p1);
  110450. normal.normalize();
  110451. // Positions
  110452. this._linesPositions.push(p0.x);
  110453. this._linesPositions.push(p0.y);
  110454. this._linesPositions.push(p0.z);
  110455. this._linesPositions.push(p0.x);
  110456. this._linesPositions.push(p0.y);
  110457. this._linesPositions.push(p0.z);
  110458. this._linesPositions.push(p1.x);
  110459. this._linesPositions.push(p1.y);
  110460. this._linesPositions.push(p1.z);
  110461. this._linesPositions.push(p1.x);
  110462. this._linesPositions.push(p1.y);
  110463. this._linesPositions.push(p1.z);
  110464. // Normals
  110465. this._linesNormals.push(p1.x);
  110466. this._linesNormals.push(p1.y);
  110467. this._linesNormals.push(p1.z);
  110468. this._linesNormals.push(-1);
  110469. this._linesNormals.push(p1.x);
  110470. this._linesNormals.push(p1.y);
  110471. this._linesNormals.push(p1.z);
  110472. this._linesNormals.push(1);
  110473. this._linesNormals.push(p0.x);
  110474. this._linesNormals.push(p0.y);
  110475. this._linesNormals.push(p0.z);
  110476. this._linesNormals.push(-1);
  110477. this._linesNormals.push(p0.x);
  110478. this._linesNormals.push(p0.y);
  110479. this._linesNormals.push(p0.z);
  110480. this._linesNormals.push(1);
  110481. // Indices
  110482. this._linesIndices.push(offset);
  110483. this._linesIndices.push(offset + 1);
  110484. this._linesIndices.push(offset + 2);
  110485. this._linesIndices.push(offset);
  110486. this._linesIndices.push(offset + 2);
  110487. this._linesIndices.push(offset + 3);
  110488. };
  110489. /**
  110490. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  110491. */
  110492. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  110493. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110494. var indices = this._source.getIndices();
  110495. if (!indices || !positions) {
  110496. return;
  110497. }
  110498. // First let's find adjacencies
  110499. var adjacencies = new Array();
  110500. var faceNormals = new Array();
  110501. var index;
  110502. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  110503. var currentAdjecancy = new FaceAdjacencies();
  110504. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  110505. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  110506. adjacencies.push(currentAdjecancy);
  110507. }
  110508. // Create lines
  110509. for (index = 0; index < adjacencies.length; index++) {
  110510. // 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
  110511. var current = adjacencies[index];
  110512. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  110513. }
  110514. // Merge into a single mesh
  110515. var engine = this._source.getScene().getEngine();
  110516. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  110517. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  110518. this._ib = engine.createIndexBuffer(this._linesIndices);
  110519. this._indicesCount = this._linesIndices.length;
  110520. };
  110521. return LineEdgesRenderer;
  110522. }(BABYLON.EdgesRenderer));
  110523. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  110524. })(BABYLON || (BABYLON = {}));
  110525. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  110526. var BABYLON;
  110527. (function (BABYLON) {
  110528. // Adds the parser to the scene parsers.
  110529. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  110530. if (parsedData.effectLayers) {
  110531. if (!container.effectLayers) {
  110532. container.effectLayers = new Array();
  110533. }
  110534. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  110535. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  110536. container.effectLayers.push(effectLayer);
  110537. }
  110538. }
  110539. });
  110540. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  110541. var index = this.effectLayers.indexOf(toRemove);
  110542. if (index !== -1) {
  110543. this.effectLayers.splice(index, 1);
  110544. }
  110545. return index;
  110546. };
  110547. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  110548. this.effectLayers.push(newEffectLayer);
  110549. };
  110550. /**
  110551. * Defines the layer scene component responsible to manage any effect layers
  110552. * in a given scene.
  110553. */
  110554. var EffectLayerSceneComponent = /** @class */ (function () {
  110555. /**
  110556. * Creates a new instance of the component for the given scene
  110557. * @param scene Defines the scene to register the component in
  110558. */
  110559. function EffectLayerSceneComponent(scene) {
  110560. /**
  110561. * The component name helpfull to identify the component in the list of scene components.
  110562. */
  110563. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  110564. this._renderEffects = false;
  110565. this._needStencil = false;
  110566. this._previousStencilState = false;
  110567. this.scene = scene;
  110568. this._engine = scene.getEngine();
  110569. scene.effectLayers = new Array();
  110570. }
  110571. /**
  110572. * Registers the component in a given scene
  110573. */
  110574. EffectLayerSceneComponent.prototype.register = function () {
  110575. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  110576. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  110577. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  110578. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  110579. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  110580. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  110581. };
  110582. /**
  110583. * Rebuilds the elements related to this component in case of
  110584. * context lost for instance.
  110585. */
  110586. EffectLayerSceneComponent.prototype.rebuild = function () {
  110587. var layers = this.scene.effectLayers;
  110588. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110589. var effectLayer = layers_1[_i];
  110590. effectLayer._rebuild();
  110591. }
  110592. };
  110593. /**
  110594. * Serializes the component data to the specified json object
  110595. * @param serializationObject The object to serialize to
  110596. */
  110597. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  110598. // Effect layers
  110599. serializationObject.effectLayers = [];
  110600. var layers = this.scene.effectLayers;
  110601. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  110602. var effectLayer = layers_2[_i];
  110603. if (effectLayer.serialize) {
  110604. serializationObject.effectLayers.push(effectLayer.serialize());
  110605. }
  110606. }
  110607. };
  110608. /**
  110609. * Adds all the element from the container to the scene
  110610. * @param container the container holding the elements
  110611. */
  110612. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  110613. var _this = this;
  110614. if (!container.effectLayers) {
  110615. return;
  110616. }
  110617. container.effectLayers.forEach(function (o) {
  110618. _this.scene.addEffectLayer(o);
  110619. });
  110620. };
  110621. /**
  110622. * Removes all the elements in the container from the scene
  110623. * @param container contains the elements to remove
  110624. */
  110625. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  110626. var _this = this;
  110627. if (!container.effectLayers) {
  110628. return;
  110629. }
  110630. container.effectLayers.forEach(function (o) {
  110631. _this.scene.removeEffectLayer(o);
  110632. });
  110633. };
  110634. /**
  110635. * Disposes the component and the associated ressources.
  110636. */
  110637. EffectLayerSceneComponent.prototype.dispose = function () {
  110638. var layers = this.scene.effectLayers;
  110639. while (layers.length) {
  110640. layers[0].dispose();
  110641. }
  110642. };
  110643. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  110644. var layers = this.scene.effectLayers;
  110645. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  110646. var layer = layers_3[_i];
  110647. if (!layer.hasMesh(mesh)) {
  110648. continue;
  110649. }
  110650. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  110651. var subMesh = _b[_a];
  110652. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  110653. return false;
  110654. }
  110655. }
  110656. }
  110657. return true;
  110658. };
  110659. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  110660. this._renderEffects = false;
  110661. this._needStencil = false;
  110662. var layers = this.scene.effectLayers;
  110663. if (layers && layers.length > 0) {
  110664. this._previousStencilState = this._engine.getStencilBuffer();
  110665. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  110666. var effectLayer = layers_4[_i];
  110667. if (effectLayer.shouldRender() &&
  110668. (!effectLayer.camera ||
  110669. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  110670. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  110671. this._renderEffects = true;
  110672. this._needStencil = this._needStencil || effectLayer.needStencil();
  110673. var renderTarget = effectLayer._mainTexture;
  110674. if (renderTarget._shouldRender()) {
  110675. this.scene.incrementRenderId();
  110676. renderTarget.render(false, false);
  110677. }
  110678. }
  110679. }
  110680. this.scene.incrementRenderId();
  110681. }
  110682. };
  110683. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  110684. // Activate effect Layer stencil
  110685. if (this._needStencil) {
  110686. this._engine.setStencilBuffer(true);
  110687. }
  110688. };
  110689. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  110690. // Restore effect Layer stencil
  110691. if (this._needStencil) {
  110692. this._engine.setStencilBuffer(this._previousStencilState);
  110693. }
  110694. };
  110695. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  110696. if (this._renderEffects) {
  110697. this._engine.setDepthBuffer(false);
  110698. var layers = this.scene.effectLayers;
  110699. for (var i = 0; i < layers.length; i++) {
  110700. var effectLayer = layers[i];
  110701. if (effectLayer.renderingGroupId === renderingGroupId) {
  110702. if (effectLayer.shouldRender()) {
  110703. effectLayer.render();
  110704. }
  110705. }
  110706. }
  110707. this._engine.setDepthBuffer(true);
  110708. }
  110709. };
  110710. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  110711. if (this._renderEffects) {
  110712. this._draw(-1);
  110713. }
  110714. };
  110715. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  110716. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  110717. this._draw(index);
  110718. }
  110719. };
  110720. return EffectLayerSceneComponent;
  110721. }());
  110722. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  110723. })(BABYLON || (BABYLON = {}));
  110724. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  110725. var __assign = (this && this.__assign) || function () {
  110726. __assign = Object.assign || function(t) {
  110727. for (var s, i = 1, n = arguments.length; i < n; i++) {
  110728. s = arguments[i];
  110729. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  110730. t[p] = s[p];
  110731. }
  110732. return t;
  110733. };
  110734. return __assign.apply(this, arguments);
  110735. };
  110736. var BABYLON;
  110737. (function (BABYLON) {
  110738. /**
  110739. * The effect layer Helps adding post process effect blended with the main pass.
  110740. *
  110741. * This can be for instance use to generate glow or higlight effects on the scene.
  110742. *
  110743. * The effect layer class can not be used directly and is intented to inherited from to be
  110744. * customized per effects.
  110745. */
  110746. var EffectLayer = /** @class */ (function () {
  110747. /**
  110748. * Instantiates a new effect Layer and references it in the scene.
  110749. * @param name The name of the layer
  110750. * @param scene The scene to use the layer in
  110751. */
  110752. function EffectLayer(
  110753. /** The Friendly of the effect in the scene */
  110754. name, scene) {
  110755. this._vertexBuffers = {};
  110756. this._maxSize = 0;
  110757. this._mainTextureDesiredSize = { width: 0, height: 0 };
  110758. this._shouldRender = true;
  110759. this._postProcesses = [];
  110760. this._textures = [];
  110761. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  110762. /**
  110763. * The clear color of the texture used to generate the glow map.
  110764. */
  110765. this.neutralColor = new BABYLON.Color4();
  110766. /**
  110767. * Specifies wether the highlight layer is enabled or not.
  110768. */
  110769. this.isEnabled = true;
  110770. /**
  110771. * An event triggered when the effect layer has been disposed.
  110772. */
  110773. this.onDisposeObservable = new BABYLON.Observable();
  110774. /**
  110775. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  110776. */
  110777. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  110778. /**
  110779. * An event triggered when the generated texture is being merged in the scene.
  110780. */
  110781. this.onBeforeComposeObservable = new BABYLON.Observable();
  110782. /**
  110783. * An event triggered when the generated texture has been merged in the scene.
  110784. */
  110785. this.onAfterComposeObservable = new BABYLON.Observable();
  110786. /**
  110787. * An event triggered when the efffect layer changes its size.
  110788. */
  110789. this.onSizeChangedObservable = new BABYLON.Observable();
  110790. this.name = name;
  110791. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  110792. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  110793. if (!component) {
  110794. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  110795. this._scene._addComponent(component);
  110796. }
  110797. this._engine = this._scene.getEngine();
  110798. this._maxSize = this._engine.getCaps().maxTextureSize;
  110799. this._scene.effectLayers.push(this);
  110800. // Generate Buffers
  110801. this._generateIndexBuffer();
  110802. this._genrateVertexBuffer();
  110803. }
  110804. Object.defineProperty(EffectLayer.prototype, "camera", {
  110805. /**
  110806. * Gets the camera attached to the layer.
  110807. */
  110808. get: function () {
  110809. return this._effectLayerOptions.camera;
  110810. },
  110811. enumerable: true,
  110812. configurable: true
  110813. });
  110814. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  110815. /**
  110816. * Gets the rendering group id the layer should render in.
  110817. */
  110818. get: function () {
  110819. return this._effectLayerOptions.renderingGroupId;
  110820. },
  110821. enumerable: true,
  110822. configurable: true
  110823. });
  110824. /**
  110825. * Initializes the effect layer with the required options.
  110826. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  110827. */
  110828. EffectLayer.prototype._init = function (options) {
  110829. // Adapt options
  110830. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  110831. this._setMainTextureSize();
  110832. this._createMainTexture();
  110833. this._createTextureAndPostProcesses();
  110834. this._mergeEffect = this._createMergeEffect();
  110835. };
  110836. /**
  110837. * Generates the index buffer of the full screen quad blending to the main canvas.
  110838. */
  110839. EffectLayer.prototype._generateIndexBuffer = function () {
  110840. // Indices
  110841. var indices = [];
  110842. indices.push(0);
  110843. indices.push(1);
  110844. indices.push(2);
  110845. indices.push(0);
  110846. indices.push(2);
  110847. indices.push(3);
  110848. this._indexBuffer = this._engine.createIndexBuffer(indices);
  110849. };
  110850. /**
  110851. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  110852. */
  110853. EffectLayer.prototype._genrateVertexBuffer = function () {
  110854. // VBO
  110855. var vertices = [];
  110856. vertices.push(1, 1);
  110857. vertices.push(-1, 1);
  110858. vertices.push(-1, -1);
  110859. vertices.push(1, -1);
  110860. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  110861. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  110862. };
  110863. /**
  110864. * Sets the main texture desired size which is the closest power of two
  110865. * of the engine canvas size.
  110866. */
  110867. EffectLayer.prototype._setMainTextureSize = function () {
  110868. if (this._effectLayerOptions.mainTextureFixedSize) {
  110869. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  110870. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  110871. }
  110872. else {
  110873. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  110874. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  110875. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  110876. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  110877. }
  110878. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  110879. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  110880. };
  110881. /**
  110882. * Creates the main texture for the effect layer.
  110883. */
  110884. EffectLayer.prototype._createMainTexture = function () {
  110885. var _this = this;
  110886. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  110887. width: this._mainTextureDesiredSize.width,
  110888. height: this._mainTextureDesiredSize.height
  110889. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  110890. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  110891. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110892. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110893. this._mainTexture.anisotropicFilteringLevel = 1;
  110894. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110895. this._mainTexture.renderParticles = false;
  110896. this._mainTexture.renderList = null;
  110897. this._mainTexture.ignoreCameraViewport = true;
  110898. // Custom render function
  110899. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  110900. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  110901. var index;
  110902. var engine = _this._scene.getEngine();
  110903. if (depthOnlySubMeshes.length) {
  110904. engine.setColorWrite(false);
  110905. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  110906. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  110907. }
  110908. engine.setColorWrite(true);
  110909. }
  110910. for (index = 0; index < opaqueSubMeshes.length; index++) {
  110911. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  110912. }
  110913. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  110914. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  110915. }
  110916. for (index = 0; index < transparentSubMeshes.length; index++) {
  110917. _this._renderSubMesh(transparentSubMeshes.data[index]);
  110918. }
  110919. };
  110920. this._mainTexture.onClearObservable.add(function (engine) {
  110921. engine.clear(_this.neutralColor, true, true, true);
  110922. });
  110923. };
  110924. /**
  110925. * Checks for the readiness of the element composing the layer.
  110926. * @param subMesh the mesh to check for
  110927. * @param useInstances specify wether or not to use instances to render the mesh
  110928. * @param emissiveTexture the associated emissive texture used to generate the glow
  110929. * @return true if ready otherwise, false
  110930. */
  110931. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  110932. var material = subMesh.getMaterial();
  110933. if (!material) {
  110934. return false;
  110935. }
  110936. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  110937. return false;
  110938. }
  110939. var defines = [];
  110940. var attribs = [BABYLON.VertexBuffer.PositionKind];
  110941. var mesh = subMesh.getMesh();
  110942. var uv1 = false;
  110943. var uv2 = false;
  110944. // Alpha test
  110945. if (material && material.needAlphaTesting()) {
  110946. var alphaTexture = material.getAlphaTestTexture();
  110947. if (alphaTexture) {
  110948. defines.push("#define ALPHATEST");
  110949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  110950. alphaTexture.coordinatesIndex === 1) {
  110951. defines.push("#define DIFFUSEUV2");
  110952. uv2 = true;
  110953. }
  110954. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  110955. defines.push("#define DIFFUSEUV1");
  110956. uv1 = true;
  110957. }
  110958. }
  110959. }
  110960. // Emissive
  110961. if (emissiveTexture) {
  110962. defines.push("#define EMISSIVE");
  110963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  110964. emissiveTexture.coordinatesIndex === 1) {
  110965. defines.push("#define EMISSIVEUV2");
  110966. uv2 = true;
  110967. }
  110968. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  110969. defines.push("#define EMISSIVEUV1");
  110970. uv1 = true;
  110971. }
  110972. }
  110973. if (uv1) {
  110974. attribs.push(BABYLON.VertexBuffer.UVKind);
  110975. defines.push("#define UV1");
  110976. }
  110977. if (uv2) {
  110978. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  110979. defines.push("#define UV2");
  110980. }
  110981. // Bones
  110982. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  110983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  110984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  110985. if (mesh.numBoneInfluencers > 4) {
  110986. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  110987. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  110988. }
  110989. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  110990. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  110991. }
  110992. else {
  110993. defines.push("#define NUM_BONE_INFLUENCERS 0");
  110994. }
  110995. // Morph targets
  110996. var manager = mesh.morphTargetManager;
  110997. var morphInfluencers = 0;
  110998. if (manager) {
  110999. if (manager.numInfluencers > 0) {
  111000. defines.push("#define MORPHTARGETS");
  111001. morphInfluencers = manager.numInfluencers;
  111002. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  111003. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  111004. }
  111005. }
  111006. // Instances
  111007. if (useInstances) {
  111008. defines.push("#define INSTANCES");
  111009. attribs.push("world0");
  111010. attribs.push("world1");
  111011. attribs.push("world2");
  111012. attribs.push("world3");
  111013. }
  111014. // Get correct effect
  111015. var join = defines.join("\n");
  111016. if (this._cachedDefines !== join) {
  111017. this._cachedDefines = join;
  111018. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  111019. }
  111020. return this._effectLayerMapGenerationEffect.isReady();
  111021. };
  111022. /**
  111023. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  111024. */
  111025. EffectLayer.prototype.render = function () {
  111026. var currentEffect = this._mergeEffect;
  111027. // Check
  111028. if (!currentEffect.isReady()) {
  111029. return;
  111030. }
  111031. for (var i = 0; i < this._postProcesses.length; i++) {
  111032. if (!this._postProcesses[i].isReady()) {
  111033. return;
  111034. }
  111035. }
  111036. var engine = this._scene.getEngine();
  111037. this.onBeforeComposeObservable.notifyObservers(this);
  111038. // Render
  111039. engine.enableEffect(currentEffect);
  111040. engine.setState(false);
  111041. // VBOs
  111042. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  111043. // Cache
  111044. var previousAlphaMode = engine.getAlphaMode();
  111045. // Go Blend.
  111046. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  111047. // Blends the map on the main canvas.
  111048. this._internalRender(currentEffect);
  111049. // Restore Alpha
  111050. engine.setAlphaMode(previousAlphaMode);
  111051. this.onAfterComposeObservable.notifyObservers(this);
  111052. // Handle size changes.
  111053. var size = this._mainTexture.getSize();
  111054. this._setMainTextureSize();
  111055. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  111056. // Recreate RTT and post processes on size change.
  111057. this.onSizeChangedObservable.notifyObservers(this);
  111058. this._disposeTextureAndPostProcesses();
  111059. this._createMainTexture();
  111060. this._createTextureAndPostProcesses();
  111061. }
  111062. };
  111063. /**
  111064. * Determine if a given mesh will be used in the current effect.
  111065. * @param mesh mesh to test
  111066. * @returns true if the mesh will be used
  111067. */
  111068. EffectLayer.prototype.hasMesh = function (mesh) {
  111069. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  111070. return true;
  111071. }
  111072. return false;
  111073. };
  111074. /**
  111075. * Returns true if the layer contains information to display, otherwise false.
  111076. * @returns true if the glow layer should be rendered
  111077. */
  111078. EffectLayer.prototype.shouldRender = function () {
  111079. return this.isEnabled && this._shouldRender;
  111080. };
  111081. /**
  111082. * Returns true if the mesh should render, otherwise false.
  111083. * @param mesh The mesh to render
  111084. * @returns true if it should render otherwise false
  111085. */
  111086. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  111087. return true;
  111088. };
  111089. /**
  111090. * Returns true if the mesh should render, otherwise false.
  111091. * @param mesh The mesh to render
  111092. * @returns true if it should render otherwise false
  111093. */
  111094. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  111095. return true;
  111096. };
  111097. /**
  111098. * Renders the submesh passed in parameter to the generation map.
  111099. */
  111100. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  111101. var _this = this;
  111102. if (!this.shouldRender()) {
  111103. return;
  111104. }
  111105. var material = subMesh.getMaterial();
  111106. var mesh = subMesh.getRenderingMesh();
  111107. var scene = this._scene;
  111108. var engine = scene.getEngine();
  111109. if (!material) {
  111110. return;
  111111. }
  111112. // Do not block in blend mode.
  111113. if (material.needAlphaBlendingForMesh(mesh)) {
  111114. return;
  111115. }
  111116. // Culling
  111117. engine.setState(material.backFaceCulling);
  111118. // Managing instances
  111119. var batch = mesh._getInstancesRenderList(subMesh._id);
  111120. if (batch.mustReturn) {
  111121. return;
  111122. }
  111123. // Early Exit per mesh
  111124. if (!this._shouldRenderMesh(mesh)) {
  111125. return;
  111126. }
  111127. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  111128. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  111129. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  111130. engine.enableEffect(this._effectLayerMapGenerationEffect);
  111131. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  111132. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  111133. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  111134. // Alpha test
  111135. if (material && material.needAlphaTesting()) {
  111136. var alphaTexture = material.getAlphaTestTexture();
  111137. if (alphaTexture) {
  111138. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  111139. var textureMatrix = alphaTexture.getTextureMatrix();
  111140. if (textureMatrix) {
  111141. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  111142. }
  111143. }
  111144. }
  111145. // Glow emissive only
  111146. if (this._emissiveTextureAndColor.texture) {
  111147. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  111148. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  111149. }
  111150. // Bones
  111151. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  111152. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  111153. }
  111154. // Morph targets
  111155. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  111156. // Draw
  111157. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  111158. }
  111159. else {
  111160. // Need to reset refresh rate of the main map
  111161. this._mainTexture.resetRefreshCounter();
  111162. }
  111163. };
  111164. /**
  111165. * Rebuild the required buffers.
  111166. * @hidden Internal use only.
  111167. */
  111168. EffectLayer.prototype._rebuild = function () {
  111169. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111170. if (vb) {
  111171. vb._rebuild();
  111172. }
  111173. this._generateIndexBuffer();
  111174. };
  111175. /**
  111176. * Dispose only the render target textures and post process.
  111177. */
  111178. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  111179. this._mainTexture.dispose();
  111180. for (var i = 0; i < this._postProcesses.length; i++) {
  111181. if (this._postProcesses[i]) {
  111182. this._postProcesses[i].dispose();
  111183. }
  111184. }
  111185. this._postProcesses = [];
  111186. for (var i = 0; i < this._textures.length; i++) {
  111187. if (this._textures[i]) {
  111188. this._textures[i].dispose();
  111189. }
  111190. }
  111191. this._textures = [];
  111192. };
  111193. /**
  111194. * Dispose the highlight layer and free resources.
  111195. */
  111196. EffectLayer.prototype.dispose = function () {
  111197. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111198. if (vertexBuffer) {
  111199. vertexBuffer.dispose();
  111200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  111201. }
  111202. if (this._indexBuffer) {
  111203. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  111204. this._indexBuffer = null;
  111205. }
  111206. // Clean textures and post processes
  111207. this._disposeTextureAndPostProcesses();
  111208. // Remove from scene
  111209. var index = this._scene.effectLayers.indexOf(this, 0);
  111210. if (index > -1) {
  111211. this._scene.effectLayers.splice(index, 1);
  111212. }
  111213. // Callback
  111214. this.onDisposeObservable.notifyObservers(this);
  111215. this.onDisposeObservable.clear();
  111216. this.onBeforeRenderMainTextureObservable.clear();
  111217. this.onBeforeComposeObservable.clear();
  111218. this.onAfterComposeObservable.clear();
  111219. this.onSizeChangedObservable.clear();
  111220. };
  111221. /**
  111222. * Gets the class name of the effect layer
  111223. * @returns the string with the class name of the effect layer
  111224. */
  111225. EffectLayer.prototype.getClassName = function () {
  111226. return "EffectLayer";
  111227. };
  111228. /**
  111229. * Creates an effect layer from parsed effect layer data
  111230. * @param parsedEffectLayer defines effect layer data
  111231. * @param scene defines the current scene
  111232. * @param rootUrl defines the root URL containing the effect layer information
  111233. * @returns a parsed effect Layer
  111234. */
  111235. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  111236. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  111237. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  111238. };
  111239. __decorate([
  111240. BABYLON.serialize()
  111241. ], EffectLayer.prototype, "name", void 0);
  111242. __decorate([
  111243. BABYLON.serializeAsColor4()
  111244. ], EffectLayer.prototype, "neutralColor", void 0);
  111245. __decorate([
  111246. BABYLON.serialize()
  111247. ], EffectLayer.prototype, "isEnabled", void 0);
  111248. __decorate([
  111249. BABYLON.serializeAsCameraReference()
  111250. ], EffectLayer.prototype, "camera", null);
  111251. __decorate([
  111252. BABYLON.serialize()
  111253. ], EffectLayer.prototype, "renderingGroupId", null);
  111254. return EffectLayer;
  111255. }());
  111256. BABYLON.EffectLayer = EffectLayer;
  111257. })(BABYLON || (BABYLON = {}));
  111258. //# sourceMappingURL=babylon.effectLayer.js.map
  111259. var BABYLON;
  111260. (function (BABYLON) {
  111261. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  111262. for (var index = 0; index < this.effectLayers.length; index++) {
  111263. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  111264. return this.effectLayers[index];
  111265. }
  111266. }
  111267. return null;
  111268. };
  111269. /**
  111270. * Special Glow Blur post process only blurring the alpha channel
  111271. * It enforces keeping the most luminous color in the color channel.
  111272. */
  111273. var GlowBlurPostProcess = /** @class */ (function (_super) {
  111274. __extends(GlowBlurPostProcess, _super);
  111275. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  111276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  111277. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  111278. _this.direction = direction;
  111279. _this.kernel = kernel;
  111280. _this.onApplyObservable.add(function (effect) {
  111281. effect.setFloat2("screenSize", _this.width, _this.height);
  111282. effect.setVector2("direction", _this.direction);
  111283. effect.setFloat("blurWidth", _this.kernel);
  111284. });
  111285. return _this;
  111286. }
  111287. return GlowBlurPostProcess;
  111288. }(BABYLON.PostProcess));
  111289. /**
  111290. * The highlight layer Helps adding a glow effect around a mesh.
  111291. *
  111292. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  111293. * glowy meshes to your scene.
  111294. *
  111295. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  111296. */
  111297. var HighlightLayer = /** @class */ (function (_super) {
  111298. __extends(HighlightLayer, _super);
  111299. /**
  111300. * Instantiates a new highlight Layer and references it to the scene..
  111301. * @param name The name of the layer
  111302. * @param scene The scene to use the layer in
  111303. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  111304. */
  111305. function HighlightLayer(name, scene, options) {
  111306. var _this = _super.call(this, name, scene) || this;
  111307. _this.name = name;
  111308. /**
  111309. * Specifies whether or not the inner glow is ACTIVE in the layer.
  111310. */
  111311. _this.innerGlow = true;
  111312. /**
  111313. * Specifies whether or not the outer glow is ACTIVE in the layer.
  111314. */
  111315. _this.outerGlow = true;
  111316. /**
  111317. * An event triggered when the highlight layer is being blurred.
  111318. */
  111319. _this.onBeforeBlurObservable = new BABYLON.Observable();
  111320. /**
  111321. * An event triggered when the highlight layer has been blurred.
  111322. */
  111323. _this.onAfterBlurObservable = new BABYLON.Observable();
  111324. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  111325. _this._meshes = {};
  111326. _this._excludedMeshes = {};
  111327. _this.neutralColor = HighlightLayer.NeutralColor;
  111328. // Warn on stencil
  111329. if (!_this._engine.isStencilEnable) {
  111330. 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 }");
  111331. }
  111332. // Adapt options
  111333. _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);
  111334. // Initialize the layer
  111335. _this._init({
  111336. alphaBlendingMode: _this._options.alphaBlendingMode,
  111337. camera: _this._options.camera,
  111338. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  111339. mainTextureRatio: _this._options.mainTextureRatio,
  111340. renderingGroupId: _this._options.renderingGroupId
  111341. });
  111342. // Do not render as long as no meshes have been added
  111343. _this._shouldRender = false;
  111344. return _this;
  111345. }
  111346. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  111347. /**
  111348. * Gets the horizontal size of the blur.
  111349. */
  111350. get: function () {
  111351. return this._horizontalBlurPostprocess.kernel;
  111352. },
  111353. /**
  111354. * Specifies the horizontal size of the blur.
  111355. */
  111356. set: function (value) {
  111357. this._horizontalBlurPostprocess.kernel = value;
  111358. },
  111359. enumerable: true,
  111360. configurable: true
  111361. });
  111362. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  111363. /**
  111364. * Gets the vertical size of the blur.
  111365. */
  111366. get: function () {
  111367. return this._verticalBlurPostprocess.kernel;
  111368. },
  111369. /**
  111370. * Specifies the vertical size of the blur.
  111371. */
  111372. set: function (value) {
  111373. this._verticalBlurPostprocess.kernel = value;
  111374. },
  111375. enumerable: true,
  111376. configurable: true
  111377. });
  111378. /**
  111379. * Get the effect name of the layer.
  111380. * @return The effect name
  111381. */
  111382. HighlightLayer.prototype.getEffectName = function () {
  111383. return HighlightLayer.EffectName;
  111384. };
  111385. /**
  111386. * Create the merge effect. This is the shader use to blit the information back
  111387. * to the main canvas at the end of the scene rendering.
  111388. */
  111389. HighlightLayer.prototype._createMergeEffect = function () {
  111390. // Effect
  111391. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  111392. };
  111393. /**
  111394. * Creates the render target textures and post processes used in the highlight layer.
  111395. */
  111396. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  111397. var _this = this;
  111398. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  111399. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  111400. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  111401. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  111402. var textureType = 0;
  111403. if (this._engine.getCaps().textureHalfFloatRender) {
  111404. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  111405. }
  111406. else {
  111407. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111408. }
  111409. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  111410. width: blurTextureWidth,
  111411. height: blurTextureHeight
  111412. }, this._scene, false, true, textureType);
  111413. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111414. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111415. this._blurTexture.anisotropicFilteringLevel = 16;
  111416. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  111417. this._blurTexture.renderParticles = false;
  111418. this._blurTexture.ignoreCameraViewport = true;
  111419. this._textures = [this._blurTexture];
  111420. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  111421. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111422. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  111423. effect.setTexture("textureSampler", _this._mainTexture);
  111424. });
  111425. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111426. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111427. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111428. });
  111429. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111430. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  111431. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  111432. });
  111433. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111434. }
  111435. else {
  111436. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  111437. width: blurTextureWidth,
  111438. height: blurTextureHeight
  111439. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111440. this._horizontalBlurPostprocess.width = blurTextureWidth;
  111441. this._horizontalBlurPostprocess.height = blurTextureHeight;
  111442. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  111443. effect.setTexture("textureSampler", _this._mainTexture);
  111444. });
  111445. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  111446. width: blurTextureWidth,
  111447. height: blurTextureHeight
  111448. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111449. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  111450. }
  111451. this._mainTexture.onAfterUnbindObservable.add(function () {
  111452. _this.onBeforeBlurObservable.notifyObservers(_this);
  111453. var internalTexture = _this._blurTexture.getInternalTexture();
  111454. if (internalTexture) {
  111455. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  111456. }
  111457. _this.onAfterBlurObservable.notifyObservers(_this);
  111458. });
  111459. // Prevent autoClear.
  111460. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  111461. };
  111462. /**
  111463. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  111464. */
  111465. HighlightLayer.prototype.needStencil = function () {
  111466. return true;
  111467. };
  111468. /**
  111469. * Checks for the readiness of the element composing the layer.
  111470. * @param subMesh the mesh to check for
  111471. * @param useInstances specify wether or not to use instances to render the mesh
  111472. * @param emissiveTexture the associated emissive texture used to generate the glow
  111473. * @return true if ready otherwise, false
  111474. */
  111475. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  111476. var material = subMesh.getMaterial();
  111477. var mesh = subMesh.getRenderingMesh();
  111478. if (!material || !mesh || !this._meshes) {
  111479. return false;
  111480. }
  111481. var emissiveTexture = null;
  111482. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111483. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111484. emissiveTexture = material.emissiveTexture;
  111485. }
  111486. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  111487. };
  111488. /**
  111489. * Implementation specific of rendering the generating effect on the main canvas.
  111490. * @param effect The effect used to render through
  111491. */
  111492. HighlightLayer.prototype._internalRender = function (effect) {
  111493. // Texture
  111494. effect.setTexture("textureSampler", this._blurTexture);
  111495. // Cache
  111496. var engine = this._engine;
  111497. var previousStencilBuffer = engine.getStencilBuffer();
  111498. var previousStencilFunction = engine.getStencilFunction();
  111499. var previousStencilMask = engine.getStencilMask();
  111500. var previousStencilOperationPass = engine.getStencilOperationPass();
  111501. var previousStencilOperationFail = engine.getStencilOperationFail();
  111502. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  111503. var previousStencilReference = engine.getStencilFunctionReference();
  111504. // Stencil operations
  111505. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  111506. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  111507. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  111508. // Draw order
  111509. engine.setStencilMask(0x00);
  111510. engine.setStencilBuffer(true);
  111511. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  111512. // 2 passes inner outer
  111513. if (this.outerGlow) {
  111514. effect.setFloat("offset", 0);
  111515. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  111516. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111517. }
  111518. if (this.innerGlow) {
  111519. effect.setFloat("offset", 1);
  111520. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  111521. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111522. }
  111523. // Restore Cache
  111524. engine.setStencilFunction(previousStencilFunction);
  111525. engine.setStencilMask(previousStencilMask);
  111526. engine.setStencilBuffer(previousStencilBuffer);
  111527. engine.setStencilOperationPass(previousStencilOperationPass);
  111528. engine.setStencilOperationFail(previousStencilOperationFail);
  111529. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  111530. engine.setStencilFunctionReference(previousStencilReference);
  111531. };
  111532. /**
  111533. * Returns true if the layer contains information to display, otherwise false.
  111534. */
  111535. HighlightLayer.prototype.shouldRender = function () {
  111536. if (_super.prototype.shouldRender.call(this)) {
  111537. return this._meshes ? true : false;
  111538. }
  111539. return false;
  111540. };
  111541. /**
  111542. * Returns true if the mesh should render, otherwise false.
  111543. * @param mesh The mesh to render
  111544. * @returns true if it should render otherwise false
  111545. */
  111546. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  111547. // Excluded Mesh
  111548. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  111549. return false;
  111550. }
  111551. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111552. return false;
  111553. }
  111554. return true;
  111555. };
  111556. /**
  111557. * Sets the required values for both the emissive texture and and the main color.
  111558. */
  111559. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  111560. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  111561. if (highlightLayerMesh) {
  111562. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  111563. }
  111564. else {
  111565. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  111566. }
  111567. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  111568. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  111569. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  111570. }
  111571. else {
  111572. this._emissiveTextureAndColor.texture = null;
  111573. }
  111574. };
  111575. /**
  111576. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  111577. * @param mesh The mesh to exclude from the highlight layer
  111578. */
  111579. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  111580. if (!this._excludedMeshes) {
  111581. return;
  111582. }
  111583. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  111584. if (!meshExcluded) {
  111585. this._excludedMeshes[mesh.uniqueId] = {
  111586. mesh: mesh,
  111587. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  111588. mesh.getEngine().setStencilBuffer(false);
  111589. }),
  111590. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  111591. mesh.getEngine().setStencilBuffer(true);
  111592. }),
  111593. };
  111594. }
  111595. };
  111596. /**
  111597. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  111598. * @param mesh The mesh to highlight
  111599. */
  111600. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  111601. if (!this._excludedMeshes) {
  111602. return;
  111603. }
  111604. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  111605. if (meshExcluded) {
  111606. if (meshExcluded.beforeRender) {
  111607. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  111608. }
  111609. if (meshExcluded.afterRender) {
  111610. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  111611. }
  111612. }
  111613. this._excludedMeshes[mesh.uniqueId] = null;
  111614. };
  111615. /**
  111616. * Determine if a given mesh will be highlighted by the current HighlightLayer
  111617. * @param mesh mesh to test
  111618. * @returns true if the mesh will be highlighted by the current HighlightLayer
  111619. */
  111620. HighlightLayer.prototype.hasMesh = function (mesh) {
  111621. if (!this._meshes) {
  111622. return false;
  111623. }
  111624. if (!_super.prototype.hasMesh.call(this, mesh)) {
  111625. return false;
  111626. }
  111627. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  111628. };
  111629. /**
  111630. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  111631. * @param mesh The mesh to highlight
  111632. * @param color The color of the highlight
  111633. * @param glowEmissiveOnly Extract the glow from the emissive texture
  111634. */
  111635. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  111636. var _this = this;
  111637. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  111638. if (!this._meshes) {
  111639. return;
  111640. }
  111641. var meshHighlight = this._meshes[mesh.uniqueId];
  111642. if (meshHighlight) {
  111643. meshHighlight.color = color;
  111644. }
  111645. else {
  111646. this._meshes[mesh.uniqueId] = {
  111647. mesh: mesh,
  111648. color: color,
  111649. // Lambda required for capture due to Observable this context
  111650. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  111651. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  111652. _this._defaultStencilReference(mesh);
  111653. }
  111654. else {
  111655. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  111656. }
  111657. }),
  111658. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  111659. glowEmissiveOnly: glowEmissiveOnly
  111660. };
  111661. mesh.onDisposeObservable.add(function () {
  111662. _this._disposeMesh(mesh);
  111663. });
  111664. }
  111665. this._shouldRender = true;
  111666. };
  111667. /**
  111668. * Remove a mesh from the highlight layer in order to make it stop glowing.
  111669. * @param mesh The mesh to highlight
  111670. */
  111671. HighlightLayer.prototype.removeMesh = function (mesh) {
  111672. if (!this._meshes) {
  111673. return;
  111674. }
  111675. var meshHighlight = this._meshes[mesh.uniqueId];
  111676. if (meshHighlight) {
  111677. if (meshHighlight.observerHighlight) {
  111678. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  111679. }
  111680. if (meshHighlight.observerDefault) {
  111681. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  111682. }
  111683. delete this._meshes[mesh.uniqueId];
  111684. }
  111685. this._shouldRender = false;
  111686. for (var meshHighlightToCheck in this._meshes) {
  111687. if (this._meshes[meshHighlightToCheck]) {
  111688. this._shouldRender = true;
  111689. break;
  111690. }
  111691. }
  111692. };
  111693. /**
  111694. * Force the stencil to the normal expected value for none glowing parts
  111695. */
  111696. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  111697. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  111698. };
  111699. /**
  111700. * Free any resources and references associated to a mesh.
  111701. * Internal use
  111702. * @param mesh The mesh to free.
  111703. * @hidden
  111704. */
  111705. HighlightLayer.prototype._disposeMesh = function (mesh) {
  111706. this.removeMesh(mesh);
  111707. this.removeExcludedMesh(mesh);
  111708. };
  111709. /**
  111710. * Dispose the highlight layer and free resources.
  111711. */
  111712. HighlightLayer.prototype.dispose = function () {
  111713. if (this._meshes) {
  111714. // Clean mesh references
  111715. for (var id in this._meshes) {
  111716. var meshHighlight = this._meshes[id];
  111717. if (meshHighlight && meshHighlight.mesh) {
  111718. if (meshHighlight.observerHighlight) {
  111719. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  111720. }
  111721. if (meshHighlight.observerDefault) {
  111722. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  111723. }
  111724. }
  111725. }
  111726. this._meshes = null;
  111727. }
  111728. if (this._excludedMeshes) {
  111729. for (var id in this._excludedMeshes) {
  111730. var meshHighlight = this._excludedMeshes[id];
  111731. if (meshHighlight) {
  111732. if (meshHighlight.beforeRender) {
  111733. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  111734. }
  111735. if (meshHighlight.afterRender) {
  111736. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  111737. }
  111738. }
  111739. }
  111740. this._excludedMeshes = null;
  111741. }
  111742. _super.prototype.dispose.call(this);
  111743. };
  111744. /**
  111745. * Gets the class name of the effect layer
  111746. * @returns the string with the class name of the effect layer
  111747. */
  111748. HighlightLayer.prototype.getClassName = function () {
  111749. return "HighlightLayer";
  111750. };
  111751. /**
  111752. * Serializes this Highlight layer
  111753. * @returns a serialized Highlight layer object
  111754. */
  111755. HighlightLayer.prototype.serialize = function () {
  111756. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111757. serializationObject.customType = "BABYLON.HighlightLayer";
  111758. // Highlighted meshes
  111759. serializationObject.meshes = [];
  111760. if (this._meshes) {
  111761. for (var m in this._meshes) {
  111762. var mesh = this._meshes[m];
  111763. if (mesh) {
  111764. serializationObject.meshes.push({
  111765. glowEmissiveOnly: mesh.glowEmissiveOnly,
  111766. color: mesh.color.asArray(),
  111767. meshId: mesh.mesh.id
  111768. });
  111769. }
  111770. }
  111771. }
  111772. // Excluded meshes
  111773. serializationObject.excludedMeshes = [];
  111774. if (this._excludedMeshes) {
  111775. for (var e in this._excludedMeshes) {
  111776. var excludedMesh = this._excludedMeshes[e];
  111777. if (excludedMesh) {
  111778. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  111779. }
  111780. }
  111781. }
  111782. return serializationObject;
  111783. };
  111784. /**
  111785. * Creates a Highlight layer from parsed Highlight layer data
  111786. * @param parsedHightlightLayer defines the Highlight layer data
  111787. * @param scene defines the current scene
  111788. * @param rootUrl defines the root URL containing the Highlight layer information
  111789. * @returns a parsed Highlight layer
  111790. */
  111791. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  111792. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  111793. var index;
  111794. // Excluded meshes
  111795. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  111796. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  111797. if (mesh) {
  111798. hl.addExcludedMesh(mesh);
  111799. }
  111800. }
  111801. // Included meshes
  111802. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  111803. var highlightedMesh = parsedHightlightLayer.meshes[index];
  111804. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  111805. if (mesh) {
  111806. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  111807. }
  111808. }
  111809. return hl;
  111810. };
  111811. /**
  111812. * Effect Name of the highlight layer.
  111813. */
  111814. HighlightLayer.EffectName = "HighlightLayer";
  111815. /**
  111816. * The neutral color used during the preparation of the glow effect.
  111817. * This is black by default as the blend operation is a blend operation.
  111818. */
  111819. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  111820. /**
  111821. * Stencil value used for glowing meshes.
  111822. */
  111823. HighlightLayer.GlowingMeshStencilReference = 0x02;
  111824. /**
  111825. * Stencil value used for the other meshes in the scene.
  111826. */
  111827. HighlightLayer.NormalMeshStencilReference = 0x01;
  111828. __decorate([
  111829. BABYLON.serialize()
  111830. ], HighlightLayer.prototype, "innerGlow", void 0);
  111831. __decorate([
  111832. BABYLON.serialize()
  111833. ], HighlightLayer.prototype, "outerGlow", void 0);
  111834. __decorate([
  111835. BABYLON.serialize()
  111836. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  111837. __decorate([
  111838. BABYLON.serialize()
  111839. ], HighlightLayer.prototype, "blurVerticalSize", null);
  111840. __decorate([
  111841. BABYLON.serialize("options")
  111842. ], HighlightLayer.prototype, "_options", void 0);
  111843. return HighlightLayer;
  111844. }(BABYLON.EffectLayer));
  111845. BABYLON.HighlightLayer = HighlightLayer;
  111846. })(BABYLON || (BABYLON = {}));
  111847. //# sourceMappingURL=babylon.highlightLayer.js.map
  111848. var BABYLON;
  111849. (function (BABYLON) {
  111850. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  111851. for (var index = 0; index < this.effectLayers.length; index++) {
  111852. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  111853. return this.effectLayers[index];
  111854. }
  111855. }
  111856. return null;
  111857. };
  111858. /**
  111859. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  111860. *
  111861. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  111862. * glowy meshes to your scene.
  111863. *
  111864. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  111865. */
  111866. var GlowLayer = /** @class */ (function (_super) {
  111867. __extends(GlowLayer, _super);
  111868. /**
  111869. * Instantiates a new glow Layer and references it to the scene.
  111870. * @param name The name of the layer
  111871. * @param scene The scene to use the layer in
  111872. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  111873. */
  111874. function GlowLayer(name, scene, options) {
  111875. var _this = _super.call(this, name, scene) || this;
  111876. _this._intensity = 1.0;
  111877. _this._includedOnlyMeshes = [];
  111878. _this._excludedMeshes = [];
  111879. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  111880. // Adapt options
  111881. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  111882. // Initialize the layer
  111883. _this._init({
  111884. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  111885. camera: _this._options.camera,
  111886. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  111887. mainTextureRatio: _this._options.mainTextureRatio,
  111888. renderingGroupId: _this._options.renderingGroupId
  111889. });
  111890. return _this;
  111891. }
  111892. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  111893. /**
  111894. * Gets the kernel size of the blur.
  111895. */
  111896. get: function () {
  111897. return this._horizontalBlurPostprocess1.kernel;
  111898. },
  111899. /**
  111900. * Sets the kernel size of the blur.
  111901. */
  111902. set: function (value) {
  111903. this._horizontalBlurPostprocess1.kernel = value;
  111904. this._verticalBlurPostprocess1.kernel = value;
  111905. this._horizontalBlurPostprocess2.kernel = value;
  111906. this._verticalBlurPostprocess2.kernel = value;
  111907. },
  111908. enumerable: true,
  111909. configurable: true
  111910. });
  111911. Object.defineProperty(GlowLayer.prototype, "intensity", {
  111912. /**
  111913. * Gets the glow intensity.
  111914. */
  111915. get: function () {
  111916. return this._intensity;
  111917. },
  111918. /**
  111919. * Sets the glow intensity.
  111920. */
  111921. set: function (value) {
  111922. this._intensity = value;
  111923. },
  111924. enumerable: true,
  111925. configurable: true
  111926. });
  111927. /**
  111928. * Get the effect name of the layer.
  111929. * @return The effect name
  111930. */
  111931. GlowLayer.prototype.getEffectName = function () {
  111932. return GlowLayer.EffectName;
  111933. };
  111934. /**
  111935. * Create the merge effect. This is the shader use to blit the information back
  111936. * to the main canvas at the end of the scene rendering.
  111937. */
  111938. GlowLayer.prototype._createMergeEffect = function () {
  111939. // Effect
  111940. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  111941. };
  111942. /**
  111943. * Creates the render target textures and post processes used in the glow layer.
  111944. */
  111945. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  111946. var _this = this;
  111947. var blurTextureWidth = this._mainTextureDesiredSize.width;
  111948. var blurTextureHeight = this._mainTextureDesiredSize.height;
  111949. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  111950. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  111951. var textureType = 0;
  111952. if (this._engine.getCaps().textureHalfFloatRender) {
  111953. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  111954. }
  111955. else {
  111956. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111957. }
  111958. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  111959. width: blurTextureWidth,
  111960. height: blurTextureHeight
  111961. }, this._scene, false, true, textureType);
  111962. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111963. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111964. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111965. this._blurTexture1.renderParticles = false;
  111966. this._blurTexture1.ignoreCameraViewport = true;
  111967. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  111968. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  111969. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  111970. width: blurTextureWidth2,
  111971. height: blurTextureHeight2
  111972. }, this._scene, false, true, textureType);
  111973. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111974. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111975. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111976. this._blurTexture2.renderParticles = false;
  111977. this._blurTexture2.ignoreCameraViewport = true;
  111978. this._textures = [this._blurTexture1, this._blurTexture2];
  111979. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  111980. width: blurTextureWidth,
  111981. height: blurTextureHeight
  111982. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111983. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  111984. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  111985. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  111986. effect.setTexture("textureSampler", _this._mainTexture);
  111987. });
  111988. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  111989. width: blurTextureWidth,
  111990. height: blurTextureHeight
  111991. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111992. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  111993. width: blurTextureWidth2,
  111994. height: blurTextureHeight2
  111995. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  111996. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  111997. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  111998. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  111999. effect.setTexture("textureSampler", _this._blurTexture1);
  112000. });
  112001. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  112002. width: blurTextureWidth2,
  112003. height: blurTextureHeight2
  112004. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112005. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112006. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  112007. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112008. this._mainTexture.samples = this._options.mainTextureSamples;
  112009. this._mainTexture.onAfterUnbindObservable.add(function () {
  112010. var internalTexture = _this._blurTexture1.getInternalTexture();
  112011. if (internalTexture) {
  112012. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  112013. internalTexture = _this._blurTexture2.getInternalTexture();
  112014. if (internalTexture) {
  112015. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  112016. }
  112017. }
  112018. });
  112019. // Prevent autoClear.
  112020. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  112021. };
  112022. /**
  112023. * Checks for the readiness of the element composing the layer.
  112024. * @param subMesh the mesh to check for
  112025. * @param useInstances specify wether or not to use instances to render the mesh
  112026. * @param emissiveTexture the associated emissive texture used to generate the glow
  112027. * @return true if ready otherwise, false
  112028. */
  112029. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  112030. var material = subMesh.getMaterial();
  112031. var mesh = subMesh.getRenderingMesh();
  112032. if (!material || !mesh) {
  112033. return false;
  112034. }
  112035. var emissiveTexture = material.emissiveTexture;
  112036. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  112037. };
  112038. /**
  112039. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  112040. */
  112041. GlowLayer.prototype.needStencil = function () {
  112042. return false;
  112043. };
  112044. /**
  112045. * Implementation specific of rendering the generating effect on the main canvas.
  112046. * @param effect The effect used to render through
  112047. */
  112048. GlowLayer.prototype._internalRender = function (effect) {
  112049. // Texture
  112050. effect.setTexture("textureSampler", this._blurTexture1);
  112051. effect.setTexture("textureSampler2", this._blurTexture2);
  112052. effect.setFloat("offset", this._intensity);
  112053. // Cache
  112054. var engine = this._engine;
  112055. var previousStencilBuffer = engine.getStencilBuffer();
  112056. // Draw order
  112057. engine.setStencilBuffer(false);
  112058. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112059. // Draw order
  112060. engine.setStencilBuffer(previousStencilBuffer);
  112061. };
  112062. /**
  112063. * Sets the required values for both the emissive texture and and the main color.
  112064. */
  112065. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  112066. var textureLevel = 1.0;
  112067. if (this.customEmissiveTextureSelector) {
  112068. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  112069. }
  112070. else {
  112071. if (material) {
  112072. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  112073. if (this._emissiveTextureAndColor.texture) {
  112074. textureLevel = this._emissiveTextureAndColor.texture.level;
  112075. }
  112076. }
  112077. else {
  112078. this._emissiveTextureAndColor.texture = null;
  112079. }
  112080. }
  112081. if (this.customEmissiveColorSelector) {
  112082. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  112083. }
  112084. else {
  112085. if (material.emissiveColor) {
  112086. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  112087. }
  112088. else {
  112089. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  112090. }
  112091. }
  112092. };
  112093. /**
  112094. * Returns true if the mesh should render, otherwise false.
  112095. * @param mesh The mesh to render
  112096. * @returns true if it should render otherwise false
  112097. */
  112098. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  112099. return this.hasMesh(mesh);
  112100. };
  112101. /**
  112102. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  112103. * @param mesh The mesh to exclude from the glow layer
  112104. */
  112105. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  112106. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  112107. this._excludedMeshes.push(mesh.uniqueId);
  112108. }
  112109. };
  112110. /**
  112111. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  112112. * @param mesh The mesh to remove
  112113. */
  112114. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  112115. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  112116. if (index !== -1) {
  112117. this._excludedMeshes.splice(index, 1);
  112118. }
  112119. };
  112120. /**
  112121. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  112122. * @param mesh The mesh to include in the glow layer
  112123. */
  112124. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  112125. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  112126. this._includedOnlyMeshes.push(mesh.uniqueId);
  112127. }
  112128. };
  112129. /**
  112130. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  112131. * @param mesh The mesh to remove
  112132. */
  112133. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  112134. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  112135. if (index !== -1) {
  112136. this._includedOnlyMeshes.splice(index, 1);
  112137. }
  112138. };
  112139. /**
  112140. * Determine if a given mesh will be used in the glow layer
  112141. * @param mesh The mesh to test
  112142. * @returns true if the mesh will be highlighted by the current glow layer
  112143. */
  112144. GlowLayer.prototype.hasMesh = function (mesh) {
  112145. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112146. return false;
  112147. }
  112148. // Included Mesh
  112149. if (this._includedOnlyMeshes.length) {
  112150. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  112151. }
  112152. // Excluded Mesh
  112153. if (this._excludedMeshes.length) {
  112154. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  112155. }
  112156. return true;
  112157. };
  112158. /**
  112159. * Free any resources and references associated to a mesh.
  112160. * Internal use
  112161. * @param mesh The mesh to free.
  112162. * @hidden
  112163. */
  112164. GlowLayer.prototype._disposeMesh = function (mesh) {
  112165. this.removeIncludedOnlyMesh(mesh);
  112166. this.removeExcludedMesh(mesh);
  112167. };
  112168. /**
  112169. * Gets the class name of the effect layer
  112170. * @returns the string with the class name of the effect layer
  112171. */
  112172. GlowLayer.prototype.getClassName = function () {
  112173. return "GlowLayer";
  112174. };
  112175. /**
  112176. * Serializes this glow layer
  112177. * @returns a serialized glow layer object
  112178. */
  112179. GlowLayer.prototype.serialize = function () {
  112180. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112181. serializationObject.customType = "BABYLON.GlowLayer";
  112182. var index;
  112183. // Included meshes
  112184. serializationObject.includedMeshes = [];
  112185. if (this._includedOnlyMeshes.length) {
  112186. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  112187. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  112188. if (mesh) {
  112189. serializationObject.includedMeshes.push(mesh.id);
  112190. }
  112191. }
  112192. }
  112193. // Excluded meshes
  112194. serializationObject.excludedMeshes = [];
  112195. if (this._excludedMeshes.length) {
  112196. for (index = 0; index < this._excludedMeshes.length; index++) {
  112197. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  112198. if (mesh) {
  112199. serializationObject.excludedMeshes.push(mesh.id);
  112200. }
  112201. }
  112202. }
  112203. return serializationObject;
  112204. };
  112205. /**
  112206. * Creates a Glow Layer from parsed glow layer data
  112207. * @param parsedGlowLayer defines glow layer data
  112208. * @param scene defines the current scene
  112209. * @param rootUrl defines the root URL containing the glow layer information
  112210. * @returns a parsed Glow Layer
  112211. */
  112212. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  112213. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  112214. var index;
  112215. // Excluded meshes
  112216. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  112217. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  112218. if (mesh) {
  112219. gl.addExcludedMesh(mesh);
  112220. }
  112221. }
  112222. // Included meshes
  112223. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  112224. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  112225. if (mesh) {
  112226. gl.addIncludedOnlyMesh(mesh);
  112227. }
  112228. }
  112229. return gl;
  112230. };
  112231. /**
  112232. * Effect Name of the layer.
  112233. */
  112234. GlowLayer.EffectName = "GlowLayer";
  112235. /**
  112236. * The default blur kernel size used for the glow.
  112237. */
  112238. GlowLayer.DefaultBlurKernelSize = 32;
  112239. /**
  112240. * The default texture size ratio used for the glow.
  112241. */
  112242. GlowLayer.DefaultTextureRatio = 0.5;
  112243. __decorate([
  112244. BABYLON.serialize()
  112245. ], GlowLayer.prototype, "blurKernelSize", null);
  112246. __decorate([
  112247. BABYLON.serialize()
  112248. ], GlowLayer.prototype, "intensity", null);
  112249. __decorate([
  112250. BABYLON.serialize("options")
  112251. ], GlowLayer.prototype, "_options", void 0);
  112252. return GlowLayer;
  112253. }(BABYLON.EffectLayer));
  112254. BABYLON.GlowLayer = GlowLayer;
  112255. })(BABYLON || (BABYLON = {}));
  112256. //# sourceMappingURL=babylon.glowLayer.js.map
  112257. var BABYLON;
  112258. (function (BABYLON) {
  112259. /**
  112260. * Defines the list of states available for a task inside a AssetsManager
  112261. */
  112262. var AssetTaskState;
  112263. (function (AssetTaskState) {
  112264. /**
  112265. * Initialization
  112266. */
  112267. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  112268. /**
  112269. * Running
  112270. */
  112271. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  112272. /**
  112273. * Done
  112274. */
  112275. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  112276. /**
  112277. * Error
  112278. */
  112279. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  112280. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  112281. /**
  112282. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  112283. */
  112284. var AbstractAssetTask = /** @class */ (function () {
  112285. /**
  112286. * Creates a new AssetsManager
  112287. * @param name defines the name of the task
  112288. */
  112289. function AbstractAssetTask(
  112290. /**
  112291. * Task name
  112292. */ name) {
  112293. this.name = name;
  112294. this._isCompleted = false;
  112295. this._taskState = AssetTaskState.INIT;
  112296. }
  112297. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  112298. /**
  112299. * Get if the task is completed
  112300. */
  112301. get: function () {
  112302. return this._isCompleted;
  112303. },
  112304. enumerable: true,
  112305. configurable: true
  112306. });
  112307. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  112308. /**
  112309. * Gets the current state of the task
  112310. */
  112311. get: function () {
  112312. return this._taskState;
  112313. },
  112314. enumerable: true,
  112315. configurable: true
  112316. });
  112317. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  112318. /**
  112319. * Gets the current error object (if task is in error)
  112320. */
  112321. get: function () {
  112322. return this._errorObject;
  112323. },
  112324. enumerable: true,
  112325. configurable: true
  112326. });
  112327. /**
  112328. * Internal only
  112329. * @hidden
  112330. */
  112331. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  112332. if (this._errorObject) {
  112333. return;
  112334. }
  112335. this._errorObject = {
  112336. message: message,
  112337. exception: exception
  112338. };
  112339. };
  112340. /**
  112341. * Execute the current task
  112342. * @param scene defines the scene where you want your assets to be loaded
  112343. * @param onSuccess is a callback called when the task is successfully executed
  112344. * @param onError is a callback called if an error occurs
  112345. */
  112346. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  112347. var _this = this;
  112348. this._taskState = AssetTaskState.RUNNING;
  112349. this.runTask(scene, function () {
  112350. _this.onDoneCallback(onSuccess, onError);
  112351. }, function (msg, exception) {
  112352. _this.onErrorCallback(onError, msg, exception);
  112353. });
  112354. };
  112355. /**
  112356. * Execute the current task
  112357. * @param scene defines the scene where you want your assets to be loaded
  112358. * @param onSuccess is a callback called when the task is successfully executed
  112359. * @param onError is a callback called if an error occurs
  112360. */
  112361. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112362. throw new Error("runTask is not implemented");
  112363. };
  112364. /**
  112365. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  112366. * This can be used with failed tasks that have the reason for failure fixed.
  112367. */
  112368. AbstractAssetTask.prototype.reset = function () {
  112369. this._taskState = AssetTaskState.INIT;
  112370. };
  112371. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  112372. this._taskState = AssetTaskState.ERROR;
  112373. this._errorObject = {
  112374. message: message,
  112375. exception: exception
  112376. };
  112377. if (this.onError) {
  112378. this.onError(this, message, exception);
  112379. }
  112380. onError();
  112381. };
  112382. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  112383. try {
  112384. this._taskState = AssetTaskState.DONE;
  112385. this._isCompleted = true;
  112386. if (this.onSuccess) {
  112387. this.onSuccess(this);
  112388. }
  112389. onSuccess();
  112390. }
  112391. catch (e) {
  112392. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  112393. }
  112394. };
  112395. return AbstractAssetTask;
  112396. }());
  112397. BABYLON.AbstractAssetTask = AbstractAssetTask;
  112398. /**
  112399. * Class used to share progress information about assets loading
  112400. */
  112401. var AssetsProgressEvent = /** @class */ (function () {
  112402. /**
  112403. * Creates a AssetsProgressEvent
  112404. * @param remainingCount defines the number of remaining tasks to process
  112405. * @param totalCount defines the total number of tasks
  112406. * @param task defines the task that was just processed
  112407. */
  112408. function AssetsProgressEvent(remainingCount, totalCount, task) {
  112409. this.remainingCount = remainingCount;
  112410. this.totalCount = totalCount;
  112411. this.task = task;
  112412. }
  112413. return AssetsProgressEvent;
  112414. }());
  112415. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  112416. /**
  112417. * Define a task used by AssetsManager to load meshes
  112418. */
  112419. var MeshAssetTask = /** @class */ (function (_super) {
  112420. __extends(MeshAssetTask, _super);
  112421. /**
  112422. * Creates a new MeshAssetTask
  112423. * @param name defines the name of the task
  112424. * @param meshesNames defines the list of mesh's names you want to load
  112425. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  112426. * @param sceneFilename defines the filename of the scene to load from
  112427. */
  112428. function MeshAssetTask(
  112429. /**
  112430. * Defines the name of the task
  112431. */
  112432. name,
  112433. /**
  112434. * Defines the list of mesh's names you want to load
  112435. */
  112436. meshesNames,
  112437. /**
  112438. * Defines the root url to use as a base to load your meshes and associated resources
  112439. */
  112440. rootUrl,
  112441. /**
  112442. * Defines the filename of the scene to load from
  112443. */
  112444. sceneFilename) {
  112445. var _this = _super.call(this, name) || this;
  112446. _this.name = name;
  112447. _this.meshesNames = meshesNames;
  112448. _this.rootUrl = rootUrl;
  112449. _this.sceneFilename = sceneFilename;
  112450. return _this;
  112451. }
  112452. /**
  112453. * Execute the current task
  112454. * @param scene defines the scene where you want your assets to be loaded
  112455. * @param onSuccess is a callback called when the task is successfully executed
  112456. * @param onError is a callback called if an error occurs
  112457. */
  112458. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112459. var _this = this;
  112460. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  112461. _this.loadedMeshes = meshes;
  112462. _this.loadedParticleSystems = particleSystems;
  112463. _this.loadedSkeletons = skeletons;
  112464. onSuccess();
  112465. }, null, function (scene, message, exception) {
  112466. onError(message, exception);
  112467. });
  112468. };
  112469. return MeshAssetTask;
  112470. }(AbstractAssetTask));
  112471. BABYLON.MeshAssetTask = MeshAssetTask;
  112472. /**
  112473. * Define a task used by AssetsManager to load text content
  112474. */
  112475. var TextFileAssetTask = /** @class */ (function (_super) {
  112476. __extends(TextFileAssetTask, _super);
  112477. /**
  112478. * Creates a new TextFileAssetTask object
  112479. * @param name defines the name of the task
  112480. * @param url defines the location of the file to load
  112481. */
  112482. function TextFileAssetTask(
  112483. /**
  112484. * Defines the name of the task
  112485. */
  112486. name,
  112487. /**
  112488. * Defines the location of the file to load
  112489. */
  112490. url) {
  112491. var _this = _super.call(this, name) || this;
  112492. _this.name = name;
  112493. _this.url = url;
  112494. return _this;
  112495. }
  112496. /**
  112497. * Execute the current task
  112498. * @param scene defines the scene where you want your assets to be loaded
  112499. * @param onSuccess is a callback called when the task is successfully executed
  112500. * @param onError is a callback called if an error occurs
  112501. */
  112502. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112503. var _this = this;
  112504. scene._loadFile(this.url, function (data) {
  112505. _this.text = data;
  112506. onSuccess();
  112507. }, undefined, false, false, function (request, exception) {
  112508. if (request) {
  112509. onError(request.status + " " + request.statusText, exception);
  112510. }
  112511. });
  112512. };
  112513. return TextFileAssetTask;
  112514. }(AbstractAssetTask));
  112515. BABYLON.TextFileAssetTask = TextFileAssetTask;
  112516. /**
  112517. * Define a task used by AssetsManager to load binary data
  112518. */
  112519. var BinaryFileAssetTask = /** @class */ (function (_super) {
  112520. __extends(BinaryFileAssetTask, _super);
  112521. /**
  112522. * Creates a new BinaryFileAssetTask object
  112523. * @param name defines the name of the new task
  112524. * @param url defines the location of the file to load
  112525. */
  112526. function BinaryFileAssetTask(
  112527. /**
  112528. * Defines the name of the task
  112529. */
  112530. name,
  112531. /**
  112532. * Defines the location of the file to load
  112533. */
  112534. url) {
  112535. var _this = _super.call(this, name) || this;
  112536. _this.name = name;
  112537. _this.url = url;
  112538. return _this;
  112539. }
  112540. /**
  112541. * Execute the current task
  112542. * @param scene defines the scene where you want your assets to be loaded
  112543. * @param onSuccess is a callback called when the task is successfully executed
  112544. * @param onError is a callback called if an error occurs
  112545. */
  112546. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112547. var _this = this;
  112548. scene._loadFile(this.url, function (data) {
  112549. _this.data = data;
  112550. onSuccess();
  112551. }, undefined, true, true, function (request, exception) {
  112552. if (request) {
  112553. onError(request.status + " " + request.statusText, exception);
  112554. }
  112555. });
  112556. };
  112557. return BinaryFileAssetTask;
  112558. }(AbstractAssetTask));
  112559. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  112560. /**
  112561. * Define a task used by AssetsManager to load images
  112562. */
  112563. var ImageAssetTask = /** @class */ (function (_super) {
  112564. __extends(ImageAssetTask, _super);
  112565. /**
  112566. * Creates a new ImageAssetTask
  112567. * @param name defines the name of the task
  112568. * @param url defines the location of the image to load
  112569. */
  112570. function ImageAssetTask(
  112571. /**
  112572. * Defines the name of the task
  112573. */
  112574. name,
  112575. /**
  112576. * Defines the location of the image to load
  112577. */
  112578. url) {
  112579. var _this = _super.call(this, name) || this;
  112580. _this.name = name;
  112581. _this.url = url;
  112582. return _this;
  112583. }
  112584. /**
  112585. * Execute the current task
  112586. * @param scene defines the scene where you want your assets to be loaded
  112587. * @param onSuccess is a callback called when the task is successfully executed
  112588. * @param onError is a callback called if an error occurs
  112589. */
  112590. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112591. var _this = this;
  112592. var img = new Image();
  112593. BABYLON.Tools.SetCorsBehavior(this.url, img);
  112594. img.onload = function () {
  112595. _this.image = img;
  112596. onSuccess();
  112597. };
  112598. img.onerror = function (err) {
  112599. onError("Error loading image", err);
  112600. };
  112601. img.src = this.url;
  112602. };
  112603. return ImageAssetTask;
  112604. }(AbstractAssetTask));
  112605. BABYLON.ImageAssetTask = ImageAssetTask;
  112606. /**
  112607. * Define a task used by AssetsManager to load 2D textures
  112608. */
  112609. var TextureAssetTask = /** @class */ (function (_super) {
  112610. __extends(TextureAssetTask, _super);
  112611. /**
  112612. * Creates a new TextureAssetTask object
  112613. * @param name defines the name of the task
  112614. * @param url defines the location of the file to load
  112615. * @param noMipmap defines if mipmap should not be generated (default is false)
  112616. * @param invertY defines if texture must be inverted on Y axis (default is false)
  112617. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  112618. */
  112619. function TextureAssetTask(
  112620. /**
  112621. * Defines the name of the task
  112622. */
  112623. name,
  112624. /**
  112625. * Defines the location of the file to load
  112626. */
  112627. url,
  112628. /**
  112629. * Defines if mipmap should not be generated (default is false)
  112630. */
  112631. noMipmap,
  112632. /**
  112633. * Defines if texture must be inverted on Y axis (default is false)
  112634. */
  112635. invertY,
  112636. /**
  112637. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  112638. */
  112639. samplingMode) {
  112640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  112641. var _this = _super.call(this, name) || this;
  112642. _this.name = name;
  112643. _this.url = url;
  112644. _this.noMipmap = noMipmap;
  112645. _this.invertY = invertY;
  112646. _this.samplingMode = samplingMode;
  112647. return _this;
  112648. }
  112649. /**
  112650. * Execute the current task
  112651. * @param scene defines the scene where you want your assets to be loaded
  112652. * @param onSuccess is a callback called when the task is successfully executed
  112653. * @param onError is a callback called if an error occurs
  112654. */
  112655. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112656. var onload = function () {
  112657. onSuccess();
  112658. };
  112659. var onerror = function (message, exception) {
  112660. onError(message, exception);
  112661. };
  112662. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  112663. };
  112664. return TextureAssetTask;
  112665. }(AbstractAssetTask));
  112666. BABYLON.TextureAssetTask = TextureAssetTask;
  112667. /**
  112668. * Define a task used by AssetsManager to load cube textures
  112669. */
  112670. var CubeTextureAssetTask = /** @class */ (function (_super) {
  112671. __extends(CubeTextureAssetTask, _super);
  112672. /**
  112673. * Creates a new CubeTextureAssetTask
  112674. * @param name defines the name of the task
  112675. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  112676. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  112677. * @param noMipmap defines if mipmaps should not be generated (default is false)
  112678. * @param files defines the explicit list of files (undefined by default)
  112679. */
  112680. function CubeTextureAssetTask(
  112681. /**
  112682. * Defines the name of the task
  112683. */
  112684. name,
  112685. /**
  112686. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  112687. */
  112688. url,
  112689. /**
  112690. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  112691. */
  112692. extensions,
  112693. /**
  112694. * Defines if mipmaps should not be generated (default is false)
  112695. */
  112696. noMipmap,
  112697. /**
  112698. * Defines the explicit list of files (undefined by default)
  112699. */
  112700. files) {
  112701. var _this = _super.call(this, name) || this;
  112702. _this.name = name;
  112703. _this.url = url;
  112704. _this.extensions = extensions;
  112705. _this.noMipmap = noMipmap;
  112706. _this.files = files;
  112707. return _this;
  112708. }
  112709. /**
  112710. * Execute the current task
  112711. * @param scene defines the scene where you want your assets to be loaded
  112712. * @param onSuccess is a callback called when the task is successfully executed
  112713. * @param onError is a callback called if an error occurs
  112714. */
  112715. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112716. var onload = function () {
  112717. onSuccess();
  112718. };
  112719. var onerror = function (message, exception) {
  112720. onError(message, exception);
  112721. };
  112722. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  112723. };
  112724. return CubeTextureAssetTask;
  112725. }(AbstractAssetTask));
  112726. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  112727. /**
  112728. * Define a task used by AssetsManager to load HDR cube textures
  112729. */
  112730. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  112731. __extends(HDRCubeTextureAssetTask, _super);
  112732. /**
  112733. * Creates a new HDRCubeTextureAssetTask object
  112734. * @param name defines the name of the task
  112735. * @param url defines the location of the file to load
  112736. * @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.
  112737. * @param noMipmap defines if mipmaps should not be generated (default is false)
  112738. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  112739. * @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)
  112740. * @param reserved Internal use only
  112741. */
  112742. function HDRCubeTextureAssetTask(
  112743. /**
  112744. * Defines the name of the task
  112745. */
  112746. name,
  112747. /**
  112748. * Defines the location of the file to load
  112749. */
  112750. url,
  112751. /**
  112752. * Defines the desired size (the more it increases the longer the generation will be)
  112753. */
  112754. size,
  112755. /**
  112756. * Defines if mipmaps should not be generated (default is false)
  112757. */
  112758. noMipmap,
  112759. /**
  112760. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  112761. */
  112762. generateHarmonics,
  112763. /**
  112764. * 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)
  112765. */
  112766. gammaSpace,
  112767. /**
  112768. * Internal Use Only
  112769. */
  112770. reserved) {
  112771. if (noMipmap === void 0) { noMipmap = false; }
  112772. if (generateHarmonics === void 0) { generateHarmonics = true; }
  112773. if (gammaSpace === void 0) { gammaSpace = false; }
  112774. if (reserved === void 0) { reserved = false; }
  112775. var _this = _super.call(this, name) || this;
  112776. _this.name = name;
  112777. _this.url = url;
  112778. _this.size = size;
  112779. _this.noMipmap = noMipmap;
  112780. _this.generateHarmonics = generateHarmonics;
  112781. _this.gammaSpace = gammaSpace;
  112782. _this.reserved = reserved;
  112783. return _this;
  112784. }
  112785. /**
  112786. * Execute the current task
  112787. * @param scene defines the scene where you want your assets to be loaded
  112788. * @param onSuccess is a callback called when the task is successfully executed
  112789. * @param onError is a callback called if an error occurs
  112790. */
  112791. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  112792. var onload = function () {
  112793. onSuccess();
  112794. };
  112795. var onerror = function (message, exception) {
  112796. onError(message, exception);
  112797. };
  112798. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  112799. };
  112800. return HDRCubeTextureAssetTask;
  112801. }(AbstractAssetTask));
  112802. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  112803. /**
  112804. * This class can be used to easily import assets into a scene
  112805. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  112806. */
  112807. var AssetsManager = /** @class */ (function () {
  112808. /**
  112809. * Creates a new AssetsManager
  112810. * @param scene defines the scene to work on
  112811. */
  112812. function AssetsManager(scene) {
  112813. this._isLoading = false;
  112814. this._tasks = new Array();
  112815. this._waitingTasksCount = 0;
  112816. this._totalTasksCount = 0;
  112817. /**
  112818. * Observable called when all tasks are processed
  112819. */
  112820. this.onTaskSuccessObservable = new BABYLON.Observable();
  112821. /**
  112822. * Observable called when a task had an error
  112823. */
  112824. this.onTaskErrorObservable = new BABYLON.Observable();
  112825. /**
  112826. * Observable called when a task is successful
  112827. */
  112828. this.onTasksDoneObservable = new BABYLON.Observable();
  112829. /**
  112830. * Observable called when a task is done (whatever the result is)
  112831. */
  112832. this.onProgressObservable = new BABYLON.Observable();
  112833. /**
  112834. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  112835. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  112836. */
  112837. this.useDefaultLoadingScreen = true;
  112838. this._scene = scene;
  112839. }
  112840. /**
  112841. * Add a MeshAssetTask to the list of active tasks
  112842. * @param taskName defines the name of the new task
  112843. * @param meshesNames defines the name of meshes to load
  112844. * @param rootUrl defines the root url to use to locate files
  112845. * @param sceneFilename defines the filename of the scene file
  112846. * @returns a new MeshAssetTask object
  112847. */
  112848. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  112849. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  112850. this._tasks.push(task);
  112851. return task;
  112852. };
  112853. /**
  112854. * Add a TextFileAssetTask to the list of active tasks
  112855. * @param taskName defines the name of the new task
  112856. * @param url defines the url of the file to load
  112857. * @returns a new TextFileAssetTask object
  112858. */
  112859. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  112860. var task = new TextFileAssetTask(taskName, url);
  112861. this._tasks.push(task);
  112862. return task;
  112863. };
  112864. /**
  112865. * Add a BinaryFileAssetTask to the list of active tasks
  112866. * @param taskName defines the name of the new task
  112867. * @param url defines the url of the file to load
  112868. * @returns a new BinaryFileAssetTask object
  112869. */
  112870. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  112871. var task = new BinaryFileAssetTask(taskName, url);
  112872. this._tasks.push(task);
  112873. return task;
  112874. };
  112875. /**
  112876. * Add a ImageAssetTask to the list of active tasks
  112877. * @param taskName defines the name of the new task
  112878. * @param url defines the url of the file to load
  112879. * @returns a new ImageAssetTask object
  112880. */
  112881. AssetsManager.prototype.addImageTask = function (taskName, url) {
  112882. var task = new ImageAssetTask(taskName, url);
  112883. this._tasks.push(task);
  112884. return task;
  112885. };
  112886. /**
  112887. * Add a TextureAssetTask to the list of active tasks
  112888. * @param taskName defines the name of the new task
  112889. * @param url defines the url of the file to load
  112890. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  112891. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  112892. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  112893. * @returns a new TextureAssetTask object
  112894. */
  112895. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  112896. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  112897. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  112898. this._tasks.push(task);
  112899. return task;
  112900. };
  112901. /**
  112902. * Add a CubeTextureAssetTask to the list of active tasks
  112903. * @param taskName defines the name of the new task
  112904. * @param url defines the url of the file to load
  112905. * @param extensions defines the extension to use to load the cube map (can be null)
  112906. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  112907. * @param files defines the list of files to load (can be null)
  112908. * @returns a new CubeTextureAssetTask object
  112909. */
  112910. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  112911. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  112912. this._tasks.push(task);
  112913. return task;
  112914. };
  112915. /**
  112916. *
  112917. * Add a HDRCubeTextureAssetTask to the list of active tasks
  112918. * @param taskName defines the name of the new task
  112919. * @param url defines the url of the file to load
  112920. * @param size defines the size you want for the cubemap (can be null)
  112921. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  112922. * @param generateHarmonics defines if you want to automatically generate (true by default)
  112923. * @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)
  112924. * @param reserved Internal use only
  112925. * @returns a new HDRCubeTextureAssetTask object
  112926. */
  112927. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  112928. if (noMipmap === void 0) { noMipmap = false; }
  112929. if (generateHarmonics === void 0) { generateHarmonics = true; }
  112930. if (gammaSpace === void 0) { gammaSpace = false; }
  112931. if (reserved === void 0) { reserved = false; }
  112932. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  112933. this._tasks.push(task);
  112934. return task;
  112935. };
  112936. /**
  112937. * Remove a task from the assets manager.
  112938. * @param task the task to remove
  112939. */
  112940. AssetsManager.prototype.removeTask = function (task) {
  112941. var index = this._tasks.indexOf(task);
  112942. if (index > -1) {
  112943. this._tasks.splice(index, 1);
  112944. }
  112945. };
  112946. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  112947. this._waitingTasksCount--;
  112948. try {
  112949. if (this.onProgress) {
  112950. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  112951. }
  112952. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  112953. }
  112954. catch (e) {
  112955. BABYLON.Tools.Error("Error running progress callbacks.");
  112956. console.log(e);
  112957. }
  112958. if (this._waitingTasksCount === 0) {
  112959. try {
  112960. if (this.onFinish) {
  112961. this.onFinish(this._tasks);
  112962. }
  112963. // Let's remove successfull tasks
  112964. var currentTasks = this._tasks.slice();
  112965. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  112966. var task = currentTasks_1[_i];
  112967. if (task.taskState === AssetTaskState.DONE) {
  112968. var index = this._tasks.indexOf(task);
  112969. if (index > -1) {
  112970. this._tasks.splice(index, 1);
  112971. }
  112972. }
  112973. }
  112974. this.onTasksDoneObservable.notifyObservers(this._tasks);
  112975. }
  112976. catch (e) {
  112977. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  112978. console.log(e);
  112979. }
  112980. this._isLoading = false;
  112981. this._scene.getEngine().hideLoadingUI();
  112982. }
  112983. };
  112984. AssetsManager.prototype._runTask = function (task) {
  112985. var _this = this;
  112986. var done = function () {
  112987. try {
  112988. if (_this.onTaskSuccess) {
  112989. _this.onTaskSuccess(task);
  112990. }
  112991. _this.onTaskSuccessObservable.notifyObservers(task);
  112992. _this._decreaseWaitingTasksCount(task);
  112993. }
  112994. catch (e) {
  112995. error("Error executing task success callbacks", e);
  112996. }
  112997. };
  112998. var error = function (message, exception) {
  112999. task._setErrorObject(message, exception);
  113000. if (_this.onTaskError) {
  113001. _this.onTaskError(task);
  113002. }
  113003. _this.onTaskErrorObservable.notifyObservers(task);
  113004. _this._decreaseWaitingTasksCount(task);
  113005. };
  113006. task.run(this._scene, done, error);
  113007. };
  113008. /**
  113009. * Reset the AssetsManager and remove all tasks
  113010. * @return the current instance of the AssetsManager
  113011. */
  113012. AssetsManager.prototype.reset = function () {
  113013. this._isLoading = false;
  113014. this._tasks = new Array();
  113015. return this;
  113016. };
  113017. /**
  113018. * Start the loading process
  113019. * @return the current instance of the AssetsManager
  113020. */
  113021. AssetsManager.prototype.load = function () {
  113022. if (this._isLoading) {
  113023. return this;
  113024. }
  113025. this._isLoading = true;
  113026. this._waitingTasksCount = this._tasks.length;
  113027. this._totalTasksCount = this._tasks.length;
  113028. if (this._waitingTasksCount === 0) {
  113029. this._isLoading = false;
  113030. if (this.onFinish) {
  113031. this.onFinish(this._tasks);
  113032. }
  113033. this.onTasksDoneObservable.notifyObservers(this._tasks);
  113034. return this;
  113035. }
  113036. if (this.useDefaultLoadingScreen) {
  113037. this._scene.getEngine().displayLoadingUI();
  113038. }
  113039. for (var index = 0; index < this._tasks.length; index++) {
  113040. var task = this._tasks[index];
  113041. if (task.taskState === AssetTaskState.INIT) {
  113042. this._runTask(task);
  113043. }
  113044. }
  113045. return this;
  113046. };
  113047. return AssetsManager;
  113048. }());
  113049. BABYLON.AssetsManager = AssetsManager;
  113050. })(BABYLON || (BABYLON = {}));
  113051. //# sourceMappingURL=babylon.assetsManager.js.map
  113052. var BABYLON;
  113053. (function (BABYLON) {
  113054. var serializedGeometries = [];
  113055. var serializeGeometry = function (geometry, serializationGeometries) {
  113056. if (serializedGeometries[geometry.id]) {
  113057. return;
  113058. }
  113059. if (geometry.doNotSerialize) {
  113060. return;
  113061. }
  113062. if (geometry instanceof BABYLON.BoxGeometry) {
  113063. serializationGeometries.boxes.push(geometry.serialize());
  113064. }
  113065. else if (geometry instanceof BABYLON.SphereGeometry) {
  113066. serializationGeometries.spheres.push(geometry.serialize());
  113067. }
  113068. else if (geometry instanceof BABYLON.CylinderGeometry) {
  113069. serializationGeometries.cylinders.push(geometry.serialize());
  113070. }
  113071. else if (geometry instanceof BABYLON.TorusGeometry) {
  113072. serializationGeometries.toruses.push(geometry.serialize());
  113073. }
  113074. else if (geometry instanceof BABYLON.GroundGeometry) {
  113075. serializationGeometries.grounds.push(geometry.serialize());
  113076. }
  113077. else if (geometry instanceof BABYLON.Plane) {
  113078. serializationGeometries.planes.push(geometry.serialize());
  113079. }
  113080. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  113081. serializationGeometries.torusKnots.push(geometry.serialize());
  113082. }
  113083. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  113084. throw new Error("Unknown primitive type");
  113085. }
  113086. else {
  113087. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  113088. }
  113089. serializedGeometries[geometry.id] = true;
  113090. };
  113091. var serializeMesh = function (mesh, serializationScene) {
  113092. var serializationObject = {};
  113093. // Geometry
  113094. var geometry = mesh._geometry;
  113095. if (geometry) {
  113096. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  113097. // 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
  113098. serializeGeometry(geometry, serializationScene.geometries);
  113099. }
  113100. }
  113101. // Custom
  113102. if (mesh.serialize) {
  113103. mesh.serialize(serializationObject);
  113104. }
  113105. return serializationObject;
  113106. };
  113107. var finalizeSingleMesh = function (mesh, serializationObject) {
  113108. //only works if the mesh is already loaded
  113109. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113110. //serialize material
  113111. if (mesh.material) {
  113112. if (mesh.material instanceof BABYLON.MultiMaterial) {
  113113. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  113114. serializationObject.materials = serializationObject.materials || [];
  113115. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113116. serializationObject.multiMaterials.push(mesh.material.serialize());
  113117. var _loop_1 = function (submaterial) {
  113118. if (submaterial) {
  113119. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  113120. serializationObject.materials.push(submaterial.serialize());
  113121. }
  113122. }
  113123. };
  113124. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  113125. var submaterial = _a[_i];
  113126. _loop_1(submaterial);
  113127. }
  113128. }
  113129. }
  113130. else {
  113131. serializationObject.materials = serializationObject.materials || [];
  113132. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113133. serializationObject.materials.push(mesh.material.serialize());
  113134. }
  113135. }
  113136. }
  113137. //serialize geometry
  113138. var geometry = mesh._geometry;
  113139. if (geometry) {
  113140. if (!serializationObject.geometries) {
  113141. serializationObject.geometries = {};
  113142. serializationObject.geometries.boxes = [];
  113143. serializationObject.geometries.spheres = [];
  113144. serializationObject.geometries.cylinders = [];
  113145. serializationObject.geometries.toruses = [];
  113146. serializationObject.geometries.grounds = [];
  113147. serializationObject.geometries.planes = [];
  113148. serializationObject.geometries.torusKnots = [];
  113149. serializationObject.geometries.vertexData = [];
  113150. }
  113151. serializeGeometry(geometry, serializationObject.geometries);
  113152. }
  113153. // Skeletons
  113154. if (mesh.skeleton) {
  113155. serializationObject.skeletons = serializationObject.skeletons || [];
  113156. serializationObject.skeletons.push(mesh.skeleton.serialize());
  113157. }
  113158. //serialize the actual mesh
  113159. serializationObject.meshes = serializationObject.meshes || [];
  113160. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113161. }
  113162. };
  113163. /**
  113164. * Class used to serialize a scene into a string
  113165. */
  113166. var SceneSerializer = /** @class */ (function () {
  113167. function SceneSerializer() {
  113168. }
  113169. /**
  113170. * Clear cache used by a previous serialization
  113171. */
  113172. SceneSerializer.ClearCache = function () {
  113173. serializedGeometries = [];
  113174. };
  113175. /**
  113176. * Serialize a scene into a JSON compatible object
  113177. * @param scene defines the scene to serialize
  113178. * @returns a JSON compatible object
  113179. */
  113180. SceneSerializer.Serialize = function (scene) {
  113181. var serializationObject = {};
  113182. SceneSerializer.ClearCache();
  113183. // Scene
  113184. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  113185. serializationObject.autoClear = scene.autoClear;
  113186. serializationObject.clearColor = scene.clearColor.asArray();
  113187. serializationObject.ambientColor = scene.ambientColor.asArray();
  113188. serializationObject.gravity = scene.gravity.asArray();
  113189. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  113190. serializationObject.workerCollisions = scene.workerCollisions;
  113191. // Fog
  113192. if (scene.fogMode && scene.fogMode !== 0) {
  113193. serializationObject.fogMode = scene.fogMode;
  113194. serializationObject.fogColor = scene.fogColor.asArray();
  113195. serializationObject.fogStart = scene.fogStart;
  113196. serializationObject.fogEnd = scene.fogEnd;
  113197. serializationObject.fogDensity = scene.fogDensity;
  113198. }
  113199. //Physics
  113200. if (scene.isPhysicsEnabled()) {
  113201. var physicEngine = scene.getPhysicsEngine();
  113202. if (physicEngine) {
  113203. serializationObject.physicsEnabled = true;
  113204. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  113205. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  113206. }
  113207. }
  113208. // Metadata
  113209. if (scene.metadata) {
  113210. serializationObject.metadata = scene.metadata;
  113211. }
  113212. // Morph targets
  113213. serializationObject.morphTargetManagers = [];
  113214. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  113215. var abstractMesh = _a[_i];
  113216. var manager = abstractMesh.morphTargetManager;
  113217. if (manager) {
  113218. serializationObject.morphTargetManagers.push(manager.serialize());
  113219. }
  113220. }
  113221. // Lights
  113222. serializationObject.lights = [];
  113223. var index;
  113224. var light;
  113225. for (index = 0; index < scene.lights.length; index++) {
  113226. light = scene.lights[index];
  113227. if (!light.doNotSerialize) {
  113228. serializationObject.lights.push(light.serialize());
  113229. }
  113230. }
  113231. // Cameras
  113232. serializationObject.cameras = [];
  113233. for (index = 0; index < scene.cameras.length; index++) {
  113234. var camera = scene.cameras[index];
  113235. if (!camera.doNotSerialize) {
  113236. serializationObject.cameras.push(camera.serialize());
  113237. }
  113238. }
  113239. if (scene.activeCamera) {
  113240. serializationObject.activeCameraID = scene.activeCamera.id;
  113241. }
  113242. // Animations
  113243. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  113244. // Materials
  113245. serializationObject.materials = [];
  113246. serializationObject.multiMaterials = [];
  113247. var material;
  113248. for (index = 0; index < scene.materials.length; index++) {
  113249. material = scene.materials[index];
  113250. if (!material.doNotSerialize) {
  113251. serializationObject.materials.push(material.serialize());
  113252. }
  113253. }
  113254. // MultiMaterials
  113255. serializationObject.multiMaterials = [];
  113256. for (index = 0; index < scene.multiMaterials.length; index++) {
  113257. var multiMaterial = scene.multiMaterials[index];
  113258. serializationObject.multiMaterials.push(multiMaterial.serialize());
  113259. }
  113260. // Environment texture
  113261. if (scene.environmentTexture) {
  113262. serializationObject.environmentTexture = scene.environmentTexture.name;
  113263. }
  113264. // Skeletons
  113265. serializationObject.skeletons = [];
  113266. for (index = 0; index < scene.skeletons.length; index++) {
  113267. var skeleton = scene.skeletons[index];
  113268. if (!skeleton.doNotSerialize) {
  113269. serializationObject.skeletons.push(skeleton.serialize());
  113270. }
  113271. }
  113272. // Transform nodes
  113273. serializationObject.transformNodes = [];
  113274. for (index = 0; index < scene.transformNodes.length; index++) {
  113275. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  113276. }
  113277. // Geometries
  113278. serializationObject.geometries = {};
  113279. serializationObject.geometries.boxes = [];
  113280. serializationObject.geometries.spheres = [];
  113281. serializationObject.geometries.cylinders = [];
  113282. serializationObject.geometries.toruses = [];
  113283. serializationObject.geometries.grounds = [];
  113284. serializationObject.geometries.planes = [];
  113285. serializationObject.geometries.torusKnots = [];
  113286. serializationObject.geometries.vertexData = [];
  113287. serializedGeometries = [];
  113288. var geometries = scene.getGeometries();
  113289. for (index = 0; index < geometries.length; index++) {
  113290. var geometry = geometries[index];
  113291. if (geometry.isReady()) {
  113292. serializeGeometry(geometry, serializationObject.geometries);
  113293. }
  113294. }
  113295. // Meshes
  113296. serializationObject.meshes = [];
  113297. for (index = 0; index < scene.meshes.length; index++) {
  113298. var abstractMesh = scene.meshes[index];
  113299. if (abstractMesh instanceof BABYLON.Mesh) {
  113300. var mesh = abstractMesh;
  113301. if (!mesh.doNotSerialize) {
  113302. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113303. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113304. }
  113305. }
  113306. }
  113307. }
  113308. // Particles Systems
  113309. serializationObject.particleSystems = [];
  113310. for (index = 0; index < scene.particleSystems.length; index++) {
  113311. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  113312. }
  113313. // Action Manager
  113314. if (scene.actionManager) {
  113315. serializationObject.actions = scene.actionManager.serialize("scene");
  113316. }
  113317. // Components
  113318. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  113319. var component = _c[_b];
  113320. component.serialize(serializationObject);
  113321. }
  113322. return serializationObject;
  113323. };
  113324. /**
  113325. * Serialize a mesh into a JSON compatible object
  113326. * @param toSerialize defines the mesh to serialize
  113327. * @param withParents defines if parents must be serialized as well
  113328. * @param withChildren defines if children must be serialized as well
  113329. * @returns a JSON compatible object
  113330. */
  113331. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  113332. if (withParents === void 0) { withParents = false; }
  113333. if (withChildren === void 0) { withChildren = false; }
  113334. var serializationObject = {};
  113335. SceneSerializer.ClearCache();
  113336. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  113337. if (withParents || withChildren) {
  113338. //deliberate for loop! not for each, appended should be processed as well.
  113339. for (var i = 0; i < toSerialize.length; ++i) {
  113340. if (withChildren) {
  113341. toSerialize[i].getDescendants().forEach(function (node) {
  113342. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  113343. toSerialize.push(node);
  113344. }
  113345. });
  113346. }
  113347. //make sure the array doesn't contain the object already
  113348. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  113349. toSerialize.push(toSerialize[i].parent);
  113350. }
  113351. }
  113352. }
  113353. toSerialize.forEach(function (mesh) {
  113354. finalizeSingleMesh(mesh, serializationObject);
  113355. });
  113356. return serializationObject;
  113357. };
  113358. return SceneSerializer;
  113359. }());
  113360. BABYLON.SceneSerializer = SceneSerializer;
  113361. })(BABYLON || (BABYLON = {}));
  113362. //# sourceMappingURL=babylon.sceneSerializer.js.map
  113363. var BABYLON;
  113364. (function (BABYLON) {
  113365. /**
  113366. * Class used to generate realtime reflection / refraction cube textures
  113367. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  113368. */
  113369. var ReflectionProbe = /** @class */ (function () {
  113370. /**
  113371. * Creates a new reflection probe
  113372. * @param name defines the name of the probe
  113373. * @param size defines the texture resolution (for each face)
  113374. * @param scene defines the hosting scene
  113375. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  113376. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  113377. */
  113378. function ReflectionProbe(
  113379. /** defines the name of the probe */
  113380. name, size, scene, generateMipMaps, useFloat) {
  113381. if (generateMipMaps === void 0) { generateMipMaps = true; }
  113382. if (useFloat === void 0) { useFloat = false; }
  113383. var _this = this;
  113384. this.name = name;
  113385. this._viewMatrix = BABYLON.Matrix.Identity();
  113386. this._target = BABYLON.Vector3.Zero();
  113387. this._add = BABYLON.Vector3.Zero();
  113388. this._invertYAxis = false;
  113389. /** Gets or sets probe position (center of the cube map) */
  113390. this.position = BABYLON.Vector3.Zero();
  113391. this._scene = scene;
  113392. // Create the scene field if not exist.
  113393. if (!this._scene.reflectionProbes) {
  113394. this._scene.reflectionProbes = new Array();
  113395. }
  113396. this._scene.reflectionProbes.push(this);
  113397. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  113398. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  113399. switch (faceIndex) {
  113400. case 0:
  113401. _this._add.copyFromFloats(1, 0, 0);
  113402. break;
  113403. case 1:
  113404. _this._add.copyFromFloats(-1, 0, 0);
  113405. break;
  113406. case 2:
  113407. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  113408. break;
  113409. case 3:
  113410. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  113411. break;
  113412. case 4:
  113413. _this._add.copyFromFloats(0, 0, 1);
  113414. break;
  113415. case 5:
  113416. _this._add.copyFromFloats(0, 0, -1);
  113417. break;
  113418. }
  113419. if (_this._attachedMesh) {
  113420. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  113421. }
  113422. _this.position.addToRef(_this._add, _this._target);
  113423. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  113424. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  113425. scene._forcedViewPosition = _this.position;
  113426. });
  113427. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  113428. scene._forcedViewPosition = null;
  113429. scene.updateTransformMatrix(true);
  113430. });
  113431. if (scene.activeCamera) {
  113432. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  113433. }
  113434. }
  113435. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  113436. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  113437. get: function () {
  113438. return this._renderTargetTexture.samples;
  113439. },
  113440. set: function (value) {
  113441. this._renderTargetTexture.samples = value;
  113442. },
  113443. enumerable: true,
  113444. configurable: true
  113445. });
  113446. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  113447. /** Gets or sets the refresh rate to use (on every frame by default) */
  113448. get: function () {
  113449. return this._renderTargetTexture.refreshRate;
  113450. },
  113451. set: function (value) {
  113452. this._renderTargetTexture.refreshRate = value;
  113453. },
  113454. enumerable: true,
  113455. configurable: true
  113456. });
  113457. /**
  113458. * Gets the hosting scene
  113459. * @returns a Scene
  113460. */
  113461. ReflectionProbe.prototype.getScene = function () {
  113462. return this._scene;
  113463. };
  113464. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  113465. /** Gets the internal CubeTexture used to render to */
  113466. get: function () {
  113467. return this._renderTargetTexture;
  113468. },
  113469. enumerable: true,
  113470. configurable: true
  113471. });
  113472. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  113473. /** Gets the list of meshes to render */
  113474. get: function () {
  113475. return this._renderTargetTexture.renderList;
  113476. },
  113477. enumerable: true,
  113478. configurable: true
  113479. });
  113480. /**
  113481. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  113482. * @param mesh defines the mesh to attach to
  113483. */
  113484. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  113485. this._attachedMesh = mesh;
  113486. };
  113487. /**
  113488. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  113489. * @param renderingGroupId The rendering group id corresponding to its index
  113490. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  113491. */
  113492. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  113493. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  113494. };
  113495. /**
  113496. * Clean all associated resources
  113497. */
  113498. ReflectionProbe.prototype.dispose = function () {
  113499. var index = this._scene.reflectionProbes.indexOf(this);
  113500. if (index !== -1) {
  113501. // Remove from the scene if found
  113502. this._scene.reflectionProbes.splice(index, 1);
  113503. }
  113504. if (this._renderTargetTexture) {
  113505. this._renderTargetTexture.dispose();
  113506. this._renderTargetTexture = null;
  113507. }
  113508. };
  113509. return ReflectionProbe;
  113510. }());
  113511. BABYLON.ReflectionProbe = ReflectionProbe;
  113512. })(BABYLON || (BABYLON = {}));
  113513. //# sourceMappingURL=babylon.reflectionProbe.js.map
  113514. var BABYLON;
  113515. (function (BABYLON) {
  113516. /**
  113517. * Defines the layer scene component responsible to manage any layers
  113518. * in a given scene.
  113519. */
  113520. var LayerSceneComponent = /** @class */ (function () {
  113521. /**
  113522. * Creates a new instance of the component for the given scene
  113523. * @param scene Defines the scene to register the component in
  113524. */
  113525. function LayerSceneComponent(scene) {
  113526. /**
  113527. * The component name helpfull to identify the component in the list of scene components.
  113528. */
  113529. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  113530. this.scene = scene;
  113531. this._engine = scene.getEngine();
  113532. scene.layers = new Array();
  113533. }
  113534. /**
  113535. * Registers the component in a given scene
  113536. */
  113537. LayerSceneComponent.prototype.register = function () {
  113538. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  113539. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  113540. };
  113541. /**
  113542. * Rebuilds the elements related to this component in case of
  113543. * context lost for instance.
  113544. */
  113545. LayerSceneComponent.prototype.rebuild = function () {
  113546. var layers = this.scene.layers;
  113547. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  113548. var layer = layers_1[_i];
  113549. layer._rebuild();
  113550. }
  113551. };
  113552. /**
  113553. * Disposes the component and the associated ressources.
  113554. */
  113555. LayerSceneComponent.prototype.dispose = function () {
  113556. var layers = this.scene.layers;
  113557. while (layers.length) {
  113558. layers[0].dispose();
  113559. }
  113560. };
  113561. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  113562. var layers = this.scene.layers;
  113563. if (layers.length) {
  113564. this._engine.setDepthBuffer(false);
  113565. var cameraLayerMask = camera.layerMask;
  113566. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  113567. var layer = layers_2[_i];
  113568. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  113569. layer.render();
  113570. }
  113571. }
  113572. this._engine.setDepthBuffer(true);
  113573. }
  113574. };
  113575. LayerSceneComponent.prototype._drawBackground = function (camera) {
  113576. this._draw(camera, true);
  113577. };
  113578. LayerSceneComponent.prototype._drawForeground = function (camera) {
  113579. this._draw(camera, false);
  113580. };
  113581. return LayerSceneComponent;
  113582. }());
  113583. BABYLON.LayerSceneComponent = LayerSceneComponent;
  113584. })(BABYLON || (BABYLON = {}));
  113585. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  113586. var BABYLON;
  113587. (function (BABYLON) {
  113588. /**
  113589. * This represents a full screen 2d layer.
  113590. * This can be usefull to display a picture in the background of your scene for instance.
  113591. * @see https://www.babylonjs-playground.com/#08A2BS#1
  113592. */
  113593. var Layer = /** @class */ (function () {
  113594. /**
  113595. * Instantiates a new layer.
  113596. * This represents a full screen 2d layer.
  113597. * This can be usefull to display a picture in the background of your scene for instance.
  113598. * @see https://www.babylonjs-playground.com/#08A2BS#1
  113599. * @param name Define the name of the layer in the scene
  113600. * @param imgUrl Define the url of the texture to display in the layer
  113601. * @param scene Define the scene the layer belongs to
  113602. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  113603. * @param color Defines a color for the layer
  113604. */
  113605. function Layer(
  113606. /**
  113607. * Define the name of the layer.
  113608. */
  113609. name, imgUrl, scene, isBackground, color) {
  113610. this.name = name;
  113611. /**
  113612. * Define the scale of the layer in order to zoom in out of the texture.
  113613. */
  113614. this.scale = new BABYLON.Vector2(1, 1);
  113615. /**
  113616. * Define an offset for the layer in order to shift the texture.
  113617. */
  113618. this.offset = new BABYLON.Vector2(0, 0);
  113619. /**
  113620. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  113621. */
  113622. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  113623. /**
  113624. * Define a mask to restrict the layer to only some of the scene cameras.
  113625. */
  113626. this.layerMask = 0x0FFFFFFF;
  113627. this._vertexBuffers = {};
  113628. /**
  113629. * An event triggered when the layer is disposed.
  113630. */
  113631. this.onDisposeObservable = new BABYLON.Observable();
  113632. /**
  113633. * An event triggered before rendering the scene
  113634. */
  113635. this.onBeforeRenderObservable = new BABYLON.Observable();
  113636. /**
  113637. * An event triggered after rendering the scene
  113638. */
  113639. this.onAfterRenderObservable = new BABYLON.Observable();
  113640. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  113641. this.isBackground = isBackground === undefined ? true : isBackground;
  113642. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  113643. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  113644. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  113645. if (!layerComponent) {
  113646. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  113647. this._scene._addComponent(layerComponent);
  113648. }
  113649. this._scene.layers.push(this);
  113650. var engine = this._scene.getEngine();
  113651. // VBO
  113652. var vertices = [];
  113653. vertices.push(1, 1);
  113654. vertices.push(-1, 1);
  113655. vertices.push(-1, -1);
  113656. vertices.push(1, -1);
  113657. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  113658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  113659. this._createIndexBuffer();
  113660. // Effects
  113661. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  113662. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  113663. }
  113664. Object.defineProperty(Layer.prototype, "onDispose", {
  113665. /**
  113666. * Back compatibility with callback before the onDisposeObservable existed.
  113667. * The set callback will be triggered when the layer has been disposed.
  113668. */
  113669. set: function (callback) {
  113670. if (this._onDisposeObserver) {
  113671. this.onDisposeObservable.remove(this._onDisposeObserver);
  113672. }
  113673. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  113674. },
  113675. enumerable: true,
  113676. configurable: true
  113677. });
  113678. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  113679. /**
  113680. * Back compatibility with callback before the onBeforeRenderObservable existed.
  113681. * The set callback will be triggered just before rendering the layer.
  113682. */
  113683. set: function (callback) {
  113684. if (this._onBeforeRenderObserver) {
  113685. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  113686. }
  113687. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  113688. },
  113689. enumerable: true,
  113690. configurable: true
  113691. });
  113692. Object.defineProperty(Layer.prototype, "onAfterRender", {
  113693. /**
  113694. * Back compatibility with callback before the onAfterRenderObservable existed.
  113695. * The set callback will be triggered just after rendering the layer.
  113696. */
  113697. set: function (callback) {
  113698. if (this._onAfterRenderObserver) {
  113699. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  113700. }
  113701. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  113702. },
  113703. enumerable: true,
  113704. configurable: true
  113705. });
  113706. Layer.prototype._createIndexBuffer = function () {
  113707. var engine = this._scene.getEngine();
  113708. // Indices
  113709. var indices = [];
  113710. indices.push(0);
  113711. indices.push(1);
  113712. indices.push(2);
  113713. indices.push(0);
  113714. indices.push(2);
  113715. indices.push(3);
  113716. this._indexBuffer = engine.createIndexBuffer(indices);
  113717. };
  113718. /** @hidden */
  113719. Layer.prototype._rebuild = function () {
  113720. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  113721. if (vb) {
  113722. vb._rebuild();
  113723. }
  113724. this._createIndexBuffer();
  113725. };
  113726. /**
  113727. * Renders the layer in the scene.
  113728. */
  113729. Layer.prototype.render = function () {
  113730. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  113731. // Check
  113732. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  113733. return;
  113734. }
  113735. var engine = this._scene.getEngine();
  113736. this.onBeforeRenderObservable.notifyObservers(this);
  113737. // Render
  113738. engine.enableEffect(currentEffect);
  113739. engine.setState(false);
  113740. // Texture
  113741. currentEffect.setTexture("textureSampler", this.texture);
  113742. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  113743. // Color
  113744. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  113745. // Scale / offset
  113746. currentEffect.setVector2("offset", this.offset);
  113747. currentEffect.setVector2("scale", this.scale);
  113748. // VBOs
  113749. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  113750. // Draw order
  113751. if (!this.alphaTest) {
  113752. engine.setAlphaMode(this.alphaBlendingMode);
  113753. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  113754. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  113755. }
  113756. else {
  113757. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  113758. }
  113759. this.onAfterRenderObservable.notifyObservers(this);
  113760. };
  113761. /**
  113762. * Disposes and releases the associated ressources.
  113763. */
  113764. Layer.prototype.dispose = function () {
  113765. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  113766. if (vertexBuffer) {
  113767. vertexBuffer.dispose();
  113768. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  113769. }
  113770. if (this._indexBuffer) {
  113771. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  113772. this._indexBuffer = null;
  113773. }
  113774. if (this.texture) {
  113775. this.texture.dispose();
  113776. this.texture = null;
  113777. }
  113778. // Remove from scene
  113779. var index = this._scene.layers.indexOf(this);
  113780. this._scene.layers.splice(index, 1);
  113781. // Callback
  113782. this.onDisposeObservable.notifyObservers(this);
  113783. this.onDisposeObservable.clear();
  113784. this.onAfterRenderObservable.clear();
  113785. this.onBeforeRenderObservable.clear();
  113786. };
  113787. return Layer;
  113788. }());
  113789. BABYLON.Layer = Layer;
  113790. })(BABYLON || (BABYLON = {}));
  113791. //# sourceMappingURL=babylon.layer.js.map
  113792. var BABYLON;
  113793. (function (BABYLON) {
  113794. /**
  113795. * Class used to host texture specific utilities
  113796. */
  113797. var TextureTools = /** @class */ (function () {
  113798. function TextureTools() {
  113799. }
  113800. /**
  113801. * Uses the GPU to create a copy texture rescaled at a given size
  113802. * @param texture Texture to copy from
  113803. * @param width defines the desired width
  113804. * @param height defines the desired height
  113805. * @param useBilinearMode defines if bilinear mode has to be used
  113806. * @return the generated texture
  113807. */
  113808. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  113809. if (useBilinearMode === void 0) { useBilinearMode = true; }
  113810. var scene = texture.getScene();
  113811. var engine = scene.getEngine();
  113812. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  113813. rtt.wrapU = texture.wrapU;
  113814. rtt.wrapV = texture.wrapV;
  113815. rtt.uOffset = texture.uOffset;
  113816. rtt.vOffset = texture.vOffset;
  113817. rtt.uScale = texture.uScale;
  113818. rtt.vScale = texture.vScale;
  113819. rtt.uAng = texture.uAng;
  113820. rtt.vAng = texture.vAng;
  113821. rtt.wAng = texture.wAng;
  113822. rtt.coordinatesIndex = texture.coordinatesIndex;
  113823. rtt.level = texture.level;
  113824. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  113825. rtt._texture.isReady = false;
  113826. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113827. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113828. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  113829. passPostProcess.getEffect().executeWhenCompiled(function () {
  113830. passPostProcess.onApply = function (effect) {
  113831. effect.setTexture("textureSampler", texture);
  113832. };
  113833. var internalTexture = rtt.getInternalTexture();
  113834. if (internalTexture) {
  113835. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  113836. engine.unBindFramebuffer(internalTexture);
  113837. rtt.disposeFramebufferObjects();
  113838. passPostProcess.dispose();
  113839. internalTexture.isReady = true;
  113840. }
  113841. });
  113842. return rtt;
  113843. };
  113844. /**
  113845. * Gets an environment BRDF texture for a given scene
  113846. * @param scene defines the hosting scene
  113847. * @returns the environment BRDF texture
  113848. */
  113849. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  113850. if (!scene._environmentBRDFTexture) {
  113851. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  113852. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113853. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113854. scene._environmentBRDFTexture = texture;
  113855. }
  113856. return scene._environmentBRDFTexture;
  113857. };
  113858. 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=";
  113859. return TextureTools;
  113860. }());
  113861. BABYLON.TextureTools = TextureTools;
  113862. })(BABYLON || (BABYLON = {}));
  113863. //# sourceMappingURL=babylon.textureTools.js.map
  113864. var BABYLON;
  113865. (function (BABYLON) {
  113866. /**
  113867. * 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.
  113868. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  113869. */
  113870. var FramingBehavior = /** @class */ (function () {
  113871. function FramingBehavior() {
  113872. this._mode = FramingBehavior.FitFrustumSidesMode;
  113873. this._radiusScale = 1.0;
  113874. this._positionScale = 0.5;
  113875. this._defaultElevation = 0.3;
  113876. this._elevationReturnTime = 1500;
  113877. this._elevationReturnWaitTime = 1000;
  113878. this._zoomStopsAnimation = false;
  113879. this._framingTime = 1500;
  113880. /**
  113881. * Define if the behavior should automatically change the configured
  113882. * camera limits and sensibilities.
  113883. */
  113884. this.autoCorrectCameraLimitsAndSensibility = true;
  113885. this._isPointerDown = false;
  113886. this._lastInteractionTime = -Infinity;
  113887. // Framing control
  113888. this._animatables = new Array();
  113889. this._betaIsAnimating = false;
  113890. }
  113891. Object.defineProperty(FramingBehavior.prototype, "name", {
  113892. /**
  113893. * Gets the name of the behavior.
  113894. */
  113895. get: function () {
  113896. return "Framing";
  113897. },
  113898. enumerable: true,
  113899. configurable: true
  113900. });
  113901. Object.defineProperty(FramingBehavior.prototype, "mode", {
  113902. /**
  113903. * Gets current mode used by the behavior.
  113904. */
  113905. get: function () {
  113906. return this._mode;
  113907. },
  113908. /**
  113909. * Sets the current mode used by the behavior
  113910. */
  113911. set: function (mode) {
  113912. this._mode = mode;
  113913. },
  113914. enumerable: true,
  113915. configurable: true
  113916. });
  113917. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  113918. /**
  113919. * Gets the scale applied to the radius
  113920. */
  113921. get: function () {
  113922. return this._radiusScale;
  113923. },
  113924. /**
  113925. * Sets the scale applied to the radius (1 by default)
  113926. */
  113927. set: function (radius) {
  113928. this._radiusScale = radius;
  113929. },
  113930. enumerable: true,
  113931. configurable: true
  113932. });
  113933. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  113934. /**
  113935. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  113936. */
  113937. get: function () {
  113938. return this._positionScale;
  113939. },
  113940. /**
  113941. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  113942. */
  113943. set: function (scale) {
  113944. this._positionScale = scale;
  113945. },
  113946. enumerable: true,
  113947. configurable: true
  113948. });
  113949. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  113950. /**
  113951. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  113952. * behaviour is triggered, in radians.
  113953. */
  113954. get: function () {
  113955. return this._defaultElevation;
  113956. },
  113957. /**
  113958. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  113959. * behaviour is triggered, in radians.
  113960. */
  113961. set: function (elevation) {
  113962. this._defaultElevation = elevation;
  113963. },
  113964. enumerable: true,
  113965. configurable: true
  113966. });
  113967. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  113968. /**
  113969. * Gets the time (in milliseconds) taken to return to the default beta position.
  113970. * Negative value indicates camera should not return to default.
  113971. */
  113972. get: function () {
  113973. return this._elevationReturnTime;
  113974. },
  113975. /**
  113976. * Sets the time (in milliseconds) taken to return to the default beta position.
  113977. * Negative value indicates camera should not return to default.
  113978. */
  113979. set: function (speed) {
  113980. this._elevationReturnTime = speed;
  113981. },
  113982. enumerable: true,
  113983. configurable: true
  113984. });
  113985. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  113986. /**
  113987. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  113988. */
  113989. get: function () {
  113990. return this._elevationReturnWaitTime;
  113991. },
  113992. /**
  113993. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  113994. */
  113995. set: function (time) {
  113996. this._elevationReturnWaitTime = time;
  113997. },
  113998. enumerable: true,
  113999. configurable: true
  114000. });
  114001. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  114002. /**
  114003. * Gets the flag that indicates if user zooming should stop animation.
  114004. */
  114005. get: function () {
  114006. return this._zoomStopsAnimation;
  114007. },
  114008. /**
  114009. * Sets the flag that indicates if user zooming should stop animation.
  114010. */
  114011. set: function (flag) {
  114012. this._zoomStopsAnimation = flag;
  114013. },
  114014. enumerable: true,
  114015. configurable: true
  114016. });
  114017. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  114018. /**
  114019. * Gets the transition time when framing the mesh, in milliseconds
  114020. */
  114021. get: function () {
  114022. return this._framingTime;
  114023. },
  114024. /**
  114025. * Sets the transition time when framing the mesh, in milliseconds
  114026. */
  114027. set: function (time) {
  114028. this._framingTime = time;
  114029. },
  114030. enumerable: true,
  114031. configurable: true
  114032. });
  114033. /**
  114034. * Initializes the behavior.
  114035. */
  114036. FramingBehavior.prototype.init = function () {
  114037. // Do notihng
  114038. };
  114039. /**
  114040. * Attaches the behavior to its arc rotate camera.
  114041. * @param camera Defines the camera to attach the behavior to
  114042. */
  114043. FramingBehavior.prototype.attach = function (camera) {
  114044. var _this = this;
  114045. this._attachedCamera = camera;
  114046. var scene = this._attachedCamera.getScene();
  114047. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  114048. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  114049. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  114050. _this._isPointerDown = true;
  114051. return;
  114052. }
  114053. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  114054. _this._isPointerDown = false;
  114055. }
  114056. });
  114057. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114058. if (mesh) {
  114059. _this.zoomOnMesh(mesh);
  114060. }
  114061. });
  114062. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114063. // Stop the animation if there is user interaction and the animation should stop for this interaction
  114064. _this._applyUserInteraction();
  114065. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  114066. // back to the default position after a given timeout
  114067. _this._maintainCameraAboveGround();
  114068. });
  114069. };
  114070. /**
  114071. * Detaches the behavior from its current arc rotate camera.
  114072. */
  114073. FramingBehavior.prototype.detach = function () {
  114074. if (!this._attachedCamera) {
  114075. return;
  114076. }
  114077. var scene = this._attachedCamera.getScene();
  114078. if (this._onPrePointerObservableObserver) {
  114079. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  114080. }
  114081. if (this._onAfterCheckInputsObserver) {
  114082. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114083. }
  114084. if (this._onMeshTargetChangedObserver) {
  114085. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114086. }
  114087. this._attachedCamera = null;
  114088. };
  114089. /**
  114090. * Targets the given mesh and updates zoom level accordingly.
  114091. * @param mesh The mesh to target.
  114092. * @param radius Optional. If a cached radius position already exists, overrides default.
  114093. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114094. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114095. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114096. */
  114097. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114098. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114099. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114100. mesh.computeWorldMatrix(true);
  114101. var boundingBox = mesh.getBoundingInfo().boundingBox;
  114102. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  114103. };
  114104. /**
  114105. * Targets the given mesh with its children and updates zoom level accordingly.
  114106. * @param mesh The mesh to target.
  114107. * @param radius Optional. If a cached radius position already exists, overrides default.
  114108. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114109. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114110. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114111. */
  114112. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114113. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114114. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114115. mesh.computeWorldMatrix(true);
  114116. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  114117. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  114118. };
  114119. /**
  114120. * Targets the given meshes with their children and updates zoom level accordingly.
  114121. * @param meshes The mesh to target.
  114122. * @param radius Optional. If a cached radius position already exists, overrides default.
  114123. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114124. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114125. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114126. */
  114127. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  114128. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114129. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114130. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  114131. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  114132. for (var i = 0; i < meshes.length; i++) {
  114133. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  114134. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  114135. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  114136. }
  114137. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  114138. };
  114139. /**
  114140. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  114141. * @param minimumWorld Determines the smaller position of the bounding box extend
  114142. * @param maximumWorld Determines the bigger position of the bounding box extend
  114143. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114144. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114145. */
  114146. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  114147. var _this = this;
  114148. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114149. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114150. var zoomTarget;
  114151. if (!this._attachedCamera) {
  114152. return;
  114153. }
  114154. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  114155. var bottom = minimumWorld.y;
  114156. var top = maximumWorld.y;
  114157. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  114158. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  114159. if (focusOnOriginXZ) {
  114160. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  114161. }
  114162. else {
  114163. var centerWorld = minimumWorld.add(radiusWorld);
  114164. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  114165. }
  114166. if (!this._vectorTransition) {
  114167. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  114168. }
  114169. this._betaIsAnimating = true;
  114170. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  114171. if (animatable) {
  114172. this._animatables.push(animatable);
  114173. }
  114174. // sets the radius and lower radius bounds
  114175. // Small delta ensures camera is not always at lower zoom limit.
  114176. var radius = 0;
  114177. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  114178. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114179. if (this.autoCorrectCameraLimitsAndSensibility) {
  114180. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  114181. }
  114182. radius = position;
  114183. }
  114184. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114185. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114186. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  114187. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  114188. }
  114189. }
  114190. // Set sensibilities
  114191. if (this.autoCorrectCameraLimitsAndSensibility) {
  114192. var extend = maximumWorld.subtract(minimumWorld).length();
  114193. this._attachedCamera.panningSensibility = 5000 / extend;
  114194. this._attachedCamera.wheelPrecision = 100 / radius;
  114195. }
  114196. // transition to new radius
  114197. if (!this._radiusTransition) {
  114198. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114199. }
  114200. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  114201. _this.stopAllAnimations();
  114202. if (onAnimationEnd) {
  114203. onAnimationEnd();
  114204. }
  114205. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  114206. _this._attachedCamera.storeState();
  114207. }
  114208. });
  114209. if (animatable) {
  114210. this._animatables.push(animatable);
  114211. }
  114212. };
  114213. /**
  114214. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  114215. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  114216. * frustum width.
  114217. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  114218. * to fully enclose the mesh in the viewing frustum.
  114219. */
  114220. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  114221. var size = maximumWorld.subtract(minimumWorld);
  114222. var boxVectorGlobalDiagonal = size.length();
  114223. var frustumSlope = this._getFrustumSlope();
  114224. // Formula for setting distance
  114225. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  114226. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  114227. // Horizon distance
  114228. var radius = radiusWithoutFraming * this._radiusScale;
  114229. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  114230. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  114231. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  114232. var camera = this._attachedCamera;
  114233. if (!camera) {
  114234. return 0;
  114235. }
  114236. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114237. // Don't exceed the requested limit
  114238. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  114239. }
  114240. // Don't exceed the upper radius limit
  114241. if (camera.upperRadiusLimit) {
  114242. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  114243. }
  114244. return distance;
  114245. };
  114246. /**
  114247. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  114248. * is automatically returned to its default position (expected to be above ground plane).
  114249. */
  114250. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  114251. var _this = this;
  114252. if (this._elevationReturnTime < 0) {
  114253. return;
  114254. }
  114255. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  114256. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  114257. var limitBeta = Math.PI * 0.5;
  114258. // Bring the camera back up if below the ground plane
  114259. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  114260. this._betaIsAnimating = true;
  114261. //Transition to new position
  114262. this.stopAllAnimations();
  114263. if (!this._betaTransition) {
  114264. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114265. }
  114266. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  114267. _this._clearAnimationLocks();
  114268. _this.stopAllAnimations();
  114269. });
  114270. if (animatabe) {
  114271. this._animatables.push(animatabe);
  114272. }
  114273. }
  114274. };
  114275. /**
  114276. * Returns the frustum slope based on the canvas ratio and camera FOV
  114277. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  114278. */
  114279. FramingBehavior.prototype._getFrustumSlope = function () {
  114280. // Calculate the viewport ratio
  114281. // Aspect Ratio is Height/Width.
  114282. var camera = this._attachedCamera;
  114283. if (!camera) {
  114284. return BABYLON.Vector2.Zero();
  114285. }
  114286. var engine = camera.getScene().getEngine();
  114287. var aspectRatio = engine.getAspectRatio(camera);
  114288. // Camera FOV is the vertical field of view (top-bottom) in radians.
  114289. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  114290. var frustumSlopeY = Math.tan(camera.fov / 2);
  114291. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  114292. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  114293. // along the forward vector.
  114294. var frustumSlopeX = frustumSlopeY * aspectRatio;
  114295. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  114296. };
  114297. /**
  114298. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  114299. */
  114300. FramingBehavior.prototype._clearAnimationLocks = function () {
  114301. this._betaIsAnimating = false;
  114302. };
  114303. /**
  114304. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  114305. */
  114306. FramingBehavior.prototype._applyUserInteraction = function () {
  114307. if (this.isUserIsMoving) {
  114308. this._lastInteractionTime = BABYLON.Tools.Now;
  114309. this.stopAllAnimations();
  114310. this._clearAnimationLocks();
  114311. }
  114312. };
  114313. /**
  114314. * Stops and removes all animations that have been applied to the camera
  114315. */
  114316. FramingBehavior.prototype.stopAllAnimations = function () {
  114317. if (this._attachedCamera) {
  114318. this._attachedCamera.animations = [];
  114319. }
  114320. while (this._animatables.length) {
  114321. if (this._animatables[0]) {
  114322. this._animatables[0].onAnimationEnd = null;
  114323. this._animatables[0].stop();
  114324. }
  114325. this._animatables.shift();
  114326. }
  114327. };
  114328. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  114329. /**
  114330. * Gets a value indicating if the user is moving the camera
  114331. */
  114332. get: function () {
  114333. if (!this._attachedCamera) {
  114334. return false;
  114335. }
  114336. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  114337. this._attachedCamera.inertialBetaOffset !== 0 ||
  114338. this._attachedCamera.inertialRadiusOffset !== 0 ||
  114339. this._attachedCamera.inertialPanningX !== 0 ||
  114340. this._attachedCamera.inertialPanningY !== 0 ||
  114341. this._isPointerDown;
  114342. },
  114343. enumerable: true,
  114344. configurable: true
  114345. });
  114346. /**
  114347. * The easing function used by animations
  114348. */
  114349. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  114350. /**
  114351. * The easing mode used by animations
  114352. */
  114353. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  114354. // Statics
  114355. /**
  114356. * The camera can move all the way towards the mesh.
  114357. */
  114358. FramingBehavior.IgnoreBoundsSizeMode = 0;
  114359. /**
  114360. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  114361. */
  114362. FramingBehavior.FitFrustumSidesMode = 1;
  114363. return FramingBehavior;
  114364. }());
  114365. BABYLON.FramingBehavior = FramingBehavior;
  114366. })(BABYLON || (BABYLON = {}));
  114367. //# sourceMappingURL=babylon.framingBehavior.js.map
  114368. var BABYLON;
  114369. (function (BABYLON) {
  114370. /**
  114371. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  114372. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  114373. */
  114374. var BouncingBehavior = /** @class */ (function () {
  114375. function BouncingBehavior() {
  114376. /**
  114377. * The duration of the animation, in milliseconds
  114378. */
  114379. this.transitionDuration = 450;
  114380. /**
  114381. * Length of the distance animated by the transition when lower radius is reached
  114382. */
  114383. this.lowerRadiusTransitionRange = 2;
  114384. /**
  114385. * Length of the distance animated by the transition when upper radius is reached
  114386. */
  114387. this.upperRadiusTransitionRange = -2;
  114388. this._autoTransitionRange = false;
  114389. // Animations
  114390. this._radiusIsAnimating = false;
  114391. this._radiusBounceTransition = null;
  114392. this._animatables = new Array();
  114393. }
  114394. Object.defineProperty(BouncingBehavior.prototype, "name", {
  114395. /**
  114396. * Gets the name of the behavior.
  114397. */
  114398. get: function () {
  114399. return "Bouncing";
  114400. },
  114401. enumerable: true,
  114402. configurable: true
  114403. });
  114404. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  114405. /**
  114406. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114407. */
  114408. get: function () {
  114409. return this._autoTransitionRange;
  114410. },
  114411. /**
  114412. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114413. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  114414. */
  114415. set: function (value) {
  114416. var _this = this;
  114417. if (this._autoTransitionRange === value) {
  114418. return;
  114419. }
  114420. this._autoTransitionRange = value;
  114421. var camera = this._attachedCamera;
  114422. if (!camera) {
  114423. return;
  114424. }
  114425. if (value) {
  114426. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114427. if (!mesh) {
  114428. return;
  114429. }
  114430. mesh.computeWorldMatrix(true);
  114431. var diagonal = mesh.getBoundingInfo().diagonalLength;
  114432. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  114433. _this.upperRadiusTransitionRange = diagonal * 0.05;
  114434. });
  114435. }
  114436. else if (this._onMeshTargetChangedObserver) {
  114437. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114438. }
  114439. },
  114440. enumerable: true,
  114441. configurable: true
  114442. });
  114443. /**
  114444. * Initializes the behavior.
  114445. */
  114446. BouncingBehavior.prototype.init = function () {
  114447. // Do notihng
  114448. };
  114449. /**
  114450. * Attaches the behavior to its arc rotate camera.
  114451. * @param camera Defines the camera to attach the behavior to
  114452. */
  114453. BouncingBehavior.prototype.attach = function (camera) {
  114454. var _this = this;
  114455. this._attachedCamera = camera;
  114456. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114457. if (!_this._attachedCamera) {
  114458. return;
  114459. }
  114460. // Add the bounce animation to the lower radius limit
  114461. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  114462. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  114463. }
  114464. // Add the bounce animation to the upper radius limit
  114465. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  114466. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  114467. }
  114468. });
  114469. };
  114470. /**
  114471. * Detaches the behavior from its current arc rotate camera.
  114472. */
  114473. BouncingBehavior.prototype.detach = function () {
  114474. if (!this._attachedCamera) {
  114475. return;
  114476. }
  114477. if (this._onAfterCheckInputsObserver) {
  114478. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114479. }
  114480. if (this._onMeshTargetChangedObserver) {
  114481. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114482. }
  114483. this._attachedCamera = null;
  114484. };
  114485. /**
  114486. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  114487. * @param radiusLimit The limit to check against.
  114488. * @return Bool to indicate if at limit.
  114489. */
  114490. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  114491. if (!this._attachedCamera) {
  114492. return false;
  114493. }
  114494. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  114495. return true;
  114496. }
  114497. return false;
  114498. };
  114499. /**
  114500. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  114501. * @param radiusDelta The delta by which to animate to. Can be negative.
  114502. */
  114503. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  114504. var _this = this;
  114505. if (!this._attachedCamera) {
  114506. return;
  114507. }
  114508. if (!this._radiusBounceTransition) {
  114509. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  114510. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  114511. }
  114512. // Prevent zoom until bounce has completed
  114513. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  114514. this._attachedCamera.wheelPrecision = Infinity;
  114515. this._attachedCamera.inertialRadiusOffset = 0;
  114516. // Animate to the radius limit
  114517. this.stopAllAnimations();
  114518. this._radiusIsAnimating = true;
  114519. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  114520. if (animatable) {
  114521. this._animatables.push(animatable);
  114522. }
  114523. };
  114524. /**
  114525. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  114526. */
  114527. BouncingBehavior.prototype._clearAnimationLocks = function () {
  114528. this._radiusIsAnimating = false;
  114529. if (this._attachedCamera) {
  114530. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  114531. }
  114532. };
  114533. /**
  114534. * Stops and removes all animations that have been applied to the camera
  114535. */
  114536. BouncingBehavior.prototype.stopAllAnimations = function () {
  114537. if (this._attachedCamera) {
  114538. this._attachedCamera.animations = [];
  114539. }
  114540. while (this._animatables.length) {
  114541. this._animatables[0].onAnimationEnd = null;
  114542. this._animatables[0].stop();
  114543. this._animatables.shift();
  114544. }
  114545. };
  114546. /**
  114547. * The easing function used by animations
  114548. */
  114549. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  114550. /**
  114551. * The easing mode used by animations
  114552. */
  114553. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  114554. return BouncingBehavior;
  114555. }());
  114556. BABYLON.BouncingBehavior = BouncingBehavior;
  114557. })(BABYLON || (BABYLON = {}));
  114558. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  114559. var BABYLON;
  114560. (function (BABYLON) {
  114561. /**
  114562. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  114563. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  114564. */
  114565. var AutoRotationBehavior = /** @class */ (function () {
  114566. function AutoRotationBehavior() {
  114567. this._zoomStopsAnimation = false;
  114568. this._idleRotationSpeed = 0.05;
  114569. this._idleRotationWaitTime = 2000;
  114570. this._idleRotationSpinupTime = 2000;
  114571. this._isPointerDown = false;
  114572. this._lastFrameTime = null;
  114573. this._lastInteractionTime = -Infinity;
  114574. this._cameraRotationSpeed = 0;
  114575. this._lastFrameRadius = 0;
  114576. }
  114577. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  114578. /**
  114579. * Gets the name of the behavior.
  114580. */
  114581. get: function () {
  114582. return "AutoRotation";
  114583. },
  114584. enumerable: true,
  114585. configurable: true
  114586. });
  114587. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  114588. /**
  114589. * Gets the flag that indicates if user zooming should stop animation.
  114590. */
  114591. get: function () {
  114592. return this._zoomStopsAnimation;
  114593. },
  114594. /**
  114595. * Sets the flag that indicates if user zooming should stop animation.
  114596. */
  114597. set: function (flag) {
  114598. this._zoomStopsAnimation = flag;
  114599. },
  114600. enumerable: true,
  114601. configurable: true
  114602. });
  114603. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  114604. /**
  114605. * Gets the default speed at which the camera rotates around the model.
  114606. */
  114607. get: function () {
  114608. return this._idleRotationSpeed;
  114609. },
  114610. /**
  114611. * Sets the default speed at which the camera rotates around the model.
  114612. */
  114613. set: function (speed) {
  114614. this._idleRotationSpeed = speed;
  114615. },
  114616. enumerable: true,
  114617. configurable: true
  114618. });
  114619. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  114620. /**
  114621. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  114622. */
  114623. get: function () {
  114624. return this._idleRotationWaitTime;
  114625. },
  114626. /**
  114627. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  114628. */
  114629. set: function (time) {
  114630. this._idleRotationWaitTime = time;
  114631. },
  114632. enumerable: true,
  114633. configurable: true
  114634. });
  114635. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  114636. /**
  114637. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  114638. */
  114639. get: function () {
  114640. return this._idleRotationSpinupTime;
  114641. },
  114642. /**
  114643. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  114644. */
  114645. set: function (time) {
  114646. this._idleRotationSpinupTime = time;
  114647. },
  114648. enumerable: true,
  114649. configurable: true
  114650. });
  114651. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  114652. /**
  114653. * Gets a value indicating if the camera is currently rotating because of this behavior
  114654. */
  114655. get: function () {
  114656. return Math.abs(this._cameraRotationSpeed) > 0;
  114657. },
  114658. enumerable: true,
  114659. configurable: true
  114660. });
  114661. /**
  114662. * Initializes the behavior.
  114663. */
  114664. AutoRotationBehavior.prototype.init = function () {
  114665. // Do notihng
  114666. };
  114667. /**
  114668. * Attaches the behavior to its arc rotate camera.
  114669. * @param camera Defines the camera to attach the behavior to
  114670. */
  114671. AutoRotationBehavior.prototype.attach = function (camera) {
  114672. var _this = this;
  114673. this._attachedCamera = camera;
  114674. var scene = this._attachedCamera.getScene();
  114675. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  114676. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  114677. _this._isPointerDown = true;
  114678. return;
  114679. }
  114680. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  114681. _this._isPointerDown = false;
  114682. }
  114683. });
  114684. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114685. var now = BABYLON.Tools.Now;
  114686. var dt = 0;
  114687. if (_this._lastFrameTime != null) {
  114688. dt = now - _this._lastFrameTime;
  114689. }
  114690. _this._lastFrameTime = now;
  114691. // Stop the animation if there is user interaction and the animation should stop for this interaction
  114692. _this._applyUserInteraction();
  114693. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  114694. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  114695. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  114696. // Step camera rotation by rotation speed
  114697. if (_this._attachedCamera) {
  114698. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  114699. }
  114700. });
  114701. };
  114702. /**
  114703. * Detaches the behavior from its current arc rotate camera.
  114704. */
  114705. AutoRotationBehavior.prototype.detach = function () {
  114706. if (!this._attachedCamera) {
  114707. return;
  114708. }
  114709. var scene = this._attachedCamera.getScene();
  114710. if (this._onPrePointerObservableObserver) {
  114711. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  114712. }
  114713. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114714. this._attachedCamera = null;
  114715. };
  114716. /**
  114717. * Returns true if user is scrolling.
  114718. * @return true if user is scrolling.
  114719. */
  114720. AutoRotationBehavior.prototype._userIsZooming = function () {
  114721. if (!this._attachedCamera) {
  114722. return false;
  114723. }
  114724. return this._attachedCamera.inertialRadiusOffset !== 0;
  114725. };
  114726. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  114727. if (!this._attachedCamera) {
  114728. return false;
  114729. }
  114730. var zoomHasHitLimit = false;
  114731. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  114732. zoomHasHitLimit = true;
  114733. }
  114734. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  114735. this._lastFrameRadius = this._attachedCamera.radius;
  114736. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  114737. };
  114738. /**
  114739. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  114740. */
  114741. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  114742. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  114743. this._lastInteractionTime = BABYLON.Tools.Now;
  114744. }
  114745. };
  114746. // Tools
  114747. AutoRotationBehavior.prototype._userIsMoving = function () {
  114748. if (!this._attachedCamera) {
  114749. return false;
  114750. }
  114751. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  114752. this._attachedCamera.inertialBetaOffset !== 0 ||
  114753. this._attachedCamera.inertialRadiusOffset !== 0 ||
  114754. this._attachedCamera.inertialPanningX !== 0 ||
  114755. this._attachedCamera.inertialPanningY !== 0 ||
  114756. this._isPointerDown;
  114757. };
  114758. return AutoRotationBehavior;
  114759. }());
  114760. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  114761. })(BABYLON || (BABYLON = {}));
  114762. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  114763. var BABYLON;
  114764. (function (BABYLON) {
  114765. /**
  114766. * Options to create the null engine
  114767. */
  114768. var NullEngineOptions = /** @class */ (function () {
  114769. function NullEngineOptions() {
  114770. /**
  114771. * Render width (Default: 512)
  114772. */
  114773. this.renderWidth = 512;
  114774. /**
  114775. * Render height (Default: 256)
  114776. */
  114777. this.renderHeight = 256;
  114778. /**
  114779. * Texture size (Default: 512)
  114780. */
  114781. this.textureSize = 512;
  114782. /**
  114783. * If delta time between frames should be constant
  114784. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  114785. */
  114786. this.deterministicLockstep = false;
  114787. /**
  114788. * Maximum about of steps between frames (Default: 4)
  114789. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  114790. */
  114791. this.lockstepMaxSteps = 4;
  114792. }
  114793. return NullEngineOptions;
  114794. }());
  114795. BABYLON.NullEngineOptions = NullEngineOptions;
  114796. /**
  114797. * The null engine class provides support for headless version of babylon.js.
  114798. * This can be used in server side scenario or for testing purposes
  114799. */
  114800. var NullEngine = /** @class */ (function (_super) {
  114801. __extends(NullEngine, _super);
  114802. function NullEngine(options) {
  114803. if (options === void 0) { options = new NullEngineOptions(); }
  114804. var _this = _super.call(this, null) || this;
  114805. if (options.deterministicLockstep === undefined) {
  114806. options.deterministicLockstep = false;
  114807. }
  114808. if (options.lockstepMaxSteps === undefined) {
  114809. options.lockstepMaxSteps = 4;
  114810. }
  114811. _this._options = options;
  114812. // Init caps
  114813. // We consider we are on a webgl1 capable device
  114814. _this._caps = new BABYLON.EngineCapabilities();
  114815. _this._caps.maxTexturesImageUnits = 16;
  114816. _this._caps.maxVertexTextureImageUnits = 16;
  114817. _this._caps.maxTextureSize = 512;
  114818. _this._caps.maxCubemapTextureSize = 512;
  114819. _this._caps.maxRenderTextureSize = 512;
  114820. _this._caps.maxVertexAttribs = 16;
  114821. _this._caps.maxVaryingVectors = 16;
  114822. _this._caps.maxFragmentUniformVectors = 16;
  114823. _this._caps.maxVertexUniformVectors = 16;
  114824. // Extensions
  114825. _this._caps.standardDerivatives = false;
  114826. _this._caps.astc = null;
  114827. _this._caps.s3tc = null;
  114828. _this._caps.pvrtc = null;
  114829. _this._caps.etc1 = null;
  114830. _this._caps.etc2 = null;
  114831. _this._caps.textureAnisotropicFilterExtension = null;
  114832. _this._caps.maxAnisotropy = 0;
  114833. _this._caps.uintIndices = false;
  114834. _this._caps.fragmentDepthSupported = false;
  114835. _this._caps.highPrecisionShaderSupported = true;
  114836. _this._caps.colorBufferFloat = false;
  114837. _this._caps.textureFloat = false;
  114838. _this._caps.textureFloatLinearFiltering = false;
  114839. _this._caps.textureFloatRender = false;
  114840. _this._caps.textureHalfFloat = false;
  114841. _this._caps.textureHalfFloatLinearFiltering = false;
  114842. _this._caps.textureHalfFloatRender = false;
  114843. _this._caps.textureLOD = false;
  114844. _this._caps.drawBuffersExtension = false;
  114845. _this._caps.depthTextureExtension = false;
  114846. _this._caps.vertexArrayObject = false;
  114847. _this._caps.instancedArrays = false;
  114848. BABYLON.Tools.Log("Babylon.js v" + BABYLON.Engine.Version + " - Null engine");
  114849. // Wrappers
  114850. if (typeof URL === "undefined") {
  114851. URL = {
  114852. createObjectURL: function () { },
  114853. revokeObjectURL: function () { }
  114854. };
  114855. }
  114856. if (typeof Blob === "undefined") {
  114857. Blob = function () { };
  114858. }
  114859. return _this;
  114860. }
  114861. /**
  114862. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  114863. */
  114864. NullEngine.prototype.isDeterministicLockStep = function () {
  114865. return this._options.deterministicLockstep;
  114866. };
  114867. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  114868. NullEngine.prototype.getLockstepMaxSteps = function () {
  114869. return this._options.lockstepMaxSteps;
  114870. };
  114871. /**
  114872. * Sets hardware scaling, used to save performance if needed
  114873. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  114874. */
  114875. NullEngine.prototype.getHardwareScalingLevel = function () {
  114876. return 1.0;
  114877. };
  114878. NullEngine.prototype.createVertexBuffer = function (vertices) {
  114879. return {
  114880. capacity: 0,
  114881. references: 1,
  114882. is32Bits: false
  114883. };
  114884. };
  114885. NullEngine.prototype.createIndexBuffer = function (indices) {
  114886. return {
  114887. capacity: 0,
  114888. references: 1,
  114889. is32Bits: false
  114890. };
  114891. };
  114892. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  114893. if (stencil === void 0) { stencil = false; }
  114894. };
  114895. NullEngine.prototype.getRenderWidth = function (useScreen) {
  114896. if (useScreen === void 0) { useScreen = false; }
  114897. if (!useScreen && this._currentRenderTarget) {
  114898. return this._currentRenderTarget.width;
  114899. }
  114900. return this._options.renderWidth;
  114901. };
  114902. NullEngine.prototype.getRenderHeight = function (useScreen) {
  114903. if (useScreen === void 0) { useScreen = false; }
  114904. if (!useScreen && this._currentRenderTarget) {
  114905. return this._currentRenderTarget.height;
  114906. }
  114907. return this._options.renderHeight;
  114908. };
  114909. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  114910. this._cachedViewport = viewport;
  114911. };
  114912. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  114913. return {
  114914. transformFeedback: null,
  114915. __SPECTOR_rebuildProgram: null,
  114916. isParallelCompiled: false
  114917. };
  114918. };
  114919. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  114920. return [];
  114921. };
  114922. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  114923. return [];
  114924. };
  114925. NullEngine.prototype.bindSamplers = function (effect) {
  114926. this._currentEffect = null;
  114927. };
  114928. NullEngine.prototype.enableEffect = function (effect) {
  114929. this._currentEffect = effect;
  114930. if (effect.onBind) {
  114931. effect.onBind(effect);
  114932. }
  114933. if (effect._onBindObservable) {
  114934. effect._onBindObservable.notifyObservers(effect);
  114935. }
  114936. };
  114937. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  114938. if (zOffset === void 0) { zOffset = 0; }
  114939. if (reverseSide === void 0) { reverseSide = false; }
  114940. };
  114941. NullEngine.prototype.setIntArray = function (uniform, array) {
  114942. };
  114943. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  114944. };
  114945. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  114946. };
  114947. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  114948. };
  114949. NullEngine.prototype.setFloatArray = function (uniform, array) {
  114950. };
  114951. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  114952. };
  114953. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  114954. };
  114955. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  114956. };
  114957. NullEngine.prototype.setArray = function (uniform, array) {
  114958. };
  114959. NullEngine.prototype.setArray2 = function (uniform, array) {
  114960. };
  114961. NullEngine.prototype.setArray3 = function (uniform, array) {
  114962. };
  114963. NullEngine.prototype.setArray4 = function (uniform, array) {
  114964. };
  114965. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  114966. };
  114967. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  114968. };
  114969. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  114970. };
  114971. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  114972. };
  114973. NullEngine.prototype.setFloat = function (uniform, value) {
  114974. };
  114975. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  114976. };
  114977. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  114978. };
  114979. NullEngine.prototype.setBool = function (uniform, bool) {
  114980. };
  114981. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  114982. };
  114983. NullEngine.prototype.setColor3 = function (uniform, color3) {
  114984. };
  114985. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  114986. };
  114987. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  114988. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  114989. if (this._alphaMode === mode) {
  114990. return;
  114991. }
  114992. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  114993. if (!noDepthWriteChange) {
  114994. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  114995. }
  114996. this._alphaMode = mode;
  114997. };
  114998. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  114999. };
  115000. NullEngine.prototype.wipeCaches = function (bruteForce) {
  115001. if (this.preventCacheWipeBetweenFrames) {
  115002. return;
  115003. }
  115004. this.resetTextureCache();
  115005. this._currentEffect = null;
  115006. if (bruteForce) {
  115007. this._currentProgram = null;
  115008. this._stencilState.reset();
  115009. this._depthCullingState.reset();
  115010. this._alphaState.reset();
  115011. }
  115012. this._cachedVertexBuffers = null;
  115013. this._cachedIndexBuffer = null;
  115014. this._cachedEffectForVertexBuffers = null;
  115015. };
  115016. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  115017. };
  115018. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  115019. };
  115020. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  115021. };
  115022. /** @hidden */
  115023. NullEngine.prototype._createTexture = function () {
  115024. return {};
  115025. };
  115026. /** @hidden */
  115027. NullEngine.prototype._releaseTexture = function (texture) {
  115028. };
  115029. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  115030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  115031. if (onLoad === void 0) { onLoad = null; }
  115032. if (onError === void 0) { onError = null; }
  115033. if (buffer === void 0) { buffer = null; }
  115034. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  115035. var url = String(urlArg);
  115036. texture.url = url;
  115037. texture.generateMipMaps = !noMipmap;
  115038. texture.samplingMode = samplingMode;
  115039. texture.invertY = invertY;
  115040. texture.baseWidth = this._options.textureSize;
  115041. texture.baseHeight = this._options.textureSize;
  115042. texture.width = this._options.textureSize;
  115043. texture.height = this._options.textureSize;
  115044. if (format) {
  115045. texture.format = format;
  115046. }
  115047. texture.isReady = true;
  115048. if (onLoad) {
  115049. onLoad();
  115050. }
  115051. this._internalTexturesCache.push(texture);
  115052. return texture;
  115053. };
  115054. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  115055. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  115056. if (options !== undefined && typeof options === "object") {
  115057. fullOptions.generateMipMaps = options.generateMipMaps;
  115058. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  115059. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  115060. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  115061. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  115062. }
  115063. else {
  115064. fullOptions.generateMipMaps = options;
  115065. fullOptions.generateDepthBuffer = true;
  115066. fullOptions.generateStencilBuffer = false;
  115067. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  115068. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  115069. }
  115070. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  115071. var width = size.width || size;
  115072. var height = size.height || size;
  115073. texture._depthStencilBuffer = {};
  115074. texture._framebuffer = {};
  115075. texture.baseWidth = width;
  115076. texture.baseHeight = height;
  115077. texture.width = width;
  115078. texture.height = height;
  115079. texture.isReady = true;
  115080. texture.samples = 1;
  115081. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  115082. texture.samplingMode = fullOptions.samplingMode;
  115083. texture.type = fullOptions.type;
  115084. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  115085. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  115086. this._internalTexturesCache.push(texture);
  115087. return texture;
  115088. };
  115089. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  115090. texture.samplingMode = samplingMode;
  115091. };
  115092. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  115093. if (this._currentRenderTarget) {
  115094. this.unBindFramebuffer(this._currentRenderTarget);
  115095. }
  115096. this._currentRenderTarget = texture;
  115097. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  115098. if (this._cachedViewport && !forceFullscreenViewport) {
  115099. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  115100. }
  115101. };
  115102. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  115103. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  115104. this._currentRenderTarget = null;
  115105. if (onBeforeUnbind) {
  115106. if (texture._MSAAFramebuffer) {
  115107. this._currentFramebuffer = texture._framebuffer;
  115108. }
  115109. onBeforeUnbind();
  115110. }
  115111. this._currentFramebuffer = null;
  115112. };
  115113. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  115114. var vbo = {
  115115. capacity: 1,
  115116. references: 1,
  115117. is32Bits: false
  115118. };
  115119. return vbo;
  115120. };
  115121. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  115122. if (premulAlpha === void 0) { premulAlpha = false; }
  115123. };
  115124. NullEngine.prototype.areAllEffectsReady = function () {
  115125. return true;
  115126. };
  115127. /**
  115128. * @hidden
  115129. * Get the current error code of the webGL context
  115130. * @returns the error code
  115131. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  115132. */
  115133. NullEngine.prototype.getError = function () {
  115134. return 0;
  115135. };
  115136. /** @hidden */
  115137. NullEngine.prototype._getUnpackAlignement = function () {
  115138. return 1;
  115139. };
  115140. /** @hidden */
  115141. NullEngine.prototype._unpackFlipY = function (value) {
  115142. };
  115143. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  115144. if (offset === void 0) { offset = 0; }
  115145. };
  115146. /**
  115147. * Updates a dynamic vertex buffer.
  115148. * @param vertexBuffer the vertex buffer to update
  115149. * @param data the data used to update the vertex buffer
  115150. * @param byteOffset the byte offset of the data (optional)
  115151. * @param byteLength the byte length of the data (optional)
  115152. */
  115153. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  115154. };
  115155. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  115156. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  115157. this._boundTexturesCache[this._activeChannel] = texture;
  115158. return true;
  115159. }
  115160. return false;
  115161. };
  115162. /** @hidden */
  115163. NullEngine.prototype._bindTexture = function (channel, texture) {
  115164. if (channel < 0) {
  115165. return;
  115166. }
  115167. this._bindTextureDirectly(0, texture);
  115168. };
  115169. /** @hidden */
  115170. NullEngine.prototype._releaseBuffer = function (buffer) {
  115171. buffer.references--;
  115172. if (buffer.references === 0) {
  115173. return true;
  115174. }
  115175. return false;
  115176. };
  115177. NullEngine.prototype.releaseEffects = function () {
  115178. };
  115179. NullEngine.prototype.displayLoadingUI = function () {
  115180. };
  115181. NullEngine.prototype.hideLoadingUI = function () {
  115182. };
  115183. /** @hidden */
  115184. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  115185. if (faceIndex === void 0) { faceIndex = 0; }
  115186. if (lod === void 0) { lod = 0; }
  115187. };
  115188. /** @hidden */
  115189. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  115190. if (faceIndex === void 0) { faceIndex = 0; }
  115191. if (lod === void 0) { lod = 0; }
  115192. };
  115193. /** @hidden */
  115194. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  115195. if (faceIndex === void 0) { faceIndex = 0; }
  115196. if (lod === void 0) { lod = 0; }
  115197. };
  115198. /** @hidden */
  115199. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  115200. if (faceIndex === void 0) { faceIndex = 0; }
  115201. if (lod === void 0) { lod = 0; }
  115202. };
  115203. return NullEngine;
  115204. }(BABYLON.Engine));
  115205. BABYLON.NullEngine = NullEngine;
  115206. })(BABYLON || (BABYLON = {}));
  115207. //# sourceMappingURL=babylon.nullEngine.js.map
  115208. var BABYLON;
  115209. (function (BABYLON) {
  115210. /**
  115211. * This class can be used to get instrumentation data from a Babylon engine
  115212. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115213. */
  115214. var EngineInstrumentation = /** @class */ (function () {
  115215. /**
  115216. * Instantiates a new engine instrumentation.
  115217. * This class can be used to get instrumentation data from a Babylon engine
  115218. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115219. * @param engine Defines the engine to instrument
  115220. */
  115221. function EngineInstrumentation(
  115222. /**
  115223. * Define the instrumented engine.
  115224. */
  115225. engine) {
  115226. this.engine = engine;
  115227. this._captureGPUFrameTime = false;
  115228. this._gpuFrameTime = new BABYLON.PerfCounter();
  115229. this._captureShaderCompilationTime = false;
  115230. this._shaderCompilationTime = new BABYLON.PerfCounter();
  115231. // Observers
  115232. this._onBeginFrameObserver = null;
  115233. this._onEndFrameObserver = null;
  115234. this._onBeforeShaderCompilationObserver = null;
  115235. this._onAfterShaderCompilationObserver = null;
  115236. }
  115237. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  115238. // Properties
  115239. /**
  115240. * Gets the perf counter used for GPU frame time
  115241. */
  115242. get: function () {
  115243. return this._gpuFrameTime;
  115244. },
  115245. enumerable: true,
  115246. configurable: true
  115247. });
  115248. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  115249. /**
  115250. * Gets the GPU frame time capture status
  115251. */
  115252. get: function () {
  115253. return this._captureGPUFrameTime;
  115254. },
  115255. /**
  115256. * Enable or disable the GPU frame time capture
  115257. */
  115258. set: function (value) {
  115259. var _this = this;
  115260. if (value === this._captureGPUFrameTime) {
  115261. return;
  115262. }
  115263. this._captureGPUFrameTime = value;
  115264. if (value) {
  115265. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  115266. if (!_this._gpuFrameTimeToken) {
  115267. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  115268. }
  115269. });
  115270. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  115271. if (!_this._gpuFrameTimeToken) {
  115272. return;
  115273. }
  115274. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  115275. if (time > -1) {
  115276. _this._gpuFrameTimeToken = null;
  115277. _this._gpuFrameTime.fetchNewFrame();
  115278. _this._gpuFrameTime.addCount(time, true);
  115279. }
  115280. });
  115281. }
  115282. else {
  115283. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115284. this._onBeginFrameObserver = null;
  115285. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115286. this._onEndFrameObserver = null;
  115287. }
  115288. },
  115289. enumerable: true,
  115290. configurable: true
  115291. });
  115292. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  115293. /**
  115294. * Gets the perf counter used for shader compilation time
  115295. */
  115296. get: function () {
  115297. return this._shaderCompilationTime;
  115298. },
  115299. enumerable: true,
  115300. configurable: true
  115301. });
  115302. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  115303. /**
  115304. * Gets the shader compilation time capture status
  115305. */
  115306. get: function () {
  115307. return this._captureShaderCompilationTime;
  115308. },
  115309. /**
  115310. * Enable or disable the shader compilation time capture
  115311. */
  115312. set: function (value) {
  115313. var _this = this;
  115314. if (value === this._captureShaderCompilationTime) {
  115315. return;
  115316. }
  115317. this._captureShaderCompilationTime = value;
  115318. if (value) {
  115319. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  115320. _this._shaderCompilationTime.fetchNewFrame();
  115321. _this._shaderCompilationTime.beginMonitoring();
  115322. });
  115323. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  115324. _this._shaderCompilationTime.endMonitoring();
  115325. });
  115326. }
  115327. else {
  115328. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115329. this._onBeforeShaderCompilationObserver = null;
  115330. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115331. this._onAfterShaderCompilationObserver = null;
  115332. }
  115333. },
  115334. enumerable: true,
  115335. configurable: true
  115336. });
  115337. /**
  115338. * Dispose and release associated resources.
  115339. */
  115340. EngineInstrumentation.prototype.dispose = function () {
  115341. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115342. this._onBeginFrameObserver = null;
  115343. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115344. this._onEndFrameObserver = null;
  115345. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115346. this._onBeforeShaderCompilationObserver = null;
  115347. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115348. this._onAfterShaderCompilationObserver = null;
  115349. this.engine = null;
  115350. };
  115351. return EngineInstrumentation;
  115352. }());
  115353. BABYLON.EngineInstrumentation = EngineInstrumentation;
  115354. })(BABYLON || (BABYLON = {}));
  115355. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  115356. var BABYLON;
  115357. (function (BABYLON) {
  115358. /**
  115359. * This class can be used to get instrumentation data from a Babylon engine
  115360. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115361. */
  115362. var SceneInstrumentation = /** @class */ (function () {
  115363. /**
  115364. * Instantiates a new scene instrumentation.
  115365. * This class can be used to get instrumentation data from a Babylon engine
  115366. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115367. * @param scene Defines the scene to instrument
  115368. */
  115369. function SceneInstrumentation(
  115370. /**
  115371. * Defines the scene to instrument
  115372. */
  115373. scene) {
  115374. var _this = this;
  115375. this.scene = scene;
  115376. this._captureActiveMeshesEvaluationTime = false;
  115377. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  115378. this._captureRenderTargetsRenderTime = false;
  115379. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  115380. this._captureFrameTime = false;
  115381. this._frameTime = new BABYLON.PerfCounter();
  115382. this._captureRenderTime = false;
  115383. this._renderTime = new BABYLON.PerfCounter();
  115384. this._captureInterFrameTime = false;
  115385. this._interFrameTime = new BABYLON.PerfCounter();
  115386. this._captureParticlesRenderTime = false;
  115387. this._particlesRenderTime = new BABYLON.PerfCounter();
  115388. this._captureSpritesRenderTime = false;
  115389. this._spritesRenderTime = new BABYLON.PerfCounter();
  115390. this._capturePhysicsTime = false;
  115391. this._physicsTime = new BABYLON.PerfCounter();
  115392. this._captureAnimationsTime = false;
  115393. this._animationsTime = new BABYLON.PerfCounter();
  115394. this._captureCameraRenderTime = false;
  115395. this._cameraRenderTime = new BABYLON.PerfCounter();
  115396. // Observers
  115397. this._onBeforeActiveMeshesEvaluationObserver = null;
  115398. this._onAfterActiveMeshesEvaluationObserver = null;
  115399. this._onBeforeRenderTargetsRenderObserver = null;
  115400. this._onAfterRenderTargetsRenderObserver = null;
  115401. this._onAfterRenderObserver = null;
  115402. this._onBeforeDrawPhaseObserver = null;
  115403. this._onAfterDrawPhaseObserver = null;
  115404. this._onBeforeAnimationsObserver = null;
  115405. this._onBeforeParticlesRenderingObserver = null;
  115406. this._onAfterParticlesRenderingObserver = null;
  115407. this._onBeforeSpritesRenderingObserver = null;
  115408. this._onAfterSpritesRenderingObserver = null;
  115409. this._onBeforePhysicsObserver = null;
  115410. this._onAfterPhysicsObserver = null;
  115411. this._onAfterAnimationsObserver = null;
  115412. this._onBeforeCameraRenderObserver = null;
  115413. this._onAfterCameraRenderObserver = null;
  115414. // Before render
  115415. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  115416. if (_this._captureActiveMeshesEvaluationTime) {
  115417. _this._activeMeshesEvaluationTime.fetchNewFrame();
  115418. }
  115419. if (_this._captureRenderTargetsRenderTime) {
  115420. _this._renderTargetsRenderTime.fetchNewFrame();
  115421. }
  115422. if (_this._captureFrameTime) {
  115423. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  115424. _this._frameTime.beginMonitoring();
  115425. }
  115426. if (_this._captureInterFrameTime) {
  115427. _this._interFrameTime.endMonitoring();
  115428. }
  115429. if (_this._captureParticlesRenderTime) {
  115430. _this._particlesRenderTime.fetchNewFrame();
  115431. }
  115432. if (_this._captureSpritesRenderTime) {
  115433. _this._spritesRenderTime.fetchNewFrame();
  115434. }
  115435. if (_this._captureAnimationsTime) {
  115436. _this._animationsTime.beginMonitoring();
  115437. }
  115438. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  115439. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  115440. });
  115441. // After render
  115442. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  115443. if (_this._captureFrameTime) {
  115444. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  115445. _this._frameTime.endMonitoring();
  115446. }
  115447. if (_this._captureRenderTime) {
  115448. _this._renderTime.endMonitoring(false);
  115449. }
  115450. if (_this._captureInterFrameTime) {
  115451. _this._interFrameTime.beginMonitoring();
  115452. }
  115453. });
  115454. }
  115455. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  115456. // Properties
  115457. /**
  115458. * Gets the perf counter used for active meshes evaluation time
  115459. */
  115460. get: function () {
  115461. return this._activeMeshesEvaluationTime;
  115462. },
  115463. enumerable: true,
  115464. configurable: true
  115465. });
  115466. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  115467. /**
  115468. * Gets the active meshes evaluation time capture status
  115469. */
  115470. get: function () {
  115471. return this._captureActiveMeshesEvaluationTime;
  115472. },
  115473. /**
  115474. * Enable or disable the active meshes evaluation time capture
  115475. */
  115476. set: function (value) {
  115477. var _this = this;
  115478. if (value === this._captureActiveMeshesEvaluationTime) {
  115479. return;
  115480. }
  115481. this._captureActiveMeshesEvaluationTime = value;
  115482. if (value) {
  115483. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  115484. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  115485. _this._activeMeshesEvaluationTime.beginMonitoring();
  115486. });
  115487. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  115488. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  115489. _this._activeMeshesEvaluationTime.endMonitoring();
  115490. });
  115491. }
  115492. else {
  115493. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  115494. this._onBeforeActiveMeshesEvaluationObserver = null;
  115495. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  115496. this._onAfterActiveMeshesEvaluationObserver = null;
  115497. }
  115498. },
  115499. enumerable: true,
  115500. configurable: true
  115501. });
  115502. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  115503. /**
  115504. * Gets the perf counter used for render targets render time
  115505. */
  115506. get: function () {
  115507. return this._renderTargetsRenderTime;
  115508. },
  115509. enumerable: true,
  115510. configurable: true
  115511. });
  115512. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  115513. /**
  115514. * Gets the render targets render time capture status
  115515. */
  115516. get: function () {
  115517. return this._captureRenderTargetsRenderTime;
  115518. },
  115519. /**
  115520. * Enable or disable the render targets render time capture
  115521. */
  115522. set: function (value) {
  115523. var _this = this;
  115524. if (value === this._captureRenderTargetsRenderTime) {
  115525. return;
  115526. }
  115527. this._captureRenderTargetsRenderTime = value;
  115528. if (value) {
  115529. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  115530. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  115531. _this._renderTargetsRenderTime.beginMonitoring();
  115532. });
  115533. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  115534. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  115535. _this._renderTargetsRenderTime.endMonitoring(false);
  115536. });
  115537. }
  115538. else {
  115539. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  115540. this._onBeforeRenderTargetsRenderObserver = null;
  115541. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  115542. this._onAfterRenderTargetsRenderObserver = null;
  115543. }
  115544. },
  115545. enumerable: true,
  115546. configurable: true
  115547. });
  115548. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  115549. /**
  115550. * Gets the perf counter used for particles render time
  115551. */
  115552. get: function () {
  115553. return this._particlesRenderTime;
  115554. },
  115555. enumerable: true,
  115556. configurable: true
  115557. });
  115558. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  115559. /**
  115560. * Gets the particles render time capture status
  115561. */
  115562. get: function () {
  115563. return this._captureParticlesRenderTime;
  115564. },
  115565. /**
  115566. * Enable or disable the particles render time capture
  115567. */
  115568. set: function (value) {
  115569. var _this = this;
  115570. if (value === this._captureParticlesRenderTime) {
  115571. return;
  115572. }
  115573. this._captureParticlesRenderTime = value;
  115574. if (value) {
  115575. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  115576. BABYLON.Tools.StartPerformanceCounter("Particles");
  115577. _this._particlesRenderTime.beginMonitoring();
  115578. });
  115579. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  115580. BABYLON.Tools.EndPerformanceCounter("Particles");
  115581. _this._particlesRenderTime.endMonitoring(false);
  115582. });
  115583. }
  115584. else {
  115585. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  115586. this._onBeforeParticlesRenderingObserver = null;
  115587. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  115588. this._onAfterParticlesRenderingObserver = null;
  115589. }
  115590. },
  115591. enumerable: true,
  115592. configurable: true
  115593. });
  115594. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  115595. /**
  115596. * Gets the perf counter used for sprites render time
  115597. */
  115598. get: function () {
  115599. return this._spritesRenderTime;
  115600. },
  115601. enumerable: true,
  115602. configurable: true
  115603. });
  115604. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  115605. /**
  115606. * Gets the sprites render time capture status
  115607. */
  115608. get: function () {
  115609. return this._captureSpritesRenderTime;
  115610. },
  115611. /**
  115612. * Enable or disable the sprites render time capture
  115613. */
  115614. set: function (value) {
  115615. var _this = this;
  115616. if (value === this._captureSpritesRenderTime) {
  115617. return;
  115618. }
  115619. this._captureSpritesRenderTime = value;
  115620. if (!this.scene.spriteManagers) {
  115621. return;
  115622. }
  115623. if (value) {
  115624. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  115625. BABYLON.Tools.StartPerformanceCounter("Sprites");
  115626. _this._spritesRenderTime.beginMonitoring();
  115627. });
  115628. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  115629. BABYLON.Tools.EndPerformanceCounter("Sprites");
  115630. _this._spritesRenderTime.endMonitoring(false);
  115631. });
  115632. }
  115633. else {
  115634. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  115635. this._onBeforeSpritesRenderingObserver = null;
  115636. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  115637. this._onAfterSpritesRenderingObserver = null;
  115638. }
  115639. },
  115640. enumerable: true,
  115641. configurable: true
  115642. });
  115643. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  115644. /**
  115645. * Gets the perf counter used for physics time
  115646. */
  115647. get: function () {
  115648. return this._physicsTime;
  115649. },
  115650. enumerable: true,
  115651. configurable: true
  115652. });
  115653. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  115654. /**
  115655. * Gets the physics time capture status
  115656. */
  115657. get: function () {
  115658. return this._capturePhysicsTime;
  115659. },
  115660. /**
  115661. * Enable or disable the physics time capture
  115662. */
  115663. set: function (value) {
  115664. var _this = this;
  115665. if (value === this._capturePhysicsTime) {
  115666. return;
  115667. }
  115668. if (!this.scene.onBeforePhysicsObservable) {
  115669. return;
  115670. }
  115671. this._capturePhysicsTime = value;
  115672. if (value) {
  115673. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  115674. BABYLON.Tools.StartPerformanceCounter("Physics");
  115675. _this._physicsTime.beginMonitoring();
  115676. });
  115677. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  115678. BABYLON.Tools.EndPerformanceCounter("Physics");
  115679. _this._physicsTime.endMonitoring();
  115680. });
  115681. }
  115682. else {
  115683. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  115684. this._onBeforePhysicsObserver = null;
  115685. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  115686. this._onAfterPhysicsObserver = null;
  115687. }
  115688. },
  115689. enumerable: true,
  115690. configurable: true
  115691. });
  115692. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  115693. /**
  115694. * Gets the perf counter used for animations time
  115695. */
  115696. get: function () {
  115697. return this._animationsTime;
  115698. },
  115699. enumerable: true,
  115700. configurable: true
  115701. });
  115702. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  115703. /**
  115704. * Gets the animations time capture status
  115705. */
  115706. get: function () {
  115707. return this._captureAnimationsTime;
  115708. },
  115709. /**
  115710. * Enable or disable the animations time capture
  115711. */
  115712. set: function (value) {
  115713. var _this = this;
  115714. if (value === this._captureAnimationsTime) {
  115715. return;
  115716. }
  115717. this._captureAnimationsTime = value;
  115718. if (value) {
  115719. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  115720. _this._animationsTime.endMonitoring();
  115721. });
  115722. }
  115723. else {
  115724. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  115725. this._onAfterAnimationsObserver = null;
  115726. }
  115727. },
  115728. enumerable: true,
  115729. configurable: true
  115730. });
  115731. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  115732. /**
  115733. * Gets the perf counter used for frame time capture
  115734. */
  115735. get: function () {
  115736. return this._frameTime;
  115737. },
  115738. enumerable: true,
  115739. configurable: true
  115740. });
  115741. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  115742. /**
  115743. * Gets the frame time capture status
  115744. */
  115745. get: function () {
  115746. return this._captureFrameTime;
  115747. },
  115748. /**
  115749. * Enable or disable the frame time capture
  115750. */
  115751. set: function (value) {
  115752. this._captureFrameTime = value;
  115753. },
  115754. enumerable: true,
  115755. configurable: true
  115756. });
  115757. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  115758. /**
  115759. * Gets the perf counter used for inter-frames time capture
  115760. */
  115761. get: function () {
  115762. return this._interFrameTime;
  115763. },
  115764. enumerable: true,
  115765. configurable: true
  115766. });
  115767. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  115768. /**
  115769. * Gets the inter-frames time capture status
  115770. */
  115771. get: function () {
  115772. return this._captureInterFrameTime;
  115773. },
  115774. /**
  115775. * Enable or disable the inter-frames time capture
  115776. */
  115777. set: function (value) {
  115778. this._captureInterFrameTime = value;
  115779. },
  115780. enumerable: true,
  115781. configurable: true
  115782. });
  115783. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  115784. /**
  115785. * Gets the perf counter used for render time capture
  115786. */
  115787. get: function () {
  115788. return this._renderTime;
  115789. },
  115790. enumerable: true,
  115791. configurable: true
  115792. });
  115793. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  115794. /**
  115795. * Gets the render time capture status
  115796. */
  115797. get: function () {
  115798. return this._captureRenderTime;
  115799. },
  115800. /**
  115801. * Enable or disable the render time capture
  115802. */
  115803. set: function (value) {
  115804. var _this = this;
  115805. if (value === this._captureRenderTime) {
  115806. return;
  115807. }
  115808. this._captureRenderTime = value;
  115809. if (value) {
  115810. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  115811. _this._renderTime.beginMonitoring();
  115812. BABYLON.Tools.StartPerformanceCounter("Main render");
  115813. });
  115814. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  115815. _this._renderTime.endMonitoring(false);
  115816. BABYLON.Tools.EndPerformanceCounter("Main render");
  115817. });
  115818. }
  115819. else {
  115820. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  115821. this._onBeforeDrawPhaseObserver = null;
  115822. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  115823. this._onAfterDrawPhaseObserver = null;
  115824. }
  115825. },
  115826. enumerable: true,
  115827. configurable: true
  115828. });
  115829. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  115830. /**
  115831. * Gets the perf counter used for camera render time capture
  115832. */
  115833. get: function () {
  115834. return this._cameraRenderTime;
  115835. },
  115836. enumerable: true,
  115837. configurable: true
  115838. });
  115839. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  115840. /**
  115841. * Gets the camera render time capture status
  115842. */
  115843. get: function () {
  115844. return this._captureCameraRenderTime;
  115845. },
  115846. /**
  115847. * Enable or disable the camera render time capture
  115848. */
  115849. set: function (value) {
  115850. var _this = this;
  115851. if (value === this._captureCameraRenderTime) {
  115852. return;
  115853. }
  115854. this._captureCameraRenderTime = value;
  115855. if (value) {
  115856. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  115857. _this._cameraRenderTime.beginMonitoring();
  115858. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  115859. });
  115860. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  115861. _this._cameraRenderTime.endMonitoring(false);
  115862. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  115863. });
  115864. }
  115865. else {
  115866. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  115867. this._onBeforeCameraRenderObserver = null;
  115868. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  115869. this._onAfterCameraRenderObserver = null;
  115870. }
  115871. },
  115872. enumerable: true,
  115873. configurable: true
  115874. });
  115875. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  115876. /**
  115877. * Gets the perf counter used for draw calls
  115878. */
  115879. get: function () {
  115880. return this.scene.getEngine()._drawCalls;
  115881. },
  115882. enumerable: true,
  115883. configurable: true
  115884. });
  115885. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  115886. /**
  115887. * Gets the perf counter used for texture collisions
  115888. */
  115889. get: function () {
  115890. return this.scene.getEngine()._textureCollisions;
  115891. },
  115892. enumerable: true,
  115893. configurable: true
  115894. });
  115895. /**
  115896. * Dispose and release associated resources.
  115897. */
  115898. SceneInstrumentation.prototype.dispose = function () {
  115899. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  115900. this._onAfterRenderObserver = null;
  115901. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  115902. this._onBeforeActiveMeshesEvaluationObserver = null;
  115903. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  115904. this._onAfterActiveMeshesEvaluationObserver = null;
  115905. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  115906. this._onBeforeRenderTargetsRenderObserver = null;
  115907. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  115908. this._onAfterRenderTargetsRenderObserver = null;
  115909. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  115910. this._onBeforeAnimationsObserver = null;
  115911. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  115912. this._onBeforeParticlesRenderingObserver = null;
  115913. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  115914. this._onAfterParticlesRenderingObserver = null;
  115915. if (this._onBeforeSpritesRenderingObserver) {
  115916. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  115917. this._onBeforeSpritesRenderingObserver = null;
  115918. }
  115919. if (this._onAfterSpritesRenderingObserver) {
  115920. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  115921. this._onAfterSpritesRenderingObserver = null;
  115922. }
  115923. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  115924. this._onBeforeDrawPhaseObserver = null;
  115925. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  115926. this._onAfterDrawPhaseObserver = null;
  115927. if (this._onBeforePhysicsObserver) {
  115928. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  115929. this._onBeforePhysicsObserver = null;
  115930. }
  115931. if (this._onAfterPhysicsObserver) {
  115932. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  115933. this._onAfterPhysicsObserver = null;
  115934. }
  115935. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  115936. this._onAfterAnimationsObserver = null;
  115937. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  115938. this._onBeforeCameraRenderObserver = null;
  115939. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  115940. this._onAfterCameraRenderObserver = null;
  115941. this.scene = null;
  115942. };
  115943. return SceneInstrumentation;
  115944. }());
  115945. BABYLON.SceneInstrumentation = SceneInstrumentation;
  115946. })(BABYLON || (BABYLON = {}));
  115947. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  115948. var BABYLON;
  115949. (function (BABYLON) {
  115950. /**
  115951. * @hidden
  115952. **/
  115953. var _TimeToken = /** @class */ (function () {
  115954. function _TimeToken() {
  115955. this._timeElapsedQueryEnded = false;
  115956. }
  115957. return _TimeToken;
  115958. }());
  115959. BABYLON._TimeToken = _TimeToken;
  115960. })(BABYLON || (BABYLON = {}));
  115961. //# sourceMappingURL=babylon.timeToken.js.map
  115962. var BABYLON;
  115963. (function (BABYLON) {
  115964. /**
  115965. * Background material defines definition.
  115966. * @hidden Mainly internal Use
  115967. */
  115968. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  115969. __extends(BackgroundMaterialDefines, _super);
  115970. /**
  115971. * Constructor of the defines.
  115972. */
  115973. function BackgroundMaterialDefines() {
  115974. var _this = _super.call(this) || this;
  115975. /**
  115976. * True if the diffuse texture is in use.
  115977. */
  115978. _this.DIFFUSE = false;
  115979. /**
  115980. * The direct UV channel to use.
  115981. */
  115982. _this.DIFFUSEDIRECTUV = 0;
  115983. /**
  115984. * True if the diffuse texture is in gamma space.
  115985. */
  115986. _this.GAMMADIFFUSE = false;
  115987. /**
  115988. * True if the diffuse texture has opacity in the alpha channel.
  115989. */
  115990. _this.DIFFUSEHASALPHA = false;
  115991. /**
  115992. * True if you want the material to fade to transparent at grazing angle.
  115993. */
  115994. _this.OPACITYFRESNEL = false;
  115995. /**
  115996. * True if an extra blur needs to be added in the reflection.
  115997. */
  115998. _this.REFLECTIONBLUR = false;
  115999. /**
  116000. * True if you want the material to fade to reflection at grazing angle.
  116001. */
  116002. _this.REFLECTIONFRESNEL = false;
  116003. /**
  116004. * True if you want the material to falloff as far as you move away from the scene center.
  116005. */
  116006. _this.REFLECTIONFALLOFF = false;
  116007. /**
  116008. * False if the current Webgl implementation does not support the texture lod extension.
  116009. */
  116010. _this.TEXTURELODSUPPORT = false;
  116011. /**
  116012. * True to ensure the data are premultiplied.
  116013. */
  116014. _this.PREMULTIPLYALPHA = false;
  116015. /**
  116016. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  116017. */
  116018. _this.USERGBCOLOR = false;
  116019. /**
  116020. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  116021. * stays aligned with the desired configuration.
  116022. */
  116023. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  116024. /**
  116025. * True to add noise in order to reduce the banding effect.
  116026. */
  116027. _this.NOISE = false;
  116028. /**
  116029. * is the reflection texture in BGR color scheme?
  116030. * Mainly used to solve a bug in ios10 video tag
  116031. */
  116032. _this.REFLECTIONBGR = false;
  116033. _this.IMAGEPROCESSING = false;
  116034. _this.VIGNETTE = false;
  116035. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  116036. _this.VIGNETTEBLENDMODEOPAQUE = false;
  116037. _this.TONEMAPPING = false;
  116038. _this.TONEMAPPING_ACES = false;
  116039. _this.CONTRAST = false;
  116040. _this.COLORCURVES = false;
  116041. _this.COLORGRADING = false;
  116042. _this.COLORGRADING3D = false;
  116043. _this.SAMPLER3DGREENDEPTH = false;
  116044. _this.SAMPLER3DBGRMAP = false;
  116045. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  116046. _this.EXPOSURE = false;
  116047. // Reflection.
  116048. _this.REFLECTION = false;
  116049. _this.REFLECTIONMAP_3D = false;
  116050. _this.REFLECTIONMAP_SPHERICAL = false;
  116051. _this.REFLECTIONMAP_PLANAR = false;
  116052. _this.REFLECTIONMAP_CUBIC = false;
  116053. _this.REFLECTIONMAP_PROJECTION = false;
  116054. _this.REFLECTIONMAP_SKYBOX = false;
  116055. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  116056. _this.REFLECTIONMAP_EXPLICIT = false;
  116057. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  116058. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  116059. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  116060. _this.INVERTCUBICMAP = false;
  116061. _this.REFLECTIONMAP_OPPOSITEZ = false;
  116062. _this.LODINREFLECTIONALPHA = false;
  116063. _this.GAMMAREFLECTION = false;
  116064. _this.RGBDREFLECTION = false;
  116065. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  116066. // Default BJS.
  116067. _this.MAINUV1 = false;
  116068. _this.MAINUV2 = false;
  116069. _this.UV1 = false;
  116070. _this.UV2 = false;
  116071. _this.CLIPPLANE = false;
  116072. _this.CLIPPLANE2 = false;
  116073. _this.CLIPPLANE3 = false;
  116074. _this.CLIPPLANE4 = false;
  116075. _this.POINTSIZE = false;
  116076. _this.FOG = false;
  116077. _this.NORMAL = false;
  116078. _this.NUM_BONE_INFLUENCERS = 0;
  116079. _this.BonesPerMesh = 0;
  116080. _this.INSTANCES = false;
  116081. _this.SHADOWFLOAT = false;
  116082. _this.rebuild();
  116083. return _this;
  116084. }
  116085. return BackgroundMaterialDefines;
  116086. }(BABYLON.MaterialDefines));
  116087. /**
  116088. * Background material used to create an efficient environement around your scene.
  116089. */
  116090. var BackgroundMaterial = /** @class */ (function (_super) {
  116091. __extends(BackgroundMaterial, _super);
  116092. /**
  116093. * Instantiates a Background Material in the given scene
  116094. * @param name The friendly name of the material
  116095. * @param scene The scene to add the material to
  116096. */
  116097. function BackgroundMaterial(name, scene) {
  116098. var _this = _super.call(this, name, scene) || this;
  116099. /**
  116100. * Key light Color (multiply against the environement texture)
  116101. */
  116102. _this.primaryColor = BABYLON.Color3.White();
  116103. _this._primaryColorShadowLevel = 0;
  116104. _this._primaryColorHighlightLevel = 0;
  116105. /**
  116106. * Reflection Texture used in the material.
  116107. * Should be author in a specific way for the best result (refer to the documentation).
  116108. */
  116109. _this.reflectionTexture = null;
  116110. /**
  116111. * Reflection Texture level of blur.
  116112. *
  116113. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  116114. * texture twice.
  116115. */
  116116. _this.reflectionBlur = 0;
  116117. /**
  116118. * Diffuse Texture used in the material.
  116119. * Should be author in a specific way for the best result (refer to the documentation).
  116120. */
  116121. _this.diffuseTexture = null;
  116122. _this._shadowLights = null;
  116123. /**
  116124. * Specify the list of lights casting shadow on the material.
  116125. * All scene shadow lights will be included if null.
  116126. */
  116127. _this.shadowLights = null;
  116128. /**
  116129. * Helps adjusting the shadow to a softer level if required.
  116130. * 0 means black shadows and 1 means no shadows.
  116131. */
  116132. _this.shadowLevel = 0;
  116133. /**
  116134. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  116135. * It is usually zero but might be interesting to modify according to your setup.
  116136. */
  116137. _this.sceneCenter = BABYLON.Vector3.Zero();
  116138. /**
  116139. * This helps specifying that the material is falling off to the sky box at grazing angle.
  116140. * This helps ensuring a nice transition when the camera goes under the ground.
  116141. */
  116142. _this.opacityFresnel = true;
  116143. /**
  116144. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  116145. * This helps adding a mirror texture on the ground.
  116146. */
  116147. _this.reflectionFresnel = false;
  116148. /**
  116149. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  116150. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  116151. */
  116152. _this.reflectionFalloffDistance = 0.0;
  116153. /**
  116154. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  116155. */
  116156. _this.reflectionAmount = 1.0;
  116157. /**
  116158. * This specifies the weight of the reflection at grazing angle.
  116159. */
  116160. _this.reflectionReflectance0 = 0.05;
  116161. /**
  116162. * This specifies the weight of the reflection at a perpendicular point of view.
  116163. */
  116164. _this.reflectionReflectance90 = 0.5;
  116165. /**
  116166. * Helps to directly use the maps channels instead of their level.
  116167. */
  116168. _this.useRGBColor = true;
  116169. /**
  116170. * This helps reducing the banding effect that could occur on the background.
  116171. */
  116172. _this.enableNoise = false;
  116173. _this._fovMultiplier = 1.0;
  116174. /**
  116175. * Enable the FOV adjustment feature controlled by fovMultiplier.
  116176. */
  116177. _this.useEquirectangularFOV = false;
  116178. _this._maxSimultaneousLights = 4;
  116179. /**
  116180. * Number of Simultaneous lights allowed on the material.
  116181. */
  116182. _this.maxSimultaneousLights = 4;
  116183. /**
  116184. * Keep track of the image processing observer to allow dispose and replace.
  116185. */
  116186. _this._imageProcessingObserver = null;
  116187. /**
  116188. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  116189. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  116190. */
  116191. _this.switchToBGR = false;
  116192. // Temp values kept as cache in the material.
  116193. _this._renderTargets = new BABYLON.SmartArray(16);
  116194. _this._reflectionControls = BABYLON.Vector4.Zero();
  116195. _this._white = BABYLON.Color3.White();
  116196. _this._primaryShadowColor = BABYLON.Color3.Black();
  116197. _this._primaryHighlightColor = BABYLON.Color3.Black();
  116198. // Setup the default processing configuration to the scene.
  116199. _this._attachImageProcessingConfiguration(null);
  116200. _this.getRenderTargetTextures = function () {
  116201. _this._renderTargets.reset();
  116202. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  116203. _this._renderTargets.push(_this._diffuseTexture);
  116204. }
  116205. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  116206. _this._renderTargets.push(_this._reflectionTexture);
  116207. }
  116208. return _this._renderTargets;
  116209. };
  116210. return _this;
  116211. }
  116212. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  116213. /**
  116214. * Experimental Internal Use Only.
  116215. *
  116216. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  116217. * This acts as a helper to set the primary color to a more "human friendly" value.
  116218. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  116219. * output color as close as possible from the chosen value.
  116220. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  116221. * part of lighting setup.)
  116222. */
  116223. get: function () {
  116224. return this.__perceptualColor;
  116225. },
  116226. set: function (value) {
  116227. this.__perceptualColor = value;
  116228. this._computePrimaryColorFromPerceptualColor();
  116229. this._markAllSubMeshesAsLightsDirty();
  116230. },
  116231. enumerable: true,
  116232. configurable: true
  116233. });
  116234. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  116235. /**
  116236. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  116237. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  116238. */
  116239. get: function () {
  116240. return this._primaryColorShadowLevel;
  116241. },
  116242. set: function (value) {
  116243. this._primaryColorShadowLevel = value;
  116244. this._computePrimaryColors();
  116245. this._markAllSubMeshesAsLightsDirty();
  116246. },
  116247. enumerable: true,
  116248. configurable: true
  116249. });
  116250. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  116251. /**
  116252. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  116253. * The primary color is used at the level chosen to define what the white area would look.
  116254. */
  116255. get: function () {
  116256. return this._primaryColorHighlightLevel;
  116257. },
  116258. set: function (value) {
  116259. this._primaryColorHighlightLevel = value;
  116260. this._computePrimaryColors();
  116261. this._markAllSubMeshesAsLightsDirty();
  116262. },
  116263. enumerable: true,
  116264. configurable: true
  116265. });
  116266. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  116267. /**
  116268. * Sets the reflection reflectance fresnel values according to the default standard
  116269. * empirically know to work well :-)
  116270. */
  116271. set: function (value) {
  116272. var reflectionWeight = value;
  116273. if (reflectionWeight < 0.5) {
  116274. reflectionWeight = reflectionWeight * 2.0;
  116275. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  116276. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  116277. }
  116278. else {
  116279. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  116280. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  116281. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  116282. }
  116283. },
  116284. enumerable: true,
  116285. configurable: true
  116286. });
  116287. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  116288. /**
  116289. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116290. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  116291. * Recommended to be keep at 1.0 except for special cases.
  116292. */
  116293. get: function () {
  116294. return this._fovMultiplier;
  116295. },
  116296. set: function (value) {
  116297. if (isNaN(value)) {
  116298. value = 1.0;
  116299. }
  116300. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  116301. },
  116302. enumerable: true,
  116303. configurable: true
  116304. });
  116305. /**
  116306. * Attaches a new image processing configuration to the PBR Material.
  116307. * @param configuration (if null the scene configuration will be use)
  116308. */
  116309. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  116310. var _this = this;
  116311. if (configuration === this._imageProcessingConfiguration) {
  116312. return;
  116313. }
  116314. // Detaches observer.
  116315. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  116316. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  116317. }
  116318. // Pick the scene configuration if needed.
  116319. if (!configuration) {
  116320. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  116321. }
  116322. else {
  116323. this._imageProcessingConfiguration = configuration;
  116324. }
  116325. // Attaches observer.
  116326. if (this._imageProcessingConfiguration) {
  116327. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  116328. _this._computePrimaryColorFromPerceptualColor();
  116329. _this._markAllSubMeshesAsImageProcessingDirty();
  116330. });
  116331. }
  116332. };
  116333. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  116334. /**
  116335. * Gets the image processing configuration used either in this material.
  116336. */
  116337. get: function () {
  116338. return this._imageProcessingConfiguration;
  116339. },
  116340. /**
  116341. * Sets the Default image processing configuration used either in the this material.
  116342. *
  116343. * If sets to null, the scene one is in use.
  116344. */
  116345. set: function (value) {
  116346. this._attachImageProcessingConfiguration(value);
  116347. // Ensure the effect will be rebuilt.
  116348. this._markAllSubMeshesAsTexturesDirty();
  116349. },
  116350. enumerable: true,
  116351. configurable: true
  116352. });
  116353. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  116354. /**
  116355. * Gets wether the color curves effect is enabled.
  116356. */
  116357. get: function () {
  116358. return this.imageProcessingConfiguration.colorCurvesEnabled;
  116359. },
  116360. /**
  116361. * Sets wether the color curves effect is enabled.
  116362. */
  116363. set: function (value) {
  116364. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  116365. },
  116366. enumerable: true,
  116367. configurable: true
  116368. });
  116369. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  116370. /**
  116371. * Gets wether the color grading effect is enabled.
  116372. */
  116373. get: function () {
  116374. return this.imageProcessingConfiguration.colorGradingEnabled;
  116375. },
  116376. /**
  116377. * Gets wether the color grading effect is enabled.
  116378. */
  116379. set: function (value) {
  116380. this.imageProcessingConfiguration.colorGradingEnabled = value;
  116381. },
  116382. enumerable: true,
  116383. configurable: true
  116384. });
  116385. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  116386. /**
  116387. * Gets wether tonemapping is enabled or not.
  116388. */
  116389. get: function () {
  116390. return this._imageProcessingConfiguration.toneMappingEnabled;
  116391. },
  116392. /**
  116393. * Sets wether tonemapping is enabled or not
  116394. */
  116395. set: function (value) {
  116396. this._imageProcessingConfiguration.toneMappingEnabled = value;
  116397. },
  116398. enumerable: true,
  116399. configurable: true
  116400. });
  116401. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  116402. /**
  116403. * The camera exposure used on this material.
  116404. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116405. * This corresponds to a photographic exposure.
  116406. */
  116407. get: function () {
  116408. return this._imageProcessingConfiguration.exposure;
  116409. },
  116410. /**
  116411. * The camera exposure used on this material.
  116412. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116413. * This corresponds to a photographic exposure.
  116414. */
  116415. set: function (value) {
  116416. this._imageProcessingConfiguration.exposure = value;
  116417. },
  116418. enumerable: true,
  116419. configurable: true
  116420. });
  116421. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  116422. /**
  116423. * Gets The camera contrast used on this material.
  116424. */
  116425. get: function () {
  116426. return this._imageProcessingConfiguration.contrast;
  116427. },
  116428. /**
  116429. * Sets The camera contrast used on this material.
  116430. */
  116431. set: function (value) {
  116432. this._imageProcessingConfiguration.contrast = value;
  116433. },
  116434. enumerable: true,
  116435. configurable: true
  116436. });
  116437. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  116438. /**
  116439. * Gets the Color Grading 2D Lookup Texture.
  116440. */
  116441. get: function () {
  116442. return this._imageProcessingConfiguration.colorGradingTexture;
  116443. },
  116444. /**
  116445. * Sets the Color Grading 2D Lookup Texture.
  116446. */
  116447. set: function (value) {
  116448. this.imageProcessingConfiguration.colorGradingTexture = value;
  116449. },
  116450. enumerable: true,
  116451. configurable: true
  116452. });
  116453. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  116454. /**
  116455. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116456. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116457. * 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;
  116458. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116459. */
  116460. get: function () {
  116461. return this.imageProcessingConfiguration.colorCurves;
  116462. },
  116463. /**
  116464. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  116465. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  116466. * 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;
  116467. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  116468. */
  116469. set: function (value) {
  116470. this.imageProcessingConfiguration.colorCurves = value;
  116471. },
  116472. enumerable: true,
  116473. configurable: true
  116474. });
  116475. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  116476. /**
  116477. * Gets a boolean indicating that current material needs to register RTT
  116478. */
  116479. get: function () {
  116480. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  116481. return true;
  116482. }
  116483. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  116484. return true;
  116485. }
  116486. return false;
  116487. },
  116488. enumerable: true,
  116489. configurable: true
  116490. });
  116491. /**
  116492. * The entire material has been created in order to prevent overdraw.
  116493. * @returns false
  116494. */
  116495. BackgroundMaterial.prototype.needAlphaTesting = function () {
  116496. return true;
  116497. };
  116498. /**
  116499. * The entire material has been created in order to prevent overdraw.
  116500. * @returns true if blending is enable
  116501. */
  116502. BackgroundMaterial.prototype.needAlphaBlending = function () {
  116503. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  116504. };
  116505. /**
  116506. * Checks wether the material is ready to be rendered for a given mesh.
  116507. * @param mesh The mesh to render
  116508. * @param subMesh The submesh to check against
  116509. * @param useInstances Specify wether or not the material is used with instances
  116510. * @returns true if all the dependencies are ready (Textures, Effects...)
  116511. */
  116512. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  116513. var _this = this;
  116514. if (useInstances === void 0) { useInstances = false; }
  116515. if (subMesh.effect && this.isFrozen) {
  116516. if (this._wasPreviouslyReady) {
  116517. return true;
  116518. }
  116519. }
  116520. if (!subMesh._materialDefines) {
  116521. subMesh._materialDefines = new BackgroundMaterialDefines();
  116522. }
  116523. var scene = this.getScene();
  116524. var defines = subMesh._materialDefines;
  116525. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  116526. if (defines._renderId === scene.getRenderId()) {
  116527. return true;
  116528. }
  116529. }
  116530. var engine = scene.getEngine();
  116531. // Lights
  116532. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  116533. defines._needNormals = true;
  116534. // Textures
  116535. if (defines._areTexturesDirty) {
  116536. defines._needUVs = false;
  116537. if (scene.texturesEnabled) {
  116538. if (scene.getEngine().getCaps().textureLOD) {
  116539. defines.TEXTURELODSUPPORT = true;
  116540. }
  116541. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116542. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  116543. return false;
  116544. }
  116545. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  116546. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  116547. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  116548. defines.OPACITYFRESNEL = this._opacityFresnel;
  116549. }
  116550. else {
  116551. defines.DIFFUSE = false;
  116552. defines.DIFFUSEHASALPHA = false;
  116553. defines.GAMMADIFFUSE = false;
  116554. defines.OPACITYFRESNEL = false;
  116555. }
  116556. var reflectionTexture = this._reflectionTexture;
  116557. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116558. if (!reflectionTexture.isReadyOrNotBlocking()) {
  116559. return false;
  116560. }
  116561. defines.REFLECTION = true;
  116562. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  116563. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  116564. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  116565. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  116566. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  116567. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  116568. defines.REFLECTIONBGR = this.switchToBGR;
  116569. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  116570. defines.INVERTCUBICMAP = true;
  116571. }
  116572. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  116573. switch (reflectionTexture.coordinatesMode) {
  116574. case BABYLON.Texture.EXPLICIT_MODE:
  116575. defines.REFLECTIONMAP_EXPLICIT = true;
  116576. break;
  116577. case BABYLON.Texture.PLANAR_MODE:
  116578. defines.REFLECTIONMAP_PLANAR = true;
  116579. break;
  116580. case BABYLON.Texture.PROJECTION_MODE:
  116581. defines.REFLECTIONMAP_PROJECTION = true;
  116582. break;
  116583. case BABYLON.Texture.SKYBOX_MODE:
  116584. defines.REFLECTIONMAP_SKYBOX = true;
  116585. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  116586. break;
  116587. case BABYLON.Texture.SPHERICAL_MODE:
  116588. defines.REFLECTIONMAP_SPHERICAL = true;
  116589. break;
  116590. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  116591. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  116592. break;
  116593. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  116594. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  116595. break;
  116596. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  116597. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  116598. break;
  116599. case BABYLON.Texture.CUBIC_MODE:
  116600. case BABYLON.Texture.INVCUBIC_MODE:
  116601. default:
  116602. defines.REFLECTIONMAP_CUBIC = true;
  116603. break;
  116604. }
  116605. if (this.reflectionFresnel) {
  116606. defines.REFLECTIONFRESNEL = true;
  116607. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  116608. this._reflectionControls.x = this.reflectionAmount;
  116609. this._reflectionControls.y = this.reflectionReflectance0;
  116610. this._reflectionControls.z = this.reflectionReflectance90;
  116611. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  116612. }
  116613. else {
  116614. defines.REFLECTIONFRESNEL = false;
  116615. defines.REFLECTIONFALLOFF = false;
  116616. }
  116617. }
  116618. else {
  116619. defines.REFLECTION = false;
  116620. defines.REFLECTIONFRESNEL = false;
  116621. defines.REFLECTIONFALLOFF = false;
  116622. defines.REFLECTIONBLUR = false;
  116623. defines.REFLECTIONMAP_3D = false;
  116624. defines.REFLECTIONMAP_SPHERICAL = false;
  116625. defines.REFLECTIONMAP_PLANAR = false;
  116626. defines.REFLECTIONMAP_CUBIC = false;
  116627. defines.REFLECTIONMAP_PROJECTION = false;
  116628. defines.REFLECTIONMAP_SKYBOX = false;
  116629. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  116630. defines.REFLECTIONMAP_EXPLICIT = false;
  116631. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  116632. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  116633. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  116634. defines.INVERTCUBICMAP = false;
  116635. defines.REFLECTIONMAP_OPPOSITEZ = false;
  116636. defines.LODINREFLECTIONALPHA = false;
  116637. defines.GAMMAREFLECTION = false;
  116638. defines.RGBDREFLECTION = false;
  116639. }
  116640. }
  116641. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  116642. defines.USERGBCOLOR = this._useRGBColor;
  116643. defines.NOISE = this._enableNoise;
  116644. }
  116645. if (defines._areLightsDirty) {
  116646. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  116647. }
  116648. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  116649. if (!this._imageProcessingConfiguration.isReady()) {
  116650. return false;
  116651. }
  116652. this._imageProcessingConfiguration.prepareDefines(defines);
  116653. }
  116654. // Misc.
  116655. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  116656. // Values that need to be evaluated on every frame
  116657. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  116658. // Attribs
  116659. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  116660. if (mesh) {
  116661. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  116662. mesh.createNormals(true);
  116663. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  116664. }
  116665. }
  116666. }
  116667. // Get correct effect
  116668. if (defines.isDirty) {
  116669. defines.markAsProcessed();
  116670. scene.resetCachedMaterial();
  116671. // Fallbacks
  116672. var fallbacks = new BABYLON.EffectFallbacks();
  116673. if (defines.FOG) {
  116674. fallbacks.addFallback(0, "FOG");
  116675. }
  116676. if (defines.POINTSIZE) {
  116677. fallbacks.addFallback(1, "POINTSIZE");
  116678. }
  116679. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  116680. if (defines.NUM_BONE_INFLUENCERS > 0) {
  116681. fallbacks.addCPUSkinningFallback(0, mesh);
  116682. }
  116683. //Attributes
  116684. var attribs = [BABYLON.VertexBuffer.PositionKind];
  116685. if (defines.NORMAL) {
  116686. attribs.push(BABYLON.VertexBuffer.NormalKind);
  116687. }
  116688. if (defines.UV1) {
  116689. attribs.push(BABYLON.VertexBuffer.UVKind);
  116690. }
  116691. if (defines.UV2) {
  116692. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  116693. }
  116694. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  116695. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  116696. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  116697. "vFogInfos", "vFogColor", "pointSize",
  116698. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  116699. "vPrimaryColor", "vPrimaryColorShadow",
  116700. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  116701. "shadowLevel", "alpha",
  116702. "vBackgroundCenter", "vReflectionControl",
  116703. "vDiffuseInfos", "diffuseMatrix",
  116704. ];
  116705. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  116706. var uniformBuffers = ["Material", "Scene"];
  116707. if (BABYLON.ImageProcessingConfiguration) {
  116708. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  116709. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  116710. }
  116711. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  116712. uniformsNames: uniforms,
  116713. uniformBuffersNames: uniformBuffers,
  116714. samplers: samplers,
  116715. defines: defines,
  116716. maxSimultaneousLights: this._maxSimultaneousLights
  116717. });
  116718. var onCompiled = function (effect) {
  116719. if (_this.onCompiled) {
  116720. _this.onCompiled(effect);
  116721. }
  116722. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  116723. };
  116724. var join = defines.toString();
  116725. subMesh.setEffect(scene.getEngine().createEffect("background", {
  116726. attributes: attribs,
  116727. uniformsNames: uniforms,
  116728. uniformBuffersNames: uniformBuffers,
  116729. samplers: samplers,
  116730. defines: join,
  116731. fallbacks: fallbacks,
  116732. onCompiled: onCompiled,
  116733. onError: this.onError,
  116734. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  116735. }, engine), defines);
  116736. this.buildUniformLayout();
  116737. }
  116738. if (!subMesh.effect || !subMesh.effect.isReady()) {
  116739. return false;
  116740. }
  116741. defines._renderId = scene.getRenderId();
  116742. this._wasPreviouslyReady = true;
  116743. return true;
  116744. };
  116745. /**
  116746. * Compute the primary color according to the chosen perceptual color.
  116747. */
  116748. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  116749. if (!this.__perceptualColor) {
  116750. return;
  116751. }
  116752. this._primaryColor.copyFrom(this.__perceptualColor);
  116753. // Revert gamma space.
  116754. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  116755. // Revert image processing configuration.
  116756. if (this._imageProcessingConfiguration) {
  116757. // Revert Exposure.
  116758. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  116759. }
  116760. this._computePrimaryColors();
  116761. };
  116762. /**
  116763. * Compute the highlights and shadow colors according to their chosen levels.
  116764. */
  116765. BackgroundMaterial.prototype._computePrimaryColors = function () {
  116766. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  116767. return;
  116768. }
  116769. // Find the highlight color based on the configuration.
  116770. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  116771. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  116772. // Find the shadow color based on the configuration.
  116773. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  116774. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  116775. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  116776. };
  116777. /**
  116778. * Build the uniform buffer used in the material.
  116779. */
  116780. BackgroundMaterial.prototype.buildUniformLayout = function () {
  116781. // Order is important !
  116782. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  116783. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  116784. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  116785. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  116786. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  116787. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  116788. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  116789. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  116790. this._uniformBuffer.addUniform("pointSize", 1);
  116791. this._uniformBuffer.addUniform("shadowLevel", 1);
  116792. this._uniformBuffer.addUniform("alpha", 1);
  116793. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  116794. this._uniformBuffer.addUniform("vReflectionControl", 4);
  116795. this._uniformBuffer.create();
  116796. };
  116797. /**
  116798. * Unbind the material.
  116799. */
  116800. BackgroundMaterial.prototype.unbind = function () {
  116801. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  116802. this._uniformBuffer.setTexture("diffuseSampler", null);
  116803. }
  116804. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  116805. this._uniformBuffer.setTexture("reflectionSampler", null);
  116806. }
  116807. _super.prototype.unbind.call(this);
  116808. };
  116809. /**
  116810. * Bind only the world matrix to the material.
  116811. * @param world The world matrix to bind.
  116812. */
  116813. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  116814. this._activeEffect.setMatrix("world", world);
  116815. };
  116816. /**
  116817. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  116818. * @param world The world matrix to bind.
  116819. * @param subMesh The submesh to bind for.
  116820. */
  116821. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  116822. var scene = this.getScene();
  116823. var defines = subMesh._materialDefines;
  116824. if (!defines) {
  116825. return;
  116826. }
  116827. var effect = subMesh.effect;
  116828. if (!effect) {
  116829. return;
  116830. }
  116831. this._activeEffect = effect;
  116832. // Matrices
  116833. this.bindOnlyWorldMatrix(world);
  116834. // Bones
  116835. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  116836. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  116837. if (mustRebind) {
  116838. this._uniformBuffer.bindToEffect(effect, "Material");
  116839. this.bindViewProjection(effect);
  116840. var reflectionTexture = this._reflectionTexture;
  116841. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  116842. // Texture uniforms
  116843. if (scene.texturesEnabled) {
  116844. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116845. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  116846. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  116847. }
  116848. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116849. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  116850. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  116851. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  116852. }
  116853. }
  116854. if (this.shadowLevel > 0) {
  116855. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  116856. }
  116857. this._uniformBuffer.updateFloat("alpha", this.alpha);
  116858. // Point size
  116859. if (this.pointsCloud) {
  116860. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  116861. }
  116862. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  116863. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  116864. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  116865. }
  116866. else {
  116867. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  116868. }
  116869. }
  116870. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  116871. // Textures
  116872. if (scene.texturesEnabled) {
  116873. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  116874. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  116875. }
  116876. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  116877. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  116878. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  116879. }
  116880. else if (!defines.REFLECTIONBLUR) {
  116881. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  116882. }
  116883. else {
  116884. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  116885. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  116886. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  116887. }
  116888. if (defines.REFLECTIONFRESNEL) {
  116889. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  116890. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  116891. }
  116892. }
  116893. }
  116894. // Clip plane
  116895. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  116896. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  116897. }
  116898. if (mustRebind || !this.isFrozen) {
  116899. if (scene.lightsEnabled) {
  116900. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  116901. }
  116902. // View
  116903. this.bindView(effect);
  116904. // Fog
  116905. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  116906. // image processing
  116907. if (this._imageProcessingConfiguration) {
  116908. this._imageProcessingConfiguration.bind(this._activeEffect);
  116909. }
  116910. }
  116911. this._uniformBuffer.update();
  116912. this._afterBind(mesh, this._activeEffect);
  116913. };
  116914. /**
  116915. * Dispose the material.
  116916. * @param forceDisposeEffect Force disposal of the associated effect.
  116917. * @param forceDisposeTextures Force disposal of the associated textures.
  116918. */
  116919. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  116920. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  116921. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  116922. if (forceDisposeTextures) {
  116923. if (this.diffuseTexture) {
  116924. this.diffuseTexture.dispose();
  116925. }
  116926. if (this.reflectionTexture) {
  116927. this.reflectionTexture.dispose();
  116928. }
  116929. }
  116930. this._renderTargets.dispose();
  116931. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  116932. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  116933. }
  116934. _super.prototype.dispose.call(this, forceDisposeEffect);
  116935. };
  116936. /**
  116937. * Clones the material.
  116938. * @param name The cloned name.
  116939. * @returns The cloned material.
  116940. */
  116941. BackgroundMaterial.prototype.clone = function (name) {
  116942. var _this = this;
  116943. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  116944. };
  116945. /**
  116946. * Serializes the current material to its JSON representation.
  116947. * @returns The JSON representation.
  116948. */
  116949. BackgroundMaterial.prototype.serialize = function () {
  116950. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  116951. serializationObject.customType = "BABYLON.BackgroundMaterial";
  116952. return serializationObject;
  116953. };
  116954. /**
  116955. * Gets the class name of the material
  116956. * @returns "BackgroundMaterial"
  116957. */
  116958. BackgroundMaterial.prototype.getClassName = function () {
  116959. return "BackgroundMaterial";
  116960. };
  116961. /**
  116962. * Parse a JSON input to create back a background material.
  116963. * @param source The JSON data to parse
  116964. * @param scene The scene to create the parsed material in
  116965. * @param rootUrl The root url of the assets the material depends upon
  116966. * @returns the instantiated BackgroundMaterial.
  116967. */
  116968. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  116969. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  116970. };
  116971. /**
  116972. * Standard reflectance value at parallel view angle.
  116973. */
  116974. BackgroundMaterial.StandardReflectance0 = 0.05;
  116975. /**
  116976. * Standard reflectance value at grazing angle.
  116977. */
  116978. BackgroundMaterial.StandardReflectance90 = 0.5;
  116979. __decorate([
  116980. BABYLON.serializeAsColor3()
  116981. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  116982. __decorate([
  116983. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  116984. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  116985. __decorate([
  116986. BABYLON.serializeAsColor3()
  116987. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  116988. __decorate([
  116989. BABYLON.serialize()
  116990. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  116991. __decorate([
  116992. BABYLON.serialize()
  116993. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  116994. __decorate([
  116995. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  116996. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  116997. __decorate([
  116998. BABYLON.serializeAsTexture()
  116999. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  117000. __decorate([
  117001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117002. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  117003. __decorate([
  117004. BABYLON.serialize()
  117005. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  117006. __decorate([
  117007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117008. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  117009. __decorate([
  117010. BABYLON.serializeAsTexture()
  117011. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  117012. __decorate([
  117013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117014. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  117015. __decorate([
  117016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117017. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  117018. __decorate([
  117019. BABYLON.serialize()
  117020. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  117021. __decorate([
  117022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117023. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  117024. __decorate([
  117025. BABYLON.serializeAsVector3()
  117026. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  117027. __decorate([
  117028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117029. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  117030. __decorate([
  117031. BABYLON.serialize()
  117032. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  117033. __decorate([
  117034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117035. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  117036. __decorate([
  117037. BABYLON.serialize()
  117038. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  117039. __decorate([
  117040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117041. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  117042. __decorate([
  117043. BABYLON.serialize()
  117044. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  117045. __decorate([
  117046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117047. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  117048. __decorate([
  117049. BABYLON.serialize()
  117050. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  117051. __decorate([
  117052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117053. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  117054. __decorate([
  117055. BABYLON.serialize()
  117056. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  117057. __decorate([
  117058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117059. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  117060. __decorate([
  117061. BABYLON.serialize()
  117062. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  117063. __decorate([
  117064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117065. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  117066. __decorate([
  117067. BABYLON.serialize()
  117068. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  117069. __decorate([
  117070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117071. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  117072. __decorate([
  117073. BABYLON.serialize()
  117074. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  117075. __decorate([
  117076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117077. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  117078. __decorate([
  117079. BABYLON.serialize()
  117080. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  117081. __decorate([
  117082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117083. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  117084. __decorate([
  117085. BABYLON.serializeAsImageProcessingConfiguration()
  117086. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  117087. return BackgroundMaterial;
  117088. }(BABYLON.PushMaterial));
  117089. BABYLON.BackgroundMaterial = BackgroundMaterial;
  117090. })(BABYLON || (BABYLON = {}));
  117091. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  117092. var __assign = (this && this.__assign) || function () {
  117093. __assign = Object.assign || function(t) {
  117094. for (var s, i = 1, n = arguments.length; i < n; i++) {
  117095. s = arguments[i];
  117096. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  117097. t[p] = s[p];
  117098. }
  117099. return t;
  117100. };
  117101. return __assign.apply(this, arguments);
  117102. };
  117103. var BABYLON;
  117104. (function (BABYLON) {
  117105. /**
  117106. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  117107. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  117108. * It also helps with the default setup of your imageProcessing configuration.
  117109. */
  117110. var EnvironmentHelper = /** @class */ (function () {
  117111. /**
  117112. * constructor
  117113. * @param options
  117114. * @param scene The scene to add the material to
  117115. */
  117116. function EnvironmentHelper(options, scene) {
  117117. var _this = this;
  117118. this._errorHandler = function (message, exception) {
  117119. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  117120. };
  117121. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  117122. this._scene = scene;
  117123. this.onErrorObservable = new BABYLON.Observable();
  117124. this._setupBackground();
  117125. this._setupImageProcessing();
  117126. }
  117127. /**
  117128. * Creates the default options for the helper.
  117129. */
  117130. EnvironmentHelper._getDefaultOptions = function () {
  117131. return {
  117132. createGround: true,
  117133. groundSize: 15,
  117134. groundTexture: this._groundTextureCDNUrl,
  117135. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117136. groundOpacity: 0.9,
  117137. enableGroundShadow: true,
  117138. groundShadowLevel: 0.5,
  117139. enableGroundMirror: false,
  117140. groundMirrorSizeRatio: 0.3,
  117141. groundMirrorBlurKernel: 64,
  117142. groundMirrorAmount: 1,
  117143. groundMirrorFresnelWeight: 1,
  117144. groundMirrorFallOffDistance: 0,
  117145. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  117146. groundYBias: 0.00001,
  117147. createSkybox: true,
  117148. skyboxSize: 20,
  117149. skyboxTexture: this._skyboxTextureCDNUrl,
  117150. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117151. backgroundYRotation: 0,
  117152. sizeAuto: true,
  117153. rootPosition: BABYLON.Vector3.Zero(),
  117154. setupImageProcessing: true,
  117155. environmentTexture: this._environmentTextureCDNUrl,
  117156. cameraExposure: 0.8,
  117157. cameraContrast: 1.2,
  117158. toneMappingEnabled: true,
  117159. };
  117160. };
  117161. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  117162. /**
  117163. * Gets the root mesh created by the helper.
  117164. */
  117165. get: function () {
  117166. return this._rootMesh;
  117167. },
  117168. enumerable: true,
  117169. configurable: true
  117170. });
  117171. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  117172. /**
  117173. * Gets the skybox created by the helper.
  117174. */
  117175. get: function () {
  117176. return this._skybox;
  117177. },
  117178. enumerable: true,
  117179. configurable: true
  117180. });
  117181. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  117182. /**
  117183. * Gets the skybox texture created by the helper.
  117184. */
  117185. get: function () {
  117186. return this._skyboxTexture;
  117187. },
  117188. enumerable: true,
  117189. configurable: true
  117190. });
  117191. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  117192. /**
  117193. * Gets the skybox material created by the helper.
  117194. */
  117195. get: function () {
  117196. return this._skyboxMaterial;
  117197. },
  117198. enumerable: true,
  117199. configurable: true
  117200. });
  117201. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  117202. /**
  117203. * Gets the ground mesh created by the helper.
  117204. */
  117205. get: function () {
  117206. return this._ground;
  117207. },
  117208. enumerable: true,
  117209. configurable: true
  117210. });
  117211. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  117212. /**
  117213. * Gets the ground texture created by the helper.
  117214. */
  117215. get: function () {
  117216. return this._groundTexture;
  117217. },
  117218. enumerable: true,
  117219. configurable: true
  117220. });
  117221. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  117222. /**
  117223. * Gets the ground mirror created by the helper.
  117224. */
  117225. get: function () {
  117226. return this._groundMirror;
  117227. },
  117228. enumerable: true,
  117229. configurable: true
  117230. });
  117231. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  117232. /**
  117233. * Gets the ground mirror render list to helps pushing the meshes
  117234. * you wish in the ground reflection.
  117235. */
  117236. get: function () {
  117237. if (this._groundMirror) {
  117238. return this._groundMirror.renderList;
  117239. }
  117240. return null;
  117241. },
  117242. enumerable: true,
  117243. configurable: true
  117244. });
  117245. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  117246. /**
  117247. * Gets the ground material created by the helper.
  117248. */
  117249. get: function () {
  117250. return this._groundMaterial;
  117251. },
  117252. enumerable: true,
  117253. configurable: true
  117254. });
  117255. /**
  117256. * Updates the background according to the new options
  117257. * @param options
  117258. */
  117259. EnvironmentHelper.prototype.updateOptions = function (options) {
  117260. var newOptions = __assign({}, this._options, options);
  117261. if (this._ground && !newOptions.createGround) {
  117262. this._ground.dispose();
  117263. this._ground = null;
  117264. }
  117265. if (this._groundMaterial && !newOptions.createGround) {
  117266. this._groundMaterial.dispose();
  117267. this._groundMaterial = null;
  117268. }
  117269. if (this._groundTexture) {
  117270. if (this._options.groundTexture != newOptions.groundTexture) {
  117271. this._groundTexture.dispose();
  117272. this._groundTexture = null;
  117273. }
  117274. }
  117275. if (this._skybox && !newOptions.createSkybox) {
  117276. this._skybox.dispose();
  117277. this._skybox = null;
  117278. }
  117279. if (this._skyboxMaterial && !newOptions.createSkybox) {
  117280. this._skyboxMaterial.dispose();
  117281. this._skyboxMaterial = null;
  117282. }
  117283. if (this._skyboxTexture) {
  117284. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  117285. this._skyboxTexture.dispose();
  117286. this._skyboxTexture = null;
  117287. }
  117288. }
  117289. if (this._groundMirror && !newOptions.enableGroundMirror) {
  117290. this._groundMirror.dispose();
  117291. this._groundMirror = null;
  117292. }
  117293. if (this._scene.environmentTexture) {
  117294. if (this._options.environmentTexture != newOptions.environmentTexture) {
  117295. this._scene.environmentTexture.dispose();
  117296. }
  117297. }
  117298. this._options = newOptions;
  117299. this._setupBackground();
  117300. this._setupImageProcessing();
  117301. };
  117302. /**
  117303. * Sets the primary color of all the available elements.
  117304. * @param color the main color to affect to the ground and the background
  117305. */
  117306. EnvironmentHelper.prototype.setMainColor = function (color) {
  117307. if (this.groundMaterial) {
  117308. this.groundMaterial.primaryColor = color;
  117309. }
  117310. if (this.skyboxMaterial) {
  117311. this.skyboxMaterial.primaryColor = color;
  117312. }
  117313. if (this.groundMirror) {
  117314. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  117315. }
  117316. };
  117317. /**
  117318. * Setup the image processing according to the specified options.
  117319. */
  117320. EnvironmentHelper.prototype._setupImageProcessing = function () {
  117321. if (this._options.setupImageProcessing) {
  117322. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  117323. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  117324. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  117325. this._setupEnvironmentTexture();
  117326. }
  117327. };
  117328. /**
  117329. * Setup the environment texture according to the specified options.
  117330. */
  117331. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  117332. if (this._scene.environmentTexture) {
  117333. return;
  117334. }
  117335. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  117336. this._scene.environmentTexture = this._options.environmentTexture;
  117337. return;
  117338. }
  117339. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  117340. this._scene.environmentTexture = environmentTexture;
  117341. };
  117342. /**
  117343. * Setup the background according to the specified options.
  117344. */
  117345. EnvironmentHelper.prototype._setupBackground = function () {
  117346. if (!this._rootMesh) {
  117347. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  117348. }
  117349. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  117350. var sceneSize = this._getSceneSize();
  117351. if (this._options.createGround) {
  117352. this._setupGround(sceneSize);
  117353. this._setupGroundMaterial();
  117354. this._setupGroundDiffuseTexture();
  117355. if (this._options.enableGroundMirror) {
  117356. this._setupGroundMirrorTexture(sceneSize);
  117357. }
  117358. this._setupMirrorInGroundMaterial();
  117359. }
  117360. if (this._options.createSkybox) {
  117361. this._setupSkybox(sceneSize);
  117362. this._setupSkyboxMaterial();
  117363. this._setupSkyboxReflectionTexture();
  117364. }
  117365. this._rootMesh.position.x = sceneSize.rootPosition.x;
  117366. this._rootMesh.position.z = sceneSize.rootPosition.z;
  117367. this._rootMesh.position.y = sceneSize.rootPosition.y;
  117368. };
  117369. /**
  117370. * Get the scene sizes according to the setup.
  117371. */
  117372. EnvironmentHelper.prototype._getSceneSize = function () {
  117373. var _this = this;
  117374. var groundSize = this._options.groundSize;
  117375. var skyboxSize = this._options.skyboxSize;
  117376. var rootPosition = this._options.rootPosition;
  117377. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  117378. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117379. }
  117380. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  117381. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  117382. });
  117383. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  117384. if (this._options.sizeAuto) {
  117385. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  117386. this._scene.activeCamera.upperRadiusLimit) {
  117387. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  117388. skyboxSize = groundSize;
  117389. }
  117390. var sceneDiagonalLenght = sceneDiagonal.length();
  117391. if (sceneDiagonalLenght > groundSize) {
  117392. groundSize = sceneDiagonalLenght * 2;
  117393. skyboxSize = groundSize;
  117394. }
  117395. // 10 % bigger.
  117396. groundSize *= 1.1;
  117397. skyboxSize *= 1.5;
  117398. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  117399. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  117400. }
  117401. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117402. };
  117403. /**
  117404. * Setup the ground according to the specified options.
  117405. */
  117406. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  117407. var _this = this;
  117408. if (!this._ground || this._ground.isDisposed()) {
  117409. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  117410. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  117411. this._ground.parent = this._rootMesh;
  117412. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  117413. }
  117414. this._ground.receiveShadows = this._options.enableGroundShadow;
  117415. };
  117416. /**
  117417. * Setup the ground material according to the specified options.
  117418. */
  117419. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  117420. if (!this._groundMaterial) {
  117421. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  117422. }
  117423. this._groundMaterial.alpha = this._options.groundOpacity;
  117424. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  117425. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  117426. this._groundMaterial.primaryColor = this._options.groundColor;
  117427. this._groundMaterial.useRGBColor = false;
  117428. this._groundMaterial.enableNoise = true;
  117429. if (this._ground) {
  117430. this._ground.material = this._groundMaterial;
  117431. }
  117432. };
  117433. /**
  117434. * Setup the ground diffuse texture according to the specified options.
  117435. */
  117436. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  117437. if (!this._groundMaterial) {
  117438. return;
  117439. }
  117440. if (this._groundTexture) {
  117441. return;
  117442. }
  117443. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  117444. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  117445. return;
  117446. }
  117447. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117448. diffuseTexture.gammaSpace = false;
  117449. diffuseTexture.hasAlpha = true;
  117450. this._groundMaterial.diffuseTexture = diffuseTexture;
  117451. };
  117452. /**
  117453. * Setup the ground mirror texture according to the specified options.
  117454. */
  117455. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  117456. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117457. if (!this._groundMirror) {
  117458. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  117459. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  117460. this._groundMirror.anisotropicFilteringLevel = 1;
  117461. this._groundMirror.wrapU = wrapping;
  117462. this._groundMirror.wrapV = wrapping;
  117463. this._groundMirror.gammaSpace = false;
  117464. if (this._groundMirror.renderList) {
  117465. for (var i = 0; i < this._scene.meshes.length; i++) {
  117466. var mesh = this._scene.meshes[i];
  117467. if (mesh !== this._ground &&
  117468. mesh !== this._skybox &&
  117469. mesh !== this._rootMesh) {
  117470. this._groundMirror.renderList.push(mesh);
  117471. }
  117472. }
  117473. }
  117474. }
  117475. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  117476. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  117477. };
  117478. /**
  117479. * Setup the ground to receive the mirror texture.
  117480. */
  117481. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  117482. if (this._groundMaterial) {
  117483. this._groundMaterial.reflectionTexture = this._groundMirror;
  117484. this._groundMaterial.reflectionFresnel = true;
  117485. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  117486. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  117487. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  117488. }
  117489. };
  117490. /**
  117491. * Setup the skybox according to the specified options.
  117492. */
  117493. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  117494. var _this = this;
  117495. if (!this._skybox || this._skybox.isDisposed()) {
  117496. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  117497. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  117498. }
  117499. this._skybox.parent = this._rootMesh;
  117500. };
  117501. /**
  117502. * Setup the skybox material according to the specified options.
  117503. */
  117504. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  117505. if (!this._skybox) {
  117506. return;
  117507. }
  117508. if (!this._skyboxMaterial) {
  117509. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  117510. }
  117511. this._skyboxMaterial.useRGBColor = false;
  117512. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  117513. this._skyboxMaterial.enableNoise = true;
  117514. this._skybox.material = this._skyboxMaterial;
  117515. };
  117516. /**
  117517. * Setup the skybox reflection texture according to the specified options.
  117518. */
  117519. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  117520. if (!this._skyboxMaterial) {
  117521. return;
  117522. }
  117523. if (this._skyboxTexture) {
  117524. return;
  117525. }
  117526. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  117527. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  117528. return;
  117529. }
  117530. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  117531. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117532. this._skyboxTexture.gammaSpace = false;
  117533. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  117534. };
  117535. /**
  117536. * Dispose all the elements created by the Helper.
  117537. */
  117538. EnvironmentHelper.prototype.dispose = function () {
  117539. if (this._groundMaterial) {
  117540. this._groundMaterial.dispose(true, true);
  117541. }
  117542. if (this._skyboxMaterial) {
  117543. this._skyboxMaterial.dispose(true, true);
  117544. }
  117545. this._rootMesh.dispose(false);
  117546. };
  117547. /**
  117548. * Default ground texture URL.
  117549. */
  117550. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  117551. /**
  117552. * Default skybox texture URL.
  117553. */
  117554. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  117555. /**
  117556. * Default environment texture URL.
  117557. */
  117558. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  117559. return EnvironmentHelper;
  117560. }());
  117561. BABYLON.EnvironmentHelper = EnvironmentHelper;
  117562. })(BABYLON || (BABYLON = {}));
  117563. //# sourceMappingURL=babylon.environmentHelper.js.map
  117564. var BABYLON;
  117565. (function (BABYLON) {
  117566. /** Internal class used to store shapes for emitters */
  117567. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  117568. function ParticleSystemSetEmitterCreationOptions() {
  117569. }
  117570. return ParticleSystemSetEmitterCreationOptions;
  117571. }());
  117572. /**
  117573. * Represents a set of particle systems working together to create a specific effect
  117574. */
  117575. var ParticleSystemSet = /** @class */ (function () {
  117576. function ParticleSystemSet() {
  117577. /**
  117578. * Gets the particle system list
  117579. */
  117580. this.systems = new Array();
  117581. }
  117582. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  117583. /**
  117584. * Gets the emitter node used with this set
  117585. */
  117586. get: function () {
  117587. return this._emitterNode;
  117588. },
  117589. enumerable: true,
  117590. configurable: true
  117591. });
  117592. /**
  117593. * Creates a new emitter mesh as a sphere
  117594. * @param options defines the options used to create the sphere
  117595. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  117596. * @param scene defines the hosting scene
  117597. */
  117598. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  117599. if (this._emitterNode) {
  117600. this._emitterNode.dispose();
  117601. }
  117602. this._emitterCreationOptions = {
  117603. kind: "Sphere",
  117604. options: options,
  117605. renderingGroupId: renderingGroupId
  117606. };
  117607. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  117608. emitterMesh.renderingGroupId = renderingGroupId;
  117609. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  117610. material.emissiveColor = options.color;
  117611. emitterMesh.material = material;
  117612. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117613. var system = _a[_i];
  117614. system.emitter = emitterMesh;
  117615. }
  117616. this._emitterNode = emitterMesh;
  117617. };
  117618. /**
  117619. * Starts all particle systems of the set
  117620. * @param emitter defines an optional mesh to use as emitter for the particle systems
  117621. */
  117622. ParticleSystemSet.prototype.start = function (emitter) {
  117623. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117624. var system = _a[_i];
  117625. if (emitter) {
  117626. system.emitter = emitter;
  117627. }
  117628. system.start();
  117629. }
  117630. };
  117631. /**
  117632. * Release all associated resources
  117633. */
  117634. ParticleSystemSet.prototype.dispose = function () {
  117635. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117636. var system = _a[_i];
  117637. system.dispose();
  117638. }
  117639. this.systems = [];
  117640. if (this._emitterNode) {
  117641. this._emitterNode.dispose();
  117642. this._emitterNode = null;
  117643. }
  117644. };
  117645. /**
  117646. * Serialize the set into a JSON compatible object
  117647. * @returns a JSON compatible representation of the set
  117648. */
  117649. ParticleSystemSet.prototype.serialize = function () {
  117650. var result = {};
  117651. result.systems = [];
  117652. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  117653. var system = _a[_i];
  117654. result.systems.push(system.serialize());
  117655. }
  117656. if (this._emitterNode) {
  117657. result.emitter = this._emitterCreationOptions;
  117658. }
  117659. return result;
  117660. };
  117661. /**
  117662. * Parse a new ParticleSystemSet from a serialized source
  117663. * @param data defines a JSON compatible representation of the set
  117664. * @param scene defines the hosting scene
  117665. * @param gpu defines if we want GPU particles or CPU particles
  117666. * @returns a new ParticleSystemSet
  117667. */
  117668. ParticleSystemSet.Parse = function (data, scene, gpu) {
  117669. if (gpu === void 0) { gpu = false; }
  117670. var result = new ParticleSystemSet();
  117671. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  117672. scene = scene || BABYLON.Engine.LastCreatedScene;
  117673. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  117674. var system = _a[_i];
  117675. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  117676. }
  117677. if (data.emitter) {
  117678. var options = data.emitter.options;
  117679. switch (data.emitter.kind) {
  117680. case "Sphere":
  117681. result.setEmitterAsSphere({
  117682. diameter: options.diameter,
  117683. segments: options.segments,
  117684. color: BABYLON.Color3.FromArray(options.color)
  117685. }, data.emitter.renderingGroupId, scene);
  117686. break;
  117687. }
  117688. }
  117689. return result;
  117690. };
  117691. return ParticleSystemSet;
  117692. }());
  117693. BABYLON.ParticleSystemSet = ParticleSystemSet;
  117694. })(BABYLON || (BABYLON = {}));
  117695. //# sourceMappingURL=babylon.particleSystemSet.js.map
  117696. var BABYLON;
  117697. (function (BABYLON) {
  117698. /**
  117699. * This class is made for on one-liner static method to help creating particle system set.
  117700. */
  117701. var ParticleHelper = /** @class */ (function () {
  117702. function ParticleHelper() {
  117703. }
  117704. /**
  117705. * Create a default particle system that you can tweak
  117706. * @param emitter defines the emitter to use
  117707. * @param capacity defines the system capacity (default is 500 particles)
  117708. * @param scene defines the hosting scene
  117709. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  117710. * @returns the new Particle system
  117711. */
  117712. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  117713. if (capacity === void 0) { capacity = 500; }
  117714. if (useGPU === void 0) { useGPU = false; }
  117715. var system;
  117716. if (useGPU) {
  117717. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  117718. }
  117719. else {
  117720. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  117721. }
  117722. system.emitter = emitter;
  117723. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  117724. system.createConeEmitter(0.1, Math.PI / 4);
  117725. // Particle color
  117726. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  117727. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  117728. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  117729. // Particle Size
  117730. system.minSize = 0.1;
  117731. system.maxSize = 0.1;
  117732. // Emission speed
  117733. system.minEmitPower = 2;
  117734. system.maxEmitPower = 2;
  117735. // Update speed
  117736. system.updateSpeed = 1 / 60;
  117737. system.emitRate = 30;
  117738. return system;
  117739. };
  117740. /**
  117741. * This is the main static method (one-liner) of this helper to create different particle systems
  117742. * @param type This string represents the type to the particle system to create
  117743. * @param scene The scene where the particle system should live
  117744. * @param gpu If the system will use gpu
  117745. * @returns the ParticleSystemSet created
  117746. */
  117747. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  117748. if (gpu === void 0) { gpu = false; }
  117749. if (!scene) {
  117750. scene = BABYLON.Engine.LastCreatedScene;
  117751. }
  117752. var token = {};
  117753. scene._addPendingData(token);
  117754. return new Promise(function (resolve, reject) {
  117755. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  117756. scene._removePendingData(token);
  117757. return reject("Particle system with GPU is not supported.");
  117758. }
  117759. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  117760. scene._removePendingData(token);
  117761. var newData = JSON.parse(data.toString());
  117762. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  117763. }, undefined, undefined, undefined, function (req, exception) {
  117764. scene._removePendingData(token);
  117765. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  117766. });
  117767. });
  117768. };
  117769. /**
  117770. * Static function used to export a particle system to a ParticleSystemSet variable.
  117771. * Please note that the emitter shape is not exported
  117772. * @param systems defines the particle systems to export
  117773. * @returns the created particle system set
  117774. */
  117775. ParticleHelper.ExportSet = function (systems) {
  117776. var set = new BABYLON.ParticleSystemSet();
  117777. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  117778. var system = systems_1[_i];
  117779. set.systems.push(system);
  117780. }
  117781. return set;
  117782. };
  117783. /**
  117784. * Gets or sets base Assets URL
  117785. */
  117786. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  117787. return ParticleHelper;
  117788. }());
  117789. BABYLON.ParticleHelper = ParticleHelper;
  117790. })(BABYLON || (BABYLON = {}));
  117791. //# sourceMappingURL=babylon.particleHelper.js.map
  117792. var BABYLON;
  117793. (function (BABYLON) {
  117794. /**
  117795. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  117796. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  117797. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  117798. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  117799. */
  117800. var VideoDome = /** @class */ (function (_super) {
  117801. __extends(VideoDome, _super);
  117802. /**
  117803. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  117804. * @param name Element's name, child elements will append suffixes for their own names.
  117805. * @param urlsOrVideo defines the url(s) or the video element to use
  117806. * @param options An object containing optional or exposed sub element properties
  117807. */
  117808. function VideoDome(name, urlsOrVideo, options, scene) {
  117809. var _this = _super.call(this, name, scene) || this;
  117810. _this._useDirectMapping = false;
  117811. // set defaults and manage values
  117812. name = name || "videoDome";
  117813. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  117814. options.clickToPlay = Boolean(options.clickToPlay);
  117815. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  117816. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  117817. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  117818. if (options.useDirectMapping === undefined) {
  117819. _this._useDirectMapping = true;
  117820. }
  117821. else {
  117822. _this._useDirectMapping = options.useDirectMapping;
  117823. }
  117824. _this._setReady(false);
  117825. // create
  117826. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  117827. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  117828. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  117829. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  117830. texture.onLoadObservable.addOnce(function () {
  117831. _this._setReady(true);
  117832. });
  117833. // configure material
  117834. material.useEquirectangularFOV = true;
  117835. material.fovMultiplier = 1.0;
  117836. material.opacityFresnel = false;
  117837. if (_this._useDirectMapping) {
  117838. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117839. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117840. material.diffuseTexture = texture;
  117841. }
  117842. else {
  117843. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  117844. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117845. material.reflectionTexture = texture;
  117846. }
  117847. // configure mesh
  117848. _this._mesh.material = material;
  117849. _this._mesh.parent = _this;
  117850. // optional configuration
  117851. if (options.clickToPlay) {
  117852. scene.onPointerUp = function () {
  117853. _this._videoTexture.video.play();
  117854. };
  117855. }
  117856. return _this;
  117857. }
  117858. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  117859. /**
  117860. * Gets the video texture being displayed on the sphere
  117861. */
  117862. get: function () {
  117863. return this._videoTexture;
  117864. },
  117865. enumerable: true,
  117866. configurable: true
  117867. });
  117868. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  117869. /**
  117870. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  117871. * Also see the options.resolution property.
  117872. */
  117873. get: function () {
  117874. return this._material.fovMultiplier;
  117875. },
  117876. set: function (value) {
  117877. this._material.fovMultiplier = value;
  117878. },
  117879. enumerable: true,
  117880. configurable: true
  117881. });
  117882. /**
  117883. * Releases resources associated with this node.
  117884. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  117885. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  117886. */
  117887. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  117888. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  117889. this._videoTexture.dispose();
  117890. this._mesh.dispose();
  117891. this._material.dispose();
  117892. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  117893. };
  117894. return VideoDome;
  117895. }(BABYLON.TransformNode));
  117896. BABYLON.VideoDome = VideoDome;
  117897. })(BABYLON || (BABYLON = {}));
  117898. //# sourceMappingURL=babylon.videoDome.js.map
  117899. var BABYLON;
  117900. (function (BABYLON) {
  117901. /**
  117902. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  117903. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  117904. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  117905. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  117906. */
  117907. var PhotoDome = /** @class */ (function (_super) {
  117908. __extends(PhotoDome, _super);
  117909. /**
  117910. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  117911. * @param name Element's name, child elements will append suffixes for their own names.
  117912. * @param urlsOfPhoto defines the url of the photo to display
  117913. * @param options defines an object containing optional or exposed sub element properties
  117914. * @param onError defines a callback called when an error occured while loading the texture
  117915. */
  117916. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  117917. if (onError === void 0) { onError = null; }
  117918. var _this = _super.call(this, name, scene) || this;
  117919. _this._useDirectMapping = false;
  117920. /**
  117921. * Observable raised when an error occured while loading the 360 image
  117922. */
  117923. _this.onLoadErrorObservable = new BABYLON.Observable();
  117924. // set defaults and manage values
  117925. name = name || "photoDome";
  117926. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  117927. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  117928. if (options.useDirectMapping === undefined) {
  117929. _this._useDirectMapping = true;
  117930. }
  117931. else {
  117932. _this._useDirectMapping = options.useDirectMapping;
  117933. }
  117934. _this._setReady(false);
  117935. // create
  117936. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  117937. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  117938. // configure material
  117939. material.opacityFresnel = false;
  117940. material.useEquirectangularFOV = true;
  117941. material.fovMultiplier = 1.0;
  117942. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  117943. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  117944. if (onError) {
  117945. onError(message, exception);
  117946. }
  117947. });
  117948. _this.photoTexture.onLoadObservable.addOnce(function () {
  117949. _this._setReady(true);
  117950. });
  117951. // configure mesh
  117952. _this._mesh.material = material;
  117953. _this._mesh.parent = _this;
  117954. return _this;
  117955. }
  117956. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  117957. /**
  117958. * Gets or sets the texture being displayed on the sphere
  117959. */
  117960. get: function () {
  117961. return this._photoTexture;
  117962. },
  117963. set: function (value) {
  117964. if (this._photoTexture === value) {
  117965. return;
  117966. }
  117967. this._photoTexture = value;
  117968. if (this._useDirectMapping) {
  117969. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117970. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117971. this._material.diffuseTexture = this._photoTexture;
  117972. }
  117973. else {
  117974. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  117975. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  117976. this._material.reflectionTexture = this._photoTexture;
  117977. }
  117978. },
  117979. enumerable: true,
  117980. configurable: true
  117981. });
  117982. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  117983. /**
  117984. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  117985. * Also see the options.resolution property.
  117986. */
  117987. get: function () {
  117988. return this._material.fovMultiplier;
  117989. },
  117990. set: function (value) {
  117991. this._material.fovMultiplier = value;
  117992. },
  117993. enumerable: true,
  117994. configurable: true
  117995. });
  117996. /**
  117997. * Releases resources associated with this node.
  117998. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  117999. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118000. */
  118001. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118002. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118003. this._photoTexture.dispose();
  118004. this._mesh.dispose();
  118005. this._material.dispose();
  118006. this.onLoadErrorObservable.clear();
  118007. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  118008. };
  118009. return PhotoDome;
  118010. }(BABYLON.TransformNode));
  118011. BABYLON.PhotoDome = PhotoDome;
  118012. })(BABYLON || (BABYLON = {}));
  118013. //# sourceMappingURL=babylon.photoDome.js.map
  118014. var BABYLON;
  118015. (function (BABYLON) {
  118016. /** @hidden */
  118017. var _OcclusionDataStorage = /** @class */ (function () {
  118018. function _OcclusionDataStorage() {
  118019. /** @hidden */
  118020. this.occlusionInternalRetryCounter = 0;
  118021. /** @hidden */
  118022. this.isOcclusionQueryInProgress = false;
  118023. /** @hidden */
  118024. this.isOccluded = false;
  118025. /** @hidden */
  118026. this.occlusionRetryCount = -1;
  118027. /** @hidden */
  118028. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  118029. /** @hidden */
  118030. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  118031. }
  118032. return _OcclusionDataStorage;
  118033. }());
  118034. BABYLON.Engine.prototype.createQuery = function () {
  118035. return this._gl.createQuery();
  118036. };
  118037. BABYLON.Engine.prototype.deleteQuery = function (query) {
  118038. this._gl.deleteQuery(query);
  118039. return this;
  118040. };
  118041. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  118042. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  118043. };
  118044. BABYLON.Engine.prototype.getQueryResult = function (query) {
  118045. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  118046. };
  118047. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  118048. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118049. this._gl.beginQuery(glAlgorithm, query);
  118050. return this;
  118051. };
  118052. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  118053. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118054. this._gl.endQuery(glAlgorithm);
  118055. return this;
  118056. };
  118057. BABYLON.Engine.prototype._createTimeQuery = function () {
  118058. var timerQuery = this.getCaps().timerQuery;
  118059. if (timerQuery.createQueryEXT) {
  118060. return timerQuery.createQueryEXT();
  118061. }
  118062. return this.createQuery();
  118063. };
  118064. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  118065. var timerQuery = this.getCaps().timerQuery;
  118066. if (timerQuery.deleteQueryEXT) {
  118067. timerQuery.deleteQueryEXT(query);
  118068. return;
  118069. }
  118070. this.deleteQuery(query);
  118071. };
  118072. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  118073. var timerQuery = this.getCaps().timerQuery;
  118074. if (timerQuery.getQueryObjectEXT) {
  118075. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  118076. }
  118077. return this.getQueryResult(query);
  118078. };
  118079. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  118080. var timerQuery = this.getCaps().timerQuery;
  118081. if (timerQuery.getQueryObjectEXT) {
  118082. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  118083. }
  118084. return this.isQueryResultAvailable(query);
  118085. };
  118086. BABYLON.Engine.prototype.startTimeQuery = function () {
  118087. var caps = this.getCaps();
  118088. var timerQuery = caps.timerQuery;
  118089. if (!timerQuery) {
  118090. return null;
  118091. }
  118092. var token = new BABYLON._TimeToken();
  118093. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118094. if (caps.canUseTimestampForTimerQuery) {
  118095. token._startTimeQuery = this._createTimeQuery();
  118096. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  118097. }
  118098. else {
  118099. if (this._currentNonTimestampToken) {
  118100. return this._currentNonTimestampToken;
  118101. }
  118102. token._timeElapsedQuery = this._createTimeQuery();
  118103. if (timerQuery.beginQueryEXT) {
  118104. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118105. }
  118106. else {
  118107. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118108. }
  118109. this._currentNonTimestampToken = token;
  118110. }
  118111. return token;
  118112. };
  118113. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  118114. var caps = this.getCaps();
  118115. var timerQuery = caps.timerQuery;
  118116. if (!timerQuery || !token) {
  118117. return -1;
  118118. }
  118119. if (caps.canUseTimestampForTimerQuery) {
  118120. if (!token._startTimeQuery) {
  118121. return -1;
  118122. }
  118123. if (!token._endTimeQuery) {
  118124. token._endTimeQuery = this._createTimeQuery();
  118125. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  118126. }
  118127. }
  118128. else if (!token._timeElapsedQueryEnded) {
  118129. if (!token._timeElapsedQuery) {
  118130. return -1;
  118131. }
  118132. if (timerQuery.endQueryEXT) {
  118133. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  118134. }
  118135. else {
  118136. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  118137. }
  118138. token._timeElapsedQueryEnded = true;
  118139. }
  118140. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118141. var available = false;
  118142. if (token._endTimeQuery) {
  118143. available = this._getTimeQueryAvailability(token._endTimeQuery);
  118144. }
  118145. else if (token._timeElapsedQuery) {
  118146. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  118147. }
  118148. if (available && !disjoint) {
  118149. var result = 0;
  118150. if (caps.canUseTimestampForTimerQuery) {
  118151. if (!token._startTimeQuery || !token._endTimeQuery) {
  118152. return -1;
  118153. }
  118154. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  118155. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  118156. result = timeEnd - timeStart;
  118157. this._deleteTimeQuery(token._startTimeQuery);
  118158. this._deleteTimeQuery(token._endTimeQuery);
  118159. token._startTimeQuery = null;
  118160. token._endTimeQuery = null;
  118161. }
  118162. else {
  118163. if (!token._timeElapsedQuery) {
  118164. return -1;
  118165. }
  118166. result = this._getTimeQueryResult(token._timeElapsedQuery);
  118167. this._deleteTimeQuery(token._timeElapsedQuery);
  118168. token._timeElapsedQuery = null;
  118169. token._timeElapsedQueryEnded = false;
  118170. this._currentNonTimestampToken = null;
  118171. }
  118172. return result;
  118173. }
  118174. return -1;
  118175. };
  118176. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  118177. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  118178. };
  118179. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  118180. get: function () {
  118181. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  118182. },
  118183. enumerable: false,
  118184. configurable: true
  118185. });
  118186. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  118187. get: function () {
  118188. if (!this.__occlusionDataStorage) {
  118189. this.__occlusionDataStorage = new _OcclusionDataStorage();
  118190. }
  118191. return this.__occlusionDataStorage;
  118192. },
  118193. enumerable: false,
  118194. configurable: true
  118195. });
  118196. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  118197. get: function () {
  118198. return this._occlusionDataStorage.isOccluded;
  118199. },
  118200. set: function (value) {
  118201. this._occlusionDataStorage.isOccluded = value;
  118202. },
  118203. enumerable: true,
  118204. configurable: true
  118205. });
  118206. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  118207. get: function () {
  118208. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  118209. },
  118210. set: function (value) {
  118211. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  118212. },
  118213. enumerable: true,
  118214. configurable: true
  118215. });
  118216. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  118217. get: function () {
  118218. return this._occlusionDataStorage.occlusionType;
  118219. },
  118220. set: function (value) {
  118221. this._occlusionDataStorage.occlusionType = value;
  118222. },
  118223. enumerable: true,
  118224. configurable: true
  118225. });
  118226. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  118227. get: function () {
  118228. return this._occlusionDataStorage.occlusionRetryCount;
  118229. },
  118230. set: function (value) {
  118231. this._occlusionDataStorage.occlusionRetryCount = value;
  118232. },
  118233. enumerable: true,
  118234. configurable: true
  118235. });
  118236. // We also need to update AbstractMesh as there is a portion of the code there
  118237. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  118238. var dataStorage = this._occlusionDataStorage;
  118239. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  118240. dataStorage.isOccluded = false;
  118241. return false;
  118242. }
  118243. var engine = this.getEngine();
  118244. if (engine.webGLVersion < 2) {
  118245. dataStorage.isOccluded = false;
  118246. return false;
  118247. }
  118248. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  118249. dataStorage.isOccluded = false;
  118250. return false;
  118251. }
  118252. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  118253. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  118254. if (isOcclusionQueryAvailable) {
  118255. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  118256. dataStorage.isOcclusionQueryInProgress = false;
  118257. dataStorage.occlusionInternalRetryCounter = 0;
  118258. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  118259. }
  118260. else {
  118261. dataStorage.occlusionInternalRetryCounter++;
  118262. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  118263. dataStorage.isOcclusionQueryInProgress = false;
  118264. dataStorage.occlusionInternalRetryCounter = 0;
  118265. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  118266. // if strict continue the last state of the object.
  118267. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  118268. }
  118269. else {
  118270. return false;
  118271. }
  118272. }
  118273. }
  118274. var scene = this.getScene();
  118275. if (scene.getBoundingBoxRenderer) {
  118276. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  118277. if (!this._occlusionQuery) {
  118278. this._occlusionQuery = engine.createQuery();
  118279. }
  118280. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  118281. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  118282. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  118283. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  118284. }
  118285. return dataStorage.isOccluded;
  118286. };
  118287. })(BABYLON || (BABYLON = {}));
  118288. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  118289. var BABYLON;
  118290. (function (BABYLON) {
  118291. /**
  118292. * Class used to generate noise procedural textures
  118293. */
  118294. var NoiseProceduralTexture = /** @class */ (function (_super) {
  118295. __extends(NoiseProceduralTexture, _super);
  118296. /**
  118297. * Creates a new NoiseProceduralTexture
  118298. * @param name defines the name fo the texture
  118299. * @param size defines the size of the texture (default is 256)
  118300. * @param scene defines the hosting scene
  118301. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  118302. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  118303. */
  118304. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  118305. if (size === void 0) { size = 256; }
  118306. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  118307. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  118308. _this._time = 0;
  118309. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  118310. _this.brightness = 0.2;
  118311. /** Defines the number of octaves to process */
  118312. _this.octaves = 3;
  118313. /** Defines the level of persistence (0.8 by default) */
  118314. _this.persistence = 0.8;
  118315. /** Gets or sets animation speed factor (default is 1) */
  118316. _this.animationSpeedFactor = 1;
  118317. _this.autoClear = false;
  118318. _this._updateShaderUniforms();
  118319. return _this;
  118320. }
  118321. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  118322. var scene = this.getScene();
  118323. if (!scene) {
  118324. return;
  118325. }
  118326. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  118327. this.setFloat("brightness", this.brightness);
  118328. this.setFloat("persistence", this.persistence);
  118329. this.setFloat("timeScale", this._time);
  118330. };
  118331. NoiseProceduralTexture.prototype._getDefines = function () {
  118332. return "#define OCTAVES " + (this.octaves | 0);
  118333. };
  118334. /** Generate the current state of the procedural texture */
  118335. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  118336. this._updateShaderUniforms();
  118337. _super.prototype.render.call(this, useCameraPostProcess);
  118338. };
  118339. /**
  118340. * Serializes this noise procedural texture
  118341. * @returns a serialized noise procedural texture object
  118342. */
  118343. NoiseProceduralTexture.prototype.serialize = function () {
  118344. var serializationObject = {};
  118345. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  118346. serializationObject.brightness = this.brightness;
  118347. serializationObject.octaves = this.octaves;
  118348. serializationObject.persistence = this.persistence;
  118349. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  118350. serializationObject.size = this.getSize().width;
  118351. serializationObject.generateMipMaps = this._generateMipMaps;
  118352. return serializationObject;
  118353. };
  118354. /**
  118355. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  118356. * @param parsedTexture defines parsed texture data
  118357. * @param scene defines the current scene
  118358. * @param rootUrl defines the root URL containing noise procedural texture information
  118359. * @returns a parsed NoiseProceduralTexture
  118360. */
  118361. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  118362. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  118363. texture.brightness = parsedTexture.brightness;
  118364. texture.octaves = parsedTexture.octaves;
  118365. texture.persistence = parsedTexture.persistence;
  118366. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  118367. return texture;
  118368. };
  118369. return NoiseProceduralTexture;
  118370. }(BABYLON.ProceduralTexture));
  118371. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  118372. })(BABYLON || (BABYLON = {}));
  118373. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  118374. var __assign = (this && this.__assign) || function () {
  118375. __assign = Object.assign || function(t) {
  118376. for (var s, i = 1, n = arguments.length; i < n; i++) {
  118377. s = arguments[i];
  118378. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  118379. t[p] = s[p];
  118380. }
  118381. return t;
  118382. };
  118383. return __assign.apply(this, arguments);
  118384. };
  118385. var BABYLON;
  118386. (function (BABYLON) {
  118387. /**
  118388. * This can helps recording videos from BabylonJS.
  118389. * This is based on the available WebRTC functionalities of the browser.
  118390. *
  118391. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  118392. */
  118393. var VideoRecorder = /** @class */ (function () {
  118394. /**
  118395. * Create a new VideoCapture object which can help converting what you see in Babylon to
  118396. * a video file.
  118397. * @param engine Defines the BabylonJS Engine you wish to record
  118398. * @param options Defines options that can be used to customized the capture
  118399. */
  118400. function VideoRecorder(engine, options) {
  118401. if (options === void 0) { options = null; }
  118402. if (!VideoRecorder.IsSupported(engine)) {
  118403. throw "Your browser does not support recording so far.";
  118404. }
  118405. var canvas = engine.getRenderingCanvas();
  118406. if (!canvas) {
  118407. throw "The babylon engine must have a canvas to be recorded";
  118408. }
  118409. this._canvas = canvas;
  118410. this._canvas.isRecording = false;
  118411. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  118412. var stream = this._canvas.captureStream(this._options.fps);
  118413. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  118414. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  118415. this._mediaRecorder.onerror = this._handleError.bind(this);
  118416. this._mediaRecorder.onstop = this._handleStop.bind(this);
  118417. }
  118418. /**
  118419. * Returns wehther or not the VideoRecorder is available in your browser.
  118420. * @param engine Defines the Babylon Engine to check the support for
  118421. * @returns true if supported otherwise false
  118422. */
  118423. VideoRecorder.IsSupported = function (engine) {
  118424. var canvas = engine.getRenderingCanvas();
  118425. return (!!canvas && typeof canvas.captureStream === "function");
  118426. };
  118427. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  118428. /**
  118429. * True wether a recording is already in progress.
  118430. */
  118431. get: function () {
  118432. return !!this._canvas && this._canvas.isRecording;
  118433. },
  118434. enumerable: true,
  118435. configurable: true
  118436. });
  118437. /**
  118438. * Stops the current recording before the default capture timeout passed in the startRecording
  118439. * functions.
  118440. */
  118441. VideoRecorder.prototype.stopRecording = function () {
  118442. if (!this._canvas || !this._mediaRecorder) {
  118443. return;
  118444. }
  118445. if (!this.isRecording) {
  118446. return;
  118447. }
  118448. this._canvas.isRecording = false;
  118449. this._mediaRecorder.stop();
  118450. };
  118451. /**
  118452. * Starts recording the canvas for a max duration specified in parameters.
  118453. * @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.
  118454. * @param maxDuration Defines the maximum recording time in seconds.
  118455. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  118456. * @return a promise callback at the end of the recording with the video data in Blob.
  118457. */
  118458. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  118459. var _this = this;
  118460. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  118461. if (maxDuration === void 0) { maxDuration = 7; }
  118462. if (!this._canvas || !this._mediaRecorder) {
  118463. throw "Recorder has already been disposed";
  118464. }
  118465. if (this.isRecording) {
  118466. throw "Recording already in progress";
  118467. }
  118468. if (maxDuration > 0) {
  118469. setTimeout(function () {
  118470. _this.stopRecording();
  118471. }, maxDuration * 1000);
  118472. }
  118473. this._fileName = fileName;
  118474. this._recordedChunks = [];
  118475. this._resolve = null;
  118476. this._reject = null;
  118477. this._canvas.isRecording = true;
  118478. this._mediaRecorder.start(this._options.recordChunckSize);
  118479. return new Promise(function (resolve, reject) {
  118480. _this._resolve = resolve;
  118481. _this._reject = reject;
  118482. });
  118483. };
  118484. /**
  118485. * Releases internal resources used during the recording.
  118486. */
  118487. VideoRecorder.prototype.dispose = function () {
  118488. this._canvas = null;
  118489. this._mediaRecorder = null;
  118490. this._recordedChunks = [];
  118491. this._fileName = null;
  118492. this._resolve = null;
  118493. this._reject = null;
  118494. };
  118495. VideoRecorder.prototype._handleDataAvailable = function (event) {
  118496. if (event.data.size > 0) {
  118497. this._recordedChunks.push(event.data);
  118498. }
  118499. };
  118500. VideoRecorder.prototype._handleError = function (event) {
  118501. this.stopRecording();
  118502. if (this._reject) {
  118503. this._reject(event.error);
  118504. }
  118505. else {
  118506. throw new event.error();
  118507. }
  118508. };
  118509. VideoRecorder.prototype._handleStop = function () {
  118510. this.stopRecording();
  118511. var superBuffer = new Blob(this._recordedChunks);
  118512. if (this._resolve) {
  118513. this._resolve(superBuffer);
  118514. }
  118515. window.URL.createObjectURL(superBuffer);
  118516. if (this._fileName) {
  118517. BABYLON.Tools.Download(superBuffer, this._fileName);
  118518. }
  118519. };
  118520. VideoRecorder._defaultOptions = {
  118521. mimeType: "video/webm",
  118522. fps: 25,
  118523. recordChunckSize: 3000
  118524. };
  118525. return VideoRecorder;
  118526. }());
  118527. BABYLON.VideoRecorder = VideoRecorder;
  118528. })(BABYLON || (BABYLON = {}));
  118529. //# sourceMappingURL=babylon.videoRecorder.js.map
  118530. var BABYLON;
  118531. (function (BABYLON) {
  118532. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  118533. if (replace === void 0) { replace = false; }
  118534. // Dispose existing light in replace mode.
  118535. if (replace) {
  118536. if (this.lights) {
  118537. for (var i = 0; i < this.lights.length; i++) {
  118538. this.lights[i].dispose();
  118539. }
  118540. }
  118541. }
  118542. // Light
  118543. if (this.lights.length === 0) {
  118544. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  118545. }
  118546. };
  118547. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  118548. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  118549. if (replace === void 0) { replace = false; }
  118550. if (attachCameraControls === void 0) { attachCameraControls = false; }
  118551. // Dispose existing camera in replace mode.
  118552. if (replace) {
  118553. if (this.activeCamera) {
  118554. this.activeCamera.dispose();
  118555. this.activeCamera = null;
  118556. }
  118557. }
  118558. // Camera
  118559. if (!this.activeCamera) {
  118560. var worldExtends = this.getWorldExtends();
  118561. var worldSize = worldExtends.max.subtract(worldExtends.min);
  118562. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  118563. var camera;
  118564. var radius = worldSize.length() * 1.5;
  118565. // empty scene scenario!
  118566. if (!isFinite(radius)) {
  118567. radius = 1;
  118568. worldCenter.copyFromFloats(0, 0, 0);
  118569. }
  118570. if (createArcRotateCamera) {
  118571. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  118572. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  118573. arcRotateCamera.wheelPrecision = 100 / radius;
  118574. camera = arcRotateCamera;
  118575. }
  118576. else {
  118577. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  118578. freeCamera.setTarget(worldCenter);
  118579. camera = freeCamera;
  118580. }
  118581. camera.minZ = radius * 0.01;
  118582. camera.maxZ = radius * 1000;
  118583. camera.speed = radius * 0.2;
  118584. this.activeCamera = camera;
  118585. var canvas = this.getEngine().getRenderingCanvas();
  118586. if (attachCameraControls && canvas) {
  118587. camera.attachControl(canvas);
  118588. }
  118589. }
  118590. };
  118591. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  118592. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  118593. if (replace === void 0) { replace = false; }
  118594. if (attachCameraControls === void 0) { attachCameraControls = false; }
  118595. this.createDefaultLight(replace);
  118596. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  118597. };
  118598. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  118599. if (pbr === void 0) { pbr = false; }
  118600. if (scale === void 0) { scale = 1000; }
  118601. if (blur === void 0) { blur = 0; }
  118602. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  118603. if (!environmentTexture) {
  118604. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  118605. return null;
  118606. }
  118607. if (setGlobalEnvTexture) {
  118608. if (environmentTexture) {
  118609. this.environmentTexture = environmentTexture;
  118610. }
  118611. }
  118612. // Skybox
  118613. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  118614. if (pbr) {
  118615. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  118616. hdrSkyboxMaterial.backFaceCulling = false;
  118617. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  118618. if (hdrSkyboxMaterial.reflectionTexture) {
  118619. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118620. }
  118621. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  118622. hdrSkyboxMaterial.disableLighting = true;
  118623. hdrSkyboxMaterial.twoSidedLighting = true;
  118624. hdrSkybox.infiniteDistance = true;
  118625. hdrSkybox.material = hdrSkyboxMaterial;
  118626. }
  118627. else {
  118628. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  118629. skyboxMaterial.backFaceCulling = false;
  118630. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  118631. if (skyboxMaterial.reflectionTexture) {
  118632. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118633. }
  118634. skyboxMaterial.disableLighting = true;
  118635. hdrSkybox.infiniteDistance = true;
  118636. hdrSkybox.material = skyboxMaterial;
  118637. }
  118638. return hdrSkybox;
  118639. };
  118640. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  118641. if (BABYLON.EnvironmentHelper) {
  118642. return new BABYLON.EnvironmentHelper(options, this);
  118643. }
  118644. return null;
  118645. };
  118646. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  118647. if (webVROptions === void 0) { webVROptions = {}; }
  118648. return new BABYLON.VRExperienceHelper(this, webVROptions);
  118649. };
  118650. })(BABYLON || (BABYLON = {}));
  118651. //# sourceMappingURL=babylon.sceneHelpers.js.map
  118652. 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\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\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(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\n#ifdef VELOCITY\nuniform mat4 previousWorldViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\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\n#ifdef VELOCITY\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\nvPreviousPosition=previousWorldViewProjection*vec4(position,1.0);\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 VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\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[POSITION_INDEX]=vec4(vPosition,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=(a-b)*0.5+0.5;\nvelocity*=0.5+0.5;\nvelocity=vec2(pow(velocity.x,3.0),pow(velocity.y,3.0));\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,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}","motionBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D velocitySampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nvec2 velocityColor=texture2D(velocitySampler,vUV).rg;\nvec2 velocity=vec2(pow(velocityColor.r,1.0/3.0),pow(velocityColor.g,1.0/3.0))*2.0-1.0;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\nresult+=texture2D(textureSampler,offset);\n}\n\ngl_FragColor=result/float(samplesCount);\n}\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"};
  118653. 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};"};
  118654. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  118655. globalObject["BABYLON"] = BABYLON;
  118656. //backwards compatibility
  118657. if(typeof earcut !== 'undefined') {
  118658. globalObject["Earcut"] = {
  118659. earcut: earcut
  118660. };
  118661. }
  118662. return BABYLON;
  118663. });